Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why error message showing up on admin page, not in the current page(django)?
I created an error message if no checkboxes are selected on django template. But when i try to submit it, the error message showing up on admin page, not in the current page. It is a private project so i can show you this much. Thanks. Here is my code; if len(checkboxes)<=0: messages.error(request, 'error') return render(request, "cve.html",{"config":c, "cve_results": cve_result,"team": team_result}) -
My django's app server processing time is way bigger than laptop processing time
I have a django app that use image processing and ocr (detecting an ID card, reading all the informations on it) and I have it hosted on a personal server. The processing time on my laptop (if I run the app with runserver) is 15 seconds. The processing time on the server is 30 seconds. The server is operating Windows server. My application is running on a Ubuntu virtual machine (with dynamic RAM memory allocation) in the Windows server. The server specifications: 2x Intel(R) Xeon(R) E5450 3.00GHz 4 cores 32 GB RAM The laptop specifications: Intel Core i7 6700HQ 2.6ghz 4 cores 8 GB RAM The server is way better than my laptop. Do you know why does the app runs slower hosted on the server? -
Which one do you prefer, Laravel or Django? And Why? [closed]
I want to select a web script framework for my project. And I got stuck between Laravel and Django. Which would you prefer and why? Thank you. -
How to show last N data
For example I have 5 row with data in my db and when I want to show first 3 row in my html I'm using for loop with slice like {% for x in y|slice:":3" %}. But now my question is how to show last 3 row from db. -
Django remove certain parameter from GET
I am doing filter using GET method and i would like to be able to remove only specific filters, how do I do that? Now i have a form with token fields so I get id's of countries and towns: <form id="search" method="GET" action="{% url 'selection'%}"> <div class="bg-grey text-center"> <input type="text" class="form-control" id="tokenfield1" name="country"> </div> {% if filteredcountries %} <table class="table table-list"> {% for c in filteredcountries %} <tr> <td><button type="button" class="btn btn-xs btn-danger" data-remove="{{c.id}}"><i class="fas fa-times"></i></button></td> <td>{{c.country_name`}}</td> </tr> {% endfor %} </table> {% endif %} <div class="bg-grey text-center"> <input type="text" class="form-control" id="tokenfield2" name="town"> </div> {% if filteredtowns %} <table class="table table-list"> {% for t in filteredtowns %} <tr> <td><button type="button" class="btn btn-xs btn-danger" data-remove="{{t.id}}"><i class="fas fa-times"></i></button></td> <td>{{t.town_name}}</td> </tr> {% endfor %} </table> {% endif %} views.py: def defense_planning(request): countries = request.GET.get('country') if not countries: countries = [] else: countries = countries.split(', ') towns = request.GET.get('town') if not towns: towns = [] else: towns = towns.split(', ') results = Hotel.objects.filter(Q(town_id__in = towns) | Q(country_id__in = countries)) context = { 'filteredcountries': countries, 'filteredtowns': towns, 'hotels': results } return render(request, 'myapp/hotels.html', context) Now I want to click the button and remove the specific town or country from the GET and remain the … -
python manage.py runserver error in MAC OS
I just started using Django for a web app project and I am going through the elasticsearch in django but when I run the python manage.py runserver from the defualt mysite directory I get the following error. zsh: abort python maange.py runserver -
How to prevent a field from being "removed" from the model once you turn it into a property in Django?
I have a field that is a property, because it's the average of all reviews: ratings = models.FloatField(null=True, default=0) @property def ratings(self): return self.reviews.aggregate(avg_score=Avg('score'))['avg_score'] The problem is that if I do this, then the field "disappears." In fact, if I run makemigrations, it deletes the field. The problem is that I use django-filter, and I want to have the option of filtering by ratings (show me all books that have between a 7 and a 10). If I make it into a property, I can't do it anymore because django-filter can't "detect" the field anymore. Is there a way for me to still have property and the field at the same time? Can I maybe make a surrogate field that gets updated everytime ratings is changed and make it equal to that? -
Django Rest Framework - Serializing based on content of the fields
I have the following model in my django project: class Post(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=False) ownerId = models.ForeignKey(Group, on_delete=models.CASCADE) image = models.ImageField(upload_to='Images/', blank=True) video = models.FileField(upload_to='Videos/', blank=True) def __str__(self): return self.text class Meta: ordering = ('created', ) And my serializer class looks like this: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'text', 'ownerId', 'image', 'video') As you can see, there is a Post class representing a post. The user should be able to post images, videos and also text to the backend. What I want was: If the user posts only a text ( and leaves out the image and video fields) then the Post class should be representing a Text post. If the user posts just an image ( and leaves the text and video fields unfilled) then it should be an Image post. And so on... So, based on which field is filled, the Post class should be representing an image post, video post or text post (or maybe a combination of some fields together, e.g. a text with an image) - I think you get the idea. Now, I tried to solve that problem with a blank=True attribute. And that outputs … -
Django send data parameter type body
We have an hourly task in Dajngo managements. This task collect some data in database and send data to customer. Our customer is using swagger UI. They want data with parameter type body. But I cant create parameter type body This is my code: response['data'] .............. headers={'Content-Type': 'text/json','Authorization':'************'} r = request.post{'https://.../',params=json.dumps(response),headers=headers) I want to create parameter with type body for swagger apı. How can I do. -
Build falling using docker
I am setting up a reposotry which use docker name evalai . i have previously also used it. But from 2 to 3 days its not working it is giving me these two errors. -TypeError: eval() arg 1 must be a string, bytes or code object and this error- Data path ".builders['app-shell']" should have required property 'class'. I have tried changing ajgular version also and used docker-compose up and docker-compose up --build also but it is not starting front end . -
Not displaying the data from the database in django app when deployed in heroku?
I had a django application and I had deployed in the heroku everything like static files are working fine but the data is not being displaying dynamically from the database. should I need any connections for that display of data from database -
AWS Javascript SDK signature and policy
I was using javascript and django to upload files to s3. I was using django to encript AWS Secret key and a policy and signature is generated. Using this Policy, Signature and AWSAccessKeyId I was uploading files using Javascript. It works fine, but I'd wish to change it to multipart upload using this example. This also works well, using 'accessKeyId' and 'secretAccessKey' in AWS.Config() Is there any way to use multipart upload using Signature and Policy? -
is there any better way to lesser the time complexity?
I am working on a website in Python-Django. People can come to this website and can take a quiz. There will be user table which I think 5000-6000 entries will be there. Another table for questions which will have approx 40,000 to 50,000 questions. (There will be many more table(say 8 to 10) but wont have more than 2000 entries) User can come to my website, select number of question(say 50) and can start a quiz. Now this 50 question will be randomly selected from my database. I have tried only MySQL. Never tried PostgreSQl. But heard a lot about PostgreSQL, that it is good for huge entries in database. I tried this in MySQL but time complexity is high. What i tried?? when user request for 50 question for quiz, firstly I i call all the entries and perform a random function and get 50 different values from this value i fetch the question and display it. i call all the entries because there will be some question which are deleted. they are not actually deleted but their delete status will be changed(delete status 0 means to show and delete status 1 means question is deleted) so those question … -
Cannot query firled "votes" on yype Query, name Votes is not defined GraphQL, Django
https://prnt.sc/qhg1wq I have this issue that i cant resolve. I checked everthing in code and it seems to work but when i run server and go to Insomnia or localhost:8000/graphql and type query of votes it seems not to exist at all but in code i have that query. Its a simple cook app that you can cast vote with user who is auth with JWT token. There is not that much code so ill show you all the models and schemas that i made and i still get this error in insomnia using graphql. links/models.py from django.db import models from django.conf import settings class Link(models.Model): url = models.URLField() description = models.TextField() posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) link = models.ForeignKey('links.Link', related_name='votes', on_delete=models.CASCADE) links/schema.py (linkapp) import graphene from graphene_django import DjangoObjectType from .models import Link, Vote from users.schema import UserType class LinkType(DjangoObjectType): class Meta: model = Link class VoteType(DjangoObjectType): class Meta: model = Vote class Query(graphene.ObjectType): links = graphene.List(LinkType) votes = graphene.List(VoteType) def resolve_links(self, info, **kwargs): return Link.objects.all() def resolve_votes(self, info, **kwargs): return Votes.objects.all() class CreateLink(graphene.Mutation): id = graphene.Int() url = graphene.String() description = graphene.String() posted_by = graphene.Field(UserType) class Arguments: url = graphene.String() description = … -
How do I set a foreignkey field in Django models to return no values?
I have a Django model like: class hotel(models.Model): name = models.CharField(max_length=60) city = models.ForeignKey('city', on_delete=models.DO_NOTHING) state = models.ForeignKey('state', on_delete=models.DO_NOTHING) country = models.ForeignKey('country', on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta: verbose_name_plural = "hotels" class city(models.Model): name = models.CharField(max_length=60) state = models.ForeignKey('state', on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta: verbose_name_plural = "cities" class state(models.Model): name = models.CharField(max_length=60) country = models.ForeignKey('country', on_delete=models.DO_NOTHING) def __str__(self): return self.name class Meta: verbose_name_plural = "states" class country(models.Model): name = models.CharField(max_length=60) code = models.CharField(max_length=160) def __str__(self): return self.name class Meta: verbose_name_plural = "countries" And the ModelForm like: class Hotel(ModelForm): class Meta: model = hotel fields = '__all__' Now, I want my Django template to return all country values in dropdown, but not for state and city dropdowns (so I want state and city dropdowns to remain empty in Django template). How can I do that? PS - The purpose to do this is to load country values first, and as per the user selection of a country, I will load state and then cities accordingly. -
manage.py runserver does not work, but django and virtualenv are installed (screenshot attached)
I have read a lot of posts here and created virualenv according to instructions, however, django seem not to be able to run server: errors What could be the issue here? -
How to handle properly handle graphene error?
I am in the early period of graphene-django. I have Mutation like this class DeleteObjection(graphene.Mutation): """ 1. Authorized User only 2. His own `Objection` only 3. Be able to delete only `Hidden type Objection` """ ok = graphene.Boolean() class Arguments: id = graphene.ID() @classmethod def mutate(cls, root, info, **kwargs): tmp = { **kwargs, 'created_by': info.context.user, 'hidden': True } obj = Objection.objects.get(**tmp) obj.delete() return cls(ok=True) And the res is handle in like I expected. It is 200 with forwarded error right after the console { "errors": [ { "message": "Objection matching query does not exist.", "locations": [ { "line": 131, "column": 3 } ], "path": [ "deleteObjection" ] } ], "data": { "deleteObjection": null } } Problem: On my Python server console. I see error has been raised Testing started at 16:01 ... /Users/sarit/.pyenv/versions/multy_herr/bin/python "/Users/sarit/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/193.5662.61/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_test_manage.py" test multy_herr.objections.tests_jwt.UsersTest.test_authorized_user_delete_non_exist_objection /Users/sarit/mein-codes/multy_herr Creating test database for alias 'default'... System check identified no issues (0 silenced). Traceback (most recent call last): File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor executor(resolve, reject) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/promise/promise.py", line 756, in executor return resolve(f(*args, **kwargs)) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/Users/sarit/mein-codes/multy_herr/multy_herr/objections/grapheql/mutations.py", line 36, in mutate obj = Objection.objects.get(**tmp) File "/Users/sarit/.pyenv/versions/multy_herr/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, … -
Will pushing src to Heroku expose it publicly?
I'm looking at this blog on how to push a django/react app to heroku, and in it, we commit and push the entire app to our heroku master. So now the react src folder is stored on the server. Could this conceivably allow someone to read the react source. Of course the routes defined in urls.py should prevent that, but I don't know that much here, so I'd like to make sure. -
How to store uploaded file from django template to django channels 2?
I'm not able to get uploaded file json data and store in database -
How to capture on change event on Django Autocomplete Light widget using jQuery
I am using Django Autocomplete Light (DAL) in my application. In order to do some post-processing in the background on user selection, I am trying to capture the .on('change') event (when DAL select field choice is changed) using jQuery (like we do on objects like an input field or a Django select field etc.). However I am not able to capture the event. For example the following code: $('#x_select_item').on('change', function() { console.log('Selection on x_select_item changed'); }); is not generating any message. Looking for DAL events also did not help much excepting that it takes one to the "select2" events page. There are events listed including "change" and "change.select2", but using both of these (as in example above) are not generating any reaction in the console. Is there some way selection change event may be captured on DAL? -
Handling Redirect with URL that has multiple PK
I'm new to Django and having trouble redirecting after the AddContactEvent form has been filled out. After submitting the form, here is the redirect error: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. I am having trouble figuring out how to redirect it since the AddContactEvent url path('contacts/<int:pk1>/addcontactevent) only has one pk. In the EventDetail url there are clearly two pk which would have the contact pk and the event pk. The EventDetail page seems to be creating, but I can't get it to redirect to that page due to multiple PK. how would you handle the redirect? urls.py path('contacts/<int:pk>', contact_detail.as_view(), name="contact_detail"), path('contacts/<int:pk1>/addcontactevent', AddContactEvent.as_view(), name="addcontactevent"), path('contacts/<int:pk1>/event/<int:pk2>/update', UpdateContactEvent.as_view(), name="updatecontactevent"), path('contacts/<int:pk1>/event/<int:pk2>', EventDetail.as_view(), name="eventdetail"), views.py class AddContactEvent(CreateView): form_class = ContactEventForm template_name = 'crm/contactevent.html' def dispatch(self, request, *args, **kwargs): """ Overridden so we can make sure the `Ipsum` instance exists before going any further. """ self.contact = get_object_or_404(Contact, pk=kwargs['pk1']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): """ Save the form instance. """ contact = get_object_or_404(Contact, pk=self.kwargs['pk1']) form.instance.contact = contact form.instance.created_by = self.request.user return super().form_valid(form) class UpdateContactEvent(UpdateView): model = Event def get_object(self): pk1 = self.kwargs['pk1'] pk2 = self.kwargs['pk2'] contact = get_object_or_404(Contact, pk=pk1) event = get_object_or_404(Event, pk=pk2) … -
How to Integrate SSRS report server to Django
How to Integrate SSRS report server to Django. In next step WEBAPI need to return .rdl data as .pdf to UI. -
why does wagtail keyword is appended to my newly created app name?
I am new to wagtail cms and i am trying to create my first app (named blog) according to official documentation. My problem is that when i run the python manage.py makemigrations command, it says that No module named 'blog.apps.BlogConfigwagtail' wagtail keyword is appended to my app name and django can't find my app. -
Django query not outputting correct result
I have a model named Post and another model named Share A user can create Posts or share Posts. I'm using the following query: Post.objects.filter( Q(user=user) | Q(share__user=user) ).annotate( shared_or_created=Coalesce('share__shared_at', 'created_at') ).order_by('-shared_or_created') With this query, I'm getting the correct posts, however, let's say another user (user B) shared this user's post then the shared_at field will be the time that user B shared it. So if the user has 3 posts and 1 user shared that user's post, then two of the posts will have the correct time when the post was created and the third post will have the time when User B shared that post. The logic should be to show the user's posts and the posts shared by them in descending order. How can I implement this? -
Problem in running ASGI environments while deploying app Django Rest
I am developing an app using django,I have deployed on google cloud platforms initially using wsgi environment,now I have made addition in app and used channels due to which I have to shift from wsgi to asgi, but I am getting errors while deploying to GCP when I use Asgi environment I got the error: respiter = self.wsgi(environ, resp.start_response) TypeError: __call__() takes 2 positional arguments but 3 were given I commented the all content of WSGI file when I want to use ASGI env,here's me related code: ASGI FILE: import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Frames.settings') django.setup() application = get_default_application() WSGI FILE (which I have commented): """ WSGI config for Frames project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Frames.settings') application = get_wsgi_application()""" main.py: from Frames.asgi import application app = application Settings.py(Main changes and I have removed all WSGI related from settings.py) ASGI_APPLICATION = "Frames.routing.application" CHANNEL_LAYERS={ "default":{ "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } How can I run ASGI env?If I missed something in showing my code I can also show that,I can't get what …