Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SSE and Websocket
I want to use Webscokets and SSE in django, I know i can do it with ASGI, uWSGI and for WebSockets Django Channels. My question is what is the difference between ASGI an uWSGI and which one is better solution in 2020 -
Django model attributes not getting displayed in html page
Apologies for the noobish question, I am new to Django and trying to make an e-commerce app. What I want to do, is that show users variations available for an item in the product page. I've created a model for variations, and added some variations in my admin panel, but when I'm trying to display those, it is not happening. I think the way I'm accessing it is wrong. Can anyone please help me solve the problem? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class Meta: unique_together = ( ('item', 'name') ) class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class Meta: unique_together = ( ('variation', 'value') ) My sinngle_product.html: The form part <h1 class="product-title">{{ item.title }}</h1> <a href="#"> <span class="badge purple mr-1">{{ object.get_category_display }}</span> </a> <span class="review-no text-danger">41 reviews</span> </div> {% if object.discount_price %} <h4 class="price">price: <del><span>${{ object.price }}</span></h4></del> <h4 class="price text-primary">current price: <span>${{ object.discount_price }}</span> <span class="badge badge-pill badge-warning">Limited Time Offer!</span> {% else %} <h4 class="price">current price: <span>${{ object.price }}</span> {% endif %} <p class="vote text-success"><strong>91%</strong> of buyers enjoyed this product! <strong>(87 votes)</strong></p> <form … -
GraphQL API export of Django project in SDL representation not possible anymore
I'm trying to export the GraphQL API of my backend server with python manage.py graphql_schema --schema <django-app>.schema.schema --out <django-project>/schema.graphql. The generated file contains the introspectable representation like exported with ... --out schema.json. I was able to output the SDL representation of this project before. It seems like a package I introduced later is the root cause ot this issue. I added the following GraphQL dependencies over time: graphene==2.1.8 graphene-django==2.8.0 graphene-django-cud==0.4.4 graphene-file-upload==1.2.2 graphene-subscriptions==1.0.2 graphql-core==2.3.1 graphql-relay==2.0.1 Had someone else this behavior as well and knows how to fix or workaround it? -
what is benefit of using Redis for my Django web app?
Actually i created a simple web app with Django. I want to use server-push functionality in my web app. I think this type of functionality can be achieved through WebSockets using Django-channels. But if I want to use WebSockets in Django-channels then I also need to run Redis server parallel as well but why I need to run Redis server.what is the use of Redis with Django-server I'm so confused. -
'Django-admin not recognized as a command'
So I wanted to try Django and as the tutorial said I went ahead and installed virtualenv. I create the venv and cd into it. Then i try to create a project inside it but i cant. I put the file inside PATH and tried once again "django-admin startproject [name of my project]" and got this error: 'django-admin' is not recognized as an internal or external command, operable program or batch file. And i know there are a couple of simular forums here on stack overflow already but as far as i saw nothing worked. -
how to combine or integrate reactjs and Django
I created front end in Reactjs and backend in Django and linked using Django rest API. but react runs in localhost:3000 and Django in localhost:8000. How to combine or integrate these two and runs in the same address. -
How do i set the length of like counts
i am new on Django and i am working on a website where users like posts. I have an issue on how i can set the length of like counts before 'Likes' will be removed and show only the like counts. When a user do not click on Like button it displays 'LIKE' at the side of like button, but when a user clicked on the like button it displays the like count to 1 without 'LIKE' at the side of the count, because i am using an else statement. How do i display 'LIKE' at the side of like count. For example; '1 Liked' Then when 100 users clicked on like button, like counts: '100'. But if it is less than 100, like count will be '99 Liked' enter image description here {% if post.liked_by_user %} <button type="submit" name="post_id" value="{{ post.id }}" class="like float-left pl-2" > <img src="{{ '/static/' }}images/heart_empty.png" width="24" height="24"> </button> {% if post.likes.all %} <a href="{% url 'site:likes_users' post.id %}" class="like-count font-small dark-grey-text font-weight-bold"> <span class="d-inline-block text-truncate" style="max-width:70px;position:relative;top:3px;"> {{ post.likes.count }} </span> </a> {% else %} <span class="like-count font-small dark-grey-text font-weight-bold">Like</span> {% endif %} {% endif %} -
How to refactor Django code automatically?
I have changed column name of a table. How can I automatically trigger refactoring so that all old name reference in my app is replaced by new name? -
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 :)