These are chat archives for django/django

13th
Oct 2017
djangoReactGuy
@SanskarSans
Oct 13 2017 03:56
anyone has experience with gis?
I could not store the values in PointField()
djangoReactGuy
@SanskarSans
Oct 13 2017 04:33
class RestaurantForm(forms.ModelForm):

    class Meta:
        model = Restaurant
        widgets = {'country': forms.HiddenInput(attrs={'id': 'country'}),
                   'location': forms.HiddenInput(attrs={'id': 'location'}),
                   'city': forms.HiddenInput(attrs={'id': 'locality'}),
                   'state': forms.HiddenInput(attrs={'id':
                                                     'administrative_area_level_1'}),
                   'postal_code': forms.HiddenInput(attrs={'id':
                                                           'postal_code'}), }
        fields = (
            "logo", "name", "cuisine", "phone", "location",
            "country", "city", "state", "postal_code",
        )

    def clean_location(self):
        print('self', self.cleaned_data)
        coordinates = self.cleaned_data['location']
        lat, lng = coordinates.split(', ', 1)
        return GEOSGeometry('POINT(' + lng + ' ' + lat + ')')
why is this not working?
location = gis_models.PointField(blank=True, null=True, geography=True)
 var place = autocomplete.getPlace();
        var latLng = place.geometry.location.lat() + "," + place.geometry.location.lng();
        document.getElementById('location').value = latLng;
if restaurant_form.is_valid():
        print(request.POST.get('location'))
        new_restaurant = restaurant_form.save(commit=False)
        new_restaurant.user = request.user
        new_restaurant.save()
I could not add restaurant when using location field otherwise it works
djangoReactGuy
@SanskarSans
Oct 13 2017 04:39
I am getting Invalid geometry value. error
djangoReactGuy
@SanskarSans
Oct 13 2017 04:49
if anyone can help, here is the code in detail

class Restaurant(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='restaurant'
    )
    name = models.CharField(max_length=500)
    phone = models.CharField(max_length=500)
    location = gis_models.PointField(blank=True, null=True, geography=True)

    gis = gis_models.GeoManager()
    objects = models.Manager()

class RestaurantForm(forms.ModelForm):

    class Meta:
        model = Restaurant
        widgets = {'country': forms.HiddenInput(attrs={'id': 'country'}),
                   'location': forms.HiddenInput(attrs={'id': 'location'}),
                   'city': forms.HiddenInput(attrs={'id': 'locality'}),
                   'state': forms.HiddenInput(attrs={'id':
                                                     'administrative_area_level_1'}),
                   'postal_code': forms.HiddenInput(attrs={'id':
                                                           'postal_code'}), }
        fields = (
            "logo", "name", "cuisine", "phone", "location",
            "country", "city", "state", "postal_code",
        )

    def clean_location(self):
        print('self', self.cleaned_data)
        coordinates = self.cleaned_data['location']
        lat, lng = coordinates.split(', ', 1)
        return GEOSGeometry('POINT(' + longitude + ' ' + latitude + ')')

if request.method == "POST":
    restaurant_form = RestaurantForm(request.POST, request.FILES)
    if restaurant_form.is_valid():
        print(request.POST.get('location'))
        new_restaurant = restaurant_form.save(commit=False)
        new_restaurant.user = request.user
        new_restaurant.save()

        return redirect(restaurant_order)


<script>
      var placeSearch, autocomplete;
      var componentForm = {
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'
      };

      function initAutocomplete() {
        autocomplete.addListener('place_changed', fillInAddress);
      }

      function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();
        var latLng = place.geometry.location.lat() + "," + place.geometry.location.lng();
        document.getElementById('location').value = latLng;
        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).disabled = false;
        }

        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
      }
</script>
djangoReactGuy
@SanskarSans
Oct 13 2017 06:21
I fixed this issue but how do I show something like following restaurant is '500m' away
djangoReactGuy
@SanskarSans
Oct 13 2017 07:04
Here is the code shortened
url(r'^nearby_restaurant/(?P<current_lat>-?\d*.\d*)/(?P<current_long>-?\d*.\d*)/$',
    views.nearby_restaurant_finder, name="nearby-restaurant"),

