Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React-Native post geometry object to a GIS database via Django API
I am trying to use axios to create a post to a GIS database that is created using Django. The problem is that I have a geometry point in my model and in my front-end app I only have the coordinates. So now, my question is how to create a POST request to a table that contains Geometry object? Here is what I have for the moment: Django model: class Place(geomodel.Model): place_name = geomodel.CharField(max_length=256) description = geomodel.TextField(blank=True) picture = models.ImageField(blank=True) place_type = models.ForeignKey(PlaceType, on_delete=models.CASCADE) geom = geomodel.PointField() approved = models.BooleanField(default=False) telephone = models.CharField(max_length=256) rating = models.IntegerField() numberOfVotes = models.IntegerField() createdBy = models.ForeignKey(RegisteredUsers, on_delete=models.CASCADE) def __str__(self): return self.place_name Django serializer: PlaceSerializer(GeoFeatureModelSerializer): place_comments = CommentSerializer(many = True, required=False) dis = serializers.DecimalField(source='distance.m', required=False, read_only=True, max_digits=10, decimal_places=2) class Meta: model = Place geo_field = "geom" fields = ("id", "place_name", 'description', 'picture', 'place_type', 'dis', 'approved', 'place_comments') Django view: PlaceViewSet(viewsets.ModelViewSet): queryset = Place.objects.all().filter(approved=True) serializer_class=DogPlaceSerializer def get_queryset(self): qs = super().get_queryset() latitude = self.request.query_params.get('lat', None) longitude = self.request.query_params.get('lng', None) distance = self.request.query_params.get('dist', None) if latitude and longitude: pnt = geos.GEOSGeometry('POINT(' + str(longitude) + ' ' + str(latitude) + ')', srid=4326) if distance: qs = DogPlace.objects.all().filter(geom__dwithin=(pnt, distance)) qs = qs.annotate(distance=Distance('geom', pnt)).order_by('distance') return qs and in the front end: const … -
Customer instance has invalid ID: None, <class 'NoneType'>. ID should be of type `str` (or `unicode`)
am trying to create a stripe card but am having this error "Could not determine which URL to request: Customer instance has invalid ID: None, . ID should be of type str (or unicode)" this is my view.py ''' def index(request): # if request.user.is_authenticated: # billing_profile=request.user.billingprofile # my_customer_id=billing_profile.customer_id billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if not billing_profile: return redirect("carts:cart_view ") next_url = None next_ = request.GET.get('next') if is_safe_url(next_, request.get_host()): next_url=next_ return render(request, 'my_index.html',{"next_url":next_url}) def charge(request): if request.method == 'POST': print('Data:', request.POST) # stripe.Customer.create( # email=request.POST['email'], # # ) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) token = request.POST.get('stripeToken') if token is not None: customer = stripe.Customer.retrieve(billing_profile.customer_id) card_response=customer.sources.create(source=token) print(card_response) return redirect(reverse('Payments:success')) def successMsg(request): return render(request, 'my_success.html') this is my model.py class BillingProfileManager(models.Manager): def new_or_get(self,request): user=request.user guest_email_id = request.session.get('guest_email_id') created=False obj=None if user.is_authenticated: # logged in user checkout ;remember payement stuff obj, created=self.model.objects.get_or_create( user=user, email=user.email ) elif guest_email_id is not None: # logged in user checkout, auto reload payement stuff guest_email_obj = GuestEmail.objects.get(id=guest_email_id) obj, created = BillingProfile.objects.get_or_create( email=guest_email_obj.email) else: pass return obj,created class BillingProfile(models.Model): user=models.OneToOneField(User,unique=True,null=True,blank=True,on_delete='CASCADE') email=models.EmailField() active=models.BooleanField(default=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) customer_id=models.CharField(max_length=120,null=True,blank=True) objects=BillingProfileManager() def __str__(self): return self.email def billing_profile_created_receiver(sender,instance,*args,**kwargs): if not instance.customer_id and instance.email and instance.user: print("Actual api request send to stripe/braintree") customer=stripe.Customer.create( email=instance.email, name=instance.user, … -
Django Rest Framework default_authentication_classes setting
I am using Django Rest Framework (3.11) with Django (3.0). I have successfully implemented JWT authentication for my API. In the settings.py file, I have the following: # Rest framework configuration REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSIONS_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } Removing 'rest_framework.authentication.BasicAuthentication', results in the following error when hitting any of the endpoints in the API: TypeError at / 'type' object is not iterable Does this mean the BasicAuthentication class is required for the application to run? Or is this not normal and I have a configured something incorrectly somewhere? -
Django - Static files partially loading
I have the following static folder in my Django project: On all of my html pages, I write the following: {% extends "app_base.html" %} {% load static %} {% block app %} When I run server, the static pages load partially, I know this by inspecting element on chrome: I tried running $ python manage.py collectstatic mentioned in the docs, didn't help. I can load each static file individually as in: {% load static %} <script src="{% static 'js/my.js' %}"></script> I've had django projects in the past where { % load static % } is all i need, curious why it isn't working in this instance. -
Nested Query / not directly related field in Django
If the models are as follows, class Subject(BaseModel): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Meta: managed = True db_table = 'Subject' class Topic(BaseModel): name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=False, related_name='subject_topic') class Meta: managed = True db_table = 'Topic' class Question(BaseModel): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=False, related_name='question_topic') class Meta: managed = True db_table = 'Question' How can I make a query Question for a subject. questions = Question.objects.filter(topic_in=Topic.objects.get(subject=subject).only('id').all()) but it's not working. Any help would be really great help. -
How to run management commands from the Django admin dashboard
I have created some of my custom management commands in Django, so my question here is how to run those commands from the admin interface. -
Django Admin - Change field model and automatically update another model
Well, I have a VagasUsuarios model and a Questionario model. I would like that when I updated the Questionario.pontuacao_questionario field via django admin, my other VagaUsuarios.pontuacao_vaga field would be updated as well. Is there a way to do this? thanks for listening =) My Models: class Questionario(models.Model): usuario = models.ForeignKey(Contas, on_delete=models.CASCADE) [...] pontuacao_questionario = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True,verbose_name="Pontuacao do Questionário") class VagasUsuarios(models.Model): usuario = models.ForeignKey(Contas, on_delete=models.CASCADE) [...] pontuacao_vaga = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="Pontuacao da Vaga") -
How to get the value of variables individually from property in Django
It is difficult for me to formulate this question, so i'll try to show what i mean. I have a property def count_tax_rate(self): if self.deposit_value > 100: Deposits.objects.update(tax_rate=self.tax_rate+10) return self.tax_rate + 10 count_tax_rate.short_description = "Tax rate" tax_rate_property = property(count_tax_rate) Then i connect this property to my admin.ModelAdmin form. And in my admin panel this gives me Tax rate = 10 But i need to calculate and show more than one variable in my admin panel. I tried to rewrite my property function def count_tax_rate(self): if self.deposit_value > 100: Deposits.objects.update(tax_rate=self.tax_rate+10, total_income=self.deposit_value+100) return self.tax_rate + 10, self.deposit_value + 100 count_tax_rate.short_description = "Tax rate" tax_rate_property = property(count_tax_rate) But it gives me this Tax rate = (Decimal('10.00'), 200) I understand that this is the way property works. Is there any way to get multiple values from one property function or am i have to look for a completely different solution? -
Schema problem: relation "django_session" does not exist
There are many questions about the same error here in StackOverflow but I couldn't find the same case. Basically I got the following error: ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ The reason that I got this error is that I am using Schema in my DATABASES settings: DATABASE_SCHEMA = 'my_schema' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': f'-c search_path={DATABASE_SCHEMA}' }, 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('USER'), 'PASSWORD': os.environ.get('PASS'), 'HOST': os.environ.get('DB_LINK'), 'PORT': os.environ.get('DB_PORT', '5432'), 'TEST': { 'NAME': os.environ.get('DB_NAME'), }, } When I migrate my database, it generates all Django tables to the correct Schema. But when I execute the project, Django tried to fetch its tables without the schema name so it cannot find the tables. Django Version: Django==3.0.5 Psycopg2 Version: psycopg2-binary==2.8.5 -
Django View Skipping a return statement
def blockdata(request,districtid): #in the template, we already passed the districtid from index view to form and back here. if request.method=="POST" and 'send' in request.POST: blockid=request.POST.get('selected','') elif request.method=="POST" and 'search' in request.POST: **print('hey i got your request.')** return HttpResponseRedirect(reverse('drilldown')) else: blockid=request.session['blockid'] total_population=Population.objects.filter(districtname=districtid,talukname=blockid).count()#population of district total_males=Population.objects.filter(districtname=districtid,talukname=blockid,gender='M').count()#males in district malestopop=total_males/total_population total_females=Population.objects.filter(districtname=districtid,talukname=blockid,gender='F').count()#females in district femalestopop=total_females/total_population total_vulnerable=Population.objects.filter(districtname=districtid,talukname=blockid,total__gt=0).count()#total vulnerable in district vultopop=total_vulnerable/total_population total_over_60=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60).count()#population of district >=60 over60topop=total_over_60/total_population total_over_60_vul=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0).count()#population of district >=60 & vulnerable over60andvul=total_over_60_vul/total_over_60 total_over_60_vul_male=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0,gender='M').count()#population of district >=60 & vulnerable & male over60malevul=total_over_60_vul_male/total_over_60 total_over_60_vul_female=Population.objects.filter(districtname=districtid,talukname=blockid,age__gte=60,total__gt=0,gender='F').count()#population of district >=60 & vulnerable & female over60femalevul=total_over_60_vul_female/total_over_60 phcs=Population.objects.filter(districtname=districtid,talukname=blockid).values_list('phcname',flat=True).distinct()#unique taluks context={'blockid':blockid, 'districtid':districtid, 'total_pop': total_population, 'male_pop': round((malestopop*100)), 'female_pop': round((femalestopop*100)), 'total_vul': round((vultopop*100)), 'over60': round((over60topop*100)), 'over60vul':round((over60andvul*100)), 'over60vul_male':round((over60malevul*100)), 'over60vul_female':round((over60femalevul*100)), 'blocks':phcs} return render(request,'ashadrill/base.html',context) Above is a view function. Below is my app's urls.py urlpatterns = [ path('',views.index,name='index'), path('<slug:districtid>/',views.blockdata,name='blockdata'), path('<slug:districtid>/<slug:blockid>/',views.phcdata,name='phcdata'), path('<slug:districtid>/<slug:blockid>/<slug:phcid>/',views.centerdata,name='centerdata'), path(r'<slug:districtid>/<slug:blockid>/<slug:phcid>/(?P<centerid>[-\w.]+)/$',views.villagedata,name='villagedata'), path('drilldown/',views.drilldown,name='drilldown') In the above view function called blockdata, when my condition is true, it does print the print statement. But instead of return a reverse('drilldown') function, it ignores the return statement and just carries on with the rest of the code as if there is no return statement. I do have a view called 'drilldown' def drilldown(request): return HttpResponse(200) I am not sure why it is skipping the return of redirect. I have also tried with … -
getting problem in importing libraries in Django
I'm getting this error even tho I have installed pylint in the environment it still showing this error -
what does it take to upload a large file on heroku?
I am trying to upload a video on a Django server hosted on heroku; it is not working but when uploading a picture it works. I am also using AWS to store my files. Is that i am using heroku free? -
How to add actions to admin page with non-ascii charecters
I have this code which works fine in Django admin page, but is there a way to keep action name in Russian but function name in English? actions = ["Отправить_сообщение"] # add action to list page def Отправить_сообщение(self, request, queryset): pass cheers -
How can i handle multiple form classes in a single page in django?
I basically need to design a web page that takes in multiple input (split into different classes) from a user and submit it and redirect to next page,(i.e 5 classes in a single page with only 1 submit button). How do i approach this in django models forms and views ? -
Django - Field 'id' expected a number but got 'WUIbt'
I'm working on an online quiz. I don't want my users to be able to access questions by typing "/questions/1" so I need random ID. I created a function that returns a random string (eg 'WUIbt'): def random_id(): char = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJQLMNOPQRSTUVWXY" id_len = 5 question_id = "".join(random.sample(char, id_len)) return question_id Then I use it in my question model : class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) id = models.AutoField(primary_key=True, default=random_id, editable=False, max_length=5) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' But when I create a question, I have a Field 'id' expected a number but got 'WUIbt' error. Here is the form, in case you need it : class Form_Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de la question') class Meta: model = Question_Num fields = ['num_question', 'question', 'reponse'] Should I generate a random number that I transform in hexadecimal or is it possible to create a string id ? -
Shopify Django App: printf: warning: ignoring excess arguments, starting with ‚;‘
Used python version: 3.7 and 3.8 I am trying to follow the official instruction from Shopify (in readme.md) to start a Django Shopify App: https://github.com/Shopify/shopify_django_app By step 2 in „Setup environment „, what look like that: Generate a secret key and add it to .env by running the following in the command line: printf 'DJANGO_SECRET=' >> .env; python -c 'import random; print("".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50)]))' >> .env I am getting a warning: printf: warning: ignoring excess arguments, starting with ‚;‘ After running the command my .env file look like that: SHOPIFY_API_KEY=“1111111111111111” SHOPIFY_API_SECRET=“11111111111111”DJANGO_SECRET= if course that generate me any key, what follow an error by trying to start a server on the next step from the instruction. What I am doing wrong and why is not generating the key for me. Thank you in advance -
Can we use class as view in django?
view.py class myapp(): def index(self): return redirect(someusrl) def productview(self): return redirect(someusrl) urls.py path('', myapp.index, name="home"), path('product', myapp.productview, name="Product_page") like this way thanks in advance :) -
django + chart.js: page language switch button mess up the charts. What?
I am having a super strange issue in my django app that renders graphs with chart js. I used i18n to handle the translation but after spending hours trying to fix my charts, I found out that when language is english the chart work well but when another language is selected, then it either dont work or show messed up values. I don't even know what code to include since I can't figure out how lanaguage and the chart.js are related. Has someone had the same issue before? Or any clue how this could come from? -
ModelForm is not being saved, database fields are empty
i made ModelForm for booking. When i pass the data to the form, no errors are being shown and i think it is being executed successfully. But when i check the database nothing is being saved. here is my code. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = models.DateTimeField(default=timezone.now) visittime = models.TimeField(default=timezone.now) reason = models.TextField() poc = models.CharField(max_length=50) site = models.CharField(max_length=6, choices=choice_field) slug = models.SlugField(unique_for_date=timezone.now) form.py class booking(forms.ModelForm): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = forms.DateTimeField(required=True) visittime = forms.TimeField(required=True) reason = forms.CharField(widget=forms.Textarea, required=True) poc = forms.CharField(max_length=50) site = forms.MultipleChoiceField(choices=choice_field, widget=forms.NullBooleanSelect) class Meta: model = Post fields = ("visitdate", "visittime", "reason", "poc", "site",) views.py @login_required def dashboard(request): lu = request.user form = booking() if request.method == "POST": form = booking(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return render(request, 'account/dashboard.html', {'lu':lu, 'booking': form}) dashboard.html <form method="POST"> {%csrf_token%} <div class="ff"> <div align='center'> <select class="selector" {{booking.site}}</select> </div> <br> <div align='center'> <input type="date" class="datetime" placeholder="Date" {{booking.visitdate}} <input type="time" class="datetime" placeholder="Time" {{booking.visittime}} </div> <br> <input type="text" class="credentials" placeholder="Point of Contact" {{booking.poc}} … -
format method does not assign values to a string when importing as global variable
I defined some variables inside a file named queries.py and import them inside another file named views.py. The problem is python format does not assign values of each variable to the corresponding placeholder. Consider following lines of code : queries.py main_where_query = ''' where users.deleted_account is null and length(users.phone_number) > 2 and length(users.phone_number) < 20 and users.phone_number not like '+98888888%' ''' messages_where_query = """{0} and messages.date>'{1}' and messages.date<'{2}' """ views.py from .queries import * def get_activity(request): global main_where_query global messages_where_query messages_where_query.format(main_where_query, str(start_date), str(end_date)) .... and the output is : select count(messages.message_id) from messages join users on users.id = messages.sender {0} and messages.date>'{1}' and messages.date<'{2}' and messages.media_type = 0 As you can see all the placeholders are untouched like {0} {1} {2}.I'm sure that those variables are not empty and imported correctly. -
Django rest framework filter not working. Always giving full queryset or data on any filrer query
I making a filter API but no matter what filter I apply it doesn't give me any result. class filter_dataset(ListCreateAPIView): filter_class = ProductFilter serializer_class = AdjustDatasetSerializers filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('revenue', 'spend', 'OS', 'date') def get_queryset(self): dataset = Dataset.objects.all() return dataset def get(self, request): dataset = self.get_queryset() serializer = self.serializer_class(dataset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) models: from django.db import models class Dataset(models.Model): date = models.DateTimeField(max_length=255,auto_now_add=True) channel = models.CharField(max_length=255,null=True, blank=True) OS = models.CharField(max_length=255,null=True, blank=True) impressions = models.CharField(max_length=255,null=True, blank=True) clicks = models.CharField(max_length=255,null=True, blank=True) installs = models.CharField(max_length=255,null=True, blank=True) spend = models.CharField(max_length=255,null=True, blank=True) revenue = models.CharField(max_length=255,null=True, blank=True) Filter class: class ProductFilter(filters.FilterSet): revenue = filters.NumberFilter(field_name="revenue") spend = filters.NumberFilter(field_name="spend") OS = filters.CharFilter(field_name='OS', lookup_expr='OS__exact') date = filters.DateFromToRangeFilter(field_name='date') class Meta: model = Dataset fields = ['revenue', 'spend', 'OS', 'date'] On django rest framework filter fields are showing but no matter what you enter in field this is not giving any results. All was all the data is shown. I'm stuck on this, any help would be needful. -
Class XXX missing "Meta.model" attribute
I Trying get list of objects using DRF, But Getting Error like "missing "Meta.model attribute" Serialzers.py from rest_framework import serializers from .models import Car class CarSerializer(serializers.ModelSerializer): class Meta: model: Car fields=['brand_name','model_name','car_color'] Views.py Code Below: from app2.serializers import CarSerializer from rest_framework import generics class BrandList(generics.ListCreateAPIView): queryset = Brand.objects.all() serializer_class = CarSerializer URLS.py: from app2.views import ,BrandList path("BrandList/", BrandList.as_view(), name="BrandList"), Please someone get out from this -
In what order does celery process tasks when it is configured to use multiple queues?
If I run celery so that it consumes from multiple queues, what order will it process tasks? Given the following startup: celery worker -A app --concurrency=4 --pool=prefork -Ofair --queues=default,lowpriority,highpriority If 1000 tasks get added to the default queue, then 1000 tasks are added to the lowpriority queue, then 1000 tasks are added to the highpriority, in what order are those tasks processed? I think they will be processed in an approximate arrival order: 1000 from default, then 1000 from lowpriority, then 1000 from highpriority. What I would like to happen is a round robin processing style: 1 from default, 1 from lowpriority, 1 from highpriority ... I am aware of Task Priorities but would prefer to avoid them at this stage, because that is a larger migration that requires more planning. Can I get celery to process tasks from multiple queues in a round-robin style? -
Django ORM group by calculation should return data if the foreign have no related data too
This is my models: class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name='ledger_entry_for', ) For example, i have 400+ users but only 50 users have purchased multiple time So i want total purchase amount user by user. so this is my query is below: purchase_user_wise = Purchase.objects.values( 'entry_for' ).annotate( total_purchase=Sum('amount') ) Above query works nice and I return total amount user by user but the problem is: it only return those users calculation who have purchased at least one time or more than one time. and this query not returning all 400 users data. I want, if any of the users don't have any purchase entry, it should return 0 and rest of the calculation should be works that way. Can anyone help me how can i do it? -
What is the most efficient way to create a lobby django
I am trying to create a lobby that would be accessible by a link game/gameID. What i have is just a simple field in my db playerNumber = models.IntegerField(default =0). When user is connected i increment playerNumber by 1. When the player number is 2 i just render error page. But when user closes game page by some mistake, someone else can join instead of him. How would i make this page IP specific or somehow reserve the page for only 2 users and make them able to come back if they left.