class Restaurant(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='restaurant'
    )
    name = models.CharField(max_length=500)
    restaurant_slug = models.SlugField(max_length=250, unique=True)
    location = gis_models.PointField(blank=True, null=True, geography=True)

    gis = gis_models.GeoManager()
    objects = models.Manager()

def nearby_restaurant_finder(request, current_lat, current_long):
    from django.contrib.gis.geos import Point
    from django.contrib.gis.measure import D
    user_location = Point(float(current_long), float(current_lat))
    distance_from_point = {'km': 50}
    restaurants = Restaurant.gis.filter(
        location__distance_lte=(user_location, D(**distance_from_point)))
    restaurants = restaurants.distance(user_location).order_by('distance')
    context = {
        'restaurants': restaurants
    }
    return render(request, 'restaurant/nearby_restaurant.html', context)
kpagcha
@kpagcha
Oct 13 2017 10:23
hey guys quick question, I am having some db problems when running tests and it seems to do with auth_user or auth.User. Is auth.Usera thing in Django? Or is it an app in my project? (I just can find it anywhere, but it is referenced in some places). There is another inconsistency: getattr(settings, 'AUTH_USER_MODEL') returns auth.User but django.contrib.auth.get_user_model() returns django.contrib.auth.models.User. Can anyone help out?
Luke-VideoLibre
@LukeVideo
Oct 13 2017 11:44
I have auth_user in my current django project .
User is a django thing to. It's the build in that is used in the admin panel.
kpagcha
@kpagcha
Oct 13 2017 11:51
so auth.User is the same than django.contrib.auth.models.User?
Luke-VideoLibre
@LukeVideo
Oct 13 2017 11:52
@kpagcha It seems this is usefull if you customize your user with a specifique model. It returns that custom model if it exists else juest the User model
kpagcha
@kpagcha
Oct 13 2017 11:53
@LukeVideo yeah I do get the point of getattr(settings, 'AUTH_USER_MODEL') and django.contrib.auth.get_user_model(). What I am trying to figure out is whether auth.User and django.contrib.auth.models.User are the same or represent the same model
Luke-VideoLibre
@LukeVideo
Oct 13 2017 12:04
Not sure... Looks like it. Is one the instance and the other the model ?
kpagcha
@kpagcha
Oct 13 2017 12:09
@LukeVideo django.contrib.auth.models.User is a class and auth.User a string
Luke-VideoLibre
@LukeVideo
Oct 13 2017 12:12
That makes sense.
djangoReactGuy
@SanskarSans
Oct 13 2017 12:14
anyone know about postgis?
emihir0
@emihir0
Oct 13 2017 13:12
In my views (using CBV) I often come along a scenario where I need to refer to foreign key instances. For example 'show list of books belonging to author'. I want to be able to access the author by doing view.author in my template and so I usually define @property author which looks up _author field, if it's empty, get it and return the _author (so we don't hit DB constantly every time view.author is looked up). I made a workaround for this which works quite nice. In my view I simply do something like: class AuthorBookList(ListView): author = ModelInstance(models.Author); and the ModelInstance is as follows:
class ModelInstance(object):
def init(self, object_model, object_pk=None):
self.data = WeakKeyDictionary()
self._object_model = object_model
self._object_pk = f'{object_model.name.lower()}_pk' if object_pk is None else object_pk
def __get__(self, instance, owner):
    obj = self.data.get(instance)
    if obj is None:
        obj = get_object_or_404(self._object_model, pk=instance.kwargs.get(self._object_pk))
        self.data[instance] = obj
    return obj
Is there an argument against using something like this?
Of course a set method could be defined as well; but for this simple usecase it's pointless as it's always going to be a simple lookup based on kwargs supplied. An url would look something like '(?P<author_pk>.+)/books/$'