Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I have the method get instead of post?
I have a website using http and everything was working but now I update http to https protocol and I get the following problem into celery task : b'{"detail":"Method \\"GET\\" no allowed."}' This is my line using post : requests.post('https://localhost/api/update', data=data, headers={'Content-Type': 'application/json'}) I don't understand why I have a problem with the GET method knowing that I use POST method. Could you help me please ? Thank you very much ! -
please how do I add new key - value pairs to a dictionary without overriding the existing key?
please how do I add new key - value pairs to a dictionary without overriding the existing key? Iβm building a project requires users to give an answer that I will use as a key and value pair. Everything is working well but if a user make a mistake and enter a key that already exists, it will override the existing one. -
Trying to use property from child model in parent for charting
I am trying to use an order_total property summing the line items from a child in my django admin changelist. The order_total property displays correctly in my list view, but does not work in the chart function. What I am doing wrong? models.py class Order(models.Model): class Meta: ordering = ['date_needed'] date_ordered = models.DateField(blank=True, null=True,default=datetime.now) date_needed = models.DateField(blank=True, null=True,default=datetime.now) date_shipped = models.DateField(blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') customer_order = models.CharField(max_length=100, blank=True, null=True) status = models.ForeignKey(Order_Status, on_delete=models.CASCADE) invoice_no = models.CharField(max_length=45, blank=True, null=True) tracking_no = models.CharField(max_length=45, blank=True, null=True) shipping_cost =models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) carrier = models.CharField(max_length=50, blank=True,null=True) service = models.CharField(max_length=100, blank=True,null=True) @property def order_total(self): l = [] for item in self.order_items.all(): p = self.customer.pricings.filter(offering=item.offering).first().price if self.customer.pricings.filter(offering=item.offering).first() is not None else item.offering.wholesale_price, l.append(p[0] * item.lbs) return sum(l) **admin.py** class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemInline] list_display = ['customer','order_number','order_total','date_ordered','status'] ordering = ['-date_ordered'] def changelist_view(self, request, extra_context=None): response = super(OrderAdmin, self).changelist_view(request, extra_context) filtered_query_set = response.context_data["cl"].queryset chart_data = ( filtered_query_set.annotate(date=TruncDay("date_ordered"), month=ExtractMonth('date_ordered')) .values("date", 'month') .annotate(y=sum("order_total")) .order_by("-date_ordered") ) -
Django admin panel lags and doesn't show anything
Today I've launched my Django project and saw a really weird behavior of Django admin panel. At the first sight, everything looks OK but as soon as I click on any model to view, I can't see anything. The most strange thing is that I've got no weird commits that could damage the contents of admin panel recently. The only commit could do that is updating Django to 3.1 version. I've already tried reinstalling Django and installing older versions but nothing works. Here is the typical admin panel homepage Here is what happens when I click on models I really need to know how to fix it as well as both me and my friend have this issue and we can't deal with it. -
added two search bar in django one search by id and other by name .Tried many ways but cannot do it if i try by id then i am not able to do with name
I have to make 2 search bars. I don't know how to add multiple fiels... match= Staff.objects.filter(id=srch1...) here how can I add name=srch1 over here after trying many ways I found it but the problem is all input here is string how to change it to int def search(request): # Catch the data and search in Staff model. if request.method=='POST': srch1 = request.POST['srch'] print(type(srch1)) if type(srch1)== int: match= Staff.objects.filter(id=srch1) if match : return render(request,'search.html',{'sr': match}) else: messages.error(request,'no results,found') elif type(srch1)== str: catch= Staff.objects.filter(name=srch1) if catch: return render(request,'search.html',{'sr': catch}) else: messages.error(request,'no results,found') else: return HttpResponseRedirect("/search") return render(request,"search.html") -
How to use parameters in DRF router
Hello guys so I came to realise that DRF ModelViewSet is a quick way to make rest views, I am trying to use parameters within the router url but the ViewSet does not detect the param Here is how my viewset looks class ClientRequests(ModelsViewSet): serializer_class = serializers.ClientRequestSerializer def get_queryset(self): return models.ClientRequest.objects.filter(cliend_id=self.request.kwargs.get('client_id') now I register the router as below router = DefaultRouter() router.register('/<int:client_id/requests', views.ClientRequests, basename='clients request api endpoint') urlpatterns=[ path('', include(router.urls)) Is this the right way to use restframework router and how can I pass paramters to the url when using router -
Storing and accessing nested JSON in a Django Database
I'm using Django to store some information about a DAW and Software Synth set up. I've managed to get the database to work for storing very simple non-nested data like this: {"name": "Drums", "arm": 0, "solo": 1, "mute": 1, "devices": "compressor, reverb"}, But I have a bunch of data that's formatted something like this, which I need to be able to store and access: {"Config": { "Tracks": [ {"name": "Drums", "arm": 0, "solo": 1, "mute": 1, "devices": ["compressor", "reverb"]}, {"name": "Bass", "arm": 0, "solo": 1, "mute": 1, "devices": ["compressor", "reverb"]} ], "SelectedTrack": 0, "ActiveView": "Session" } I need to be able to update and access specific pieces of information from this, for example I need to be able to get to the names of every track easily. Or the SelectedTrack, whose number represents the index of the track. Or update the "arm" of a single track. Is there a better way of storing this? The order of the tracks is really important too as it reflects the index position of the tracks in the DAW, if they change, I need this to be reflected in the database so that I can find the index position of track named "drums" or β¦ -
Using Boolean in Django Custom Query Set
Lately I had came to one strange thing when I was working with Django custom querysets. So, I am using request.GET for passing boolean value to my django view. Then I pass this value to my custom queryset function. It seems weird because it works in case of basic query but not with '__isnull'. Are there any differencies? views.py if request.GET.get('available'): items = Item.objects.is_available(request.GET.get('available')) # this works ... if request.GET.get('order'): transfers = Transfer.objects.not_working_is_order(request.GET.get('order')) # not working managers.py class ItemQuerySet(QuerySet): def is_available(self, is_available): return self.filter(is_available=is_available) # this works class TransferQuerySet(QuerySet): def is_order(self, bool): if bool == 'False': return self.filter(order__isnull=False) elif bool == 'True': return self.filter(order__isnull=True) # this works def not_working_is_order(self, bool): return self.filter(order__isnull=bool) # not working mytemplate.html <a href="?available=False&pg={{ request.GET.pg }}&search={{ request.GET.search }}">Not available</a> myothertemplate.html <a href="?order=True&pg={{ request.GET.pg }}&search={{ request.GET.search }}">Not order</a> -
How to build compilers for django project
I am working on a django project in which I need to integrate C,C++,Java,Python,Javascript compilers in my project. Please anybody help me with the logics or code to run on the local server. -
Django: variable as initial value for form field; and filtering a form field's queryset?
I'm trying to create a form with a variable as an initial value for a form field, and to filter a MultipleChoiceField in the same model by that variable. I'm using very minimal ModelForms and Create/UpdateViews. models.py class BigLocation(models.Model): name = models.CharField(max_length=255) [...] class SmallLocation(models.Model): name = models.CharField(max_length=255) in_big_location = models.ForeignKey(BigLocation, [...]) exit_points = models.ManyToManyField('SmallLocation', [...]) From my BigLocation page, I can open a link to a SmallLocation form. In that form, I would like the value of 'in_big_location' to automatically be assigned to the BigLocation instance from which I opened the form. And also I would the 'exit_points' field to display only the SmallLocations that are in that BigLocation. I can't seem to wrap my head around how to go about doing that. Can anyone point me in the right direction? Thanks. -
SECRET KEY NOT FOUND When pushing to heroku [duplicate]
When I exceute git push heroku master everything runs fine but suddenly stops when it attempts to run python manage.py collectstatic --noinput At first when I looked up the error there where answers related to adding a STATIC_ROOT but, I have that and, upon reading the actual error, it is showing secret key not found. My secret key is stored in a .env file using python decouple The full error is shown below remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 983, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked remote: File "<frozen β¦ -
How to add alert messages in Django LoginRequiredMixin
So i am using LoginRequiredMixin in Django for some of my feature that require users to logged in. but since i am using class based views and there's no request i don't know how to add django.contrib.messages in my view and template. Is there a way to add this messages feature while using class based views ? -
how to make existing JavaScript code work on new added html with innerHTML
all that I need is: when I import any new HTML elements or replace existing ones with elements.innerHTML, the existing javascript code will apply to them ( which is selecting them by class ) when I add elements with innerHTML I want to include tags within them ( so it is included within a Django for loop or something like that ) -
Django infinite loop request is not blocking other requests
I have created a django project, and then i created two request handlers, where one completes instantly, and the other is executing an infinite loop. class IndexView(View): def get(self, request): return HttpResponse('Hello, World!') class LoopView(View): def get(self,request): while True: pass return HttpResponse() First, I make a loop request, expecting it to block incoming index requests. However, the index requests are not blocked by the loop request. Why is that happening? -
Django ORM confusion
I am running a function to fetch data from DB, there are three models Rooms RoomImages HomepageRooms I am fetching all homepage rooms with their data using this code,there are total 15 records in homepagerooms model and it is hitting database 17 times as per django debug toolbar,i am using queryset cached object of images in loop why is it hitting database then instead of using cached data. homepageRooms = HomepageHotels.objects.all().select_related('room') roomIds = [room.room_id for room in homepageRooms] images = RoomPhotos.objects.filter(room_id__in = roomIds) result = {} for room in homepageRooms: if room.group not in result.keys(): result[room.group] = [] temp = {} temp['room'] = room.room temp['image'] = images.get(seq=1,id=10) result[room.group].append(temp) Models : class RoomPhotos(models.Model): photo = ResizedImageField(size=[800, 600],quality=75,upload_to='RoomImages',default = 'hotels/room_images/noImage.png') room = models.ForeignKey(Rooms,on_delete=models.CASCADE) seq = models.IntegerField() def __str__(self): return '{} : {}'.format(self.seq,self.room.name) class HomepageHotels(models.Model): room = models.ForeignKey(Rooms,on_delete=models.CASCADE) group = models.IntegerField(choices=GroupType.CHOICES) createdOn = models.DateField(auto_now_add=True) updatedOn = models.DateField(auto_now=True) -
unreadable format of user first name in django
I have an article model with author field that the user can't submit through a form because it is his first name and last name, I put only first_name so if you can help me put last_name I will be grateful: author = models.CharField('author',max_length=50, default=User.first_name) When saved to the database it shows that author is <django.db.models.query_utils.DeferredAttribute object at 0x111874dc0> Because I can't import account, which is also a model I use User. -
In Django I didn't get the option of request.Get?
Django-Error As you can see in below iamge there are only two options. -
How to control the number of objects in a Django model
I have the following model: # Product Photos class Photo(models.Model): title = models.CharField(max_length=255, blank=True) product = models.ForeignKey("Product", null=False, default="0", on_delete=models.CASCADE, related_name='photos') file = ProcessedImageField(upload_to=get_upload_path, max_length=500, null=True, blank=True, processors=[ResizeToFill(800, 450)], options={'quality': 80}) #height_field = models.IntegerField(default=0, null=True) #width_field = models.IntegerField(default=0, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) As you can see there is a product foreign key. What I want to do is, prevent this photo model from accepting not more than 5 photos from the same product. Basically, each product should have 5 photos or less. How can I control this from Photo model? -
Django WSGI script only handles root URL, Apache throws 44 for deeper URLs
The tutorials, guides and even other posts here on SO dealing with how to deploy Django on Apache seem to assume that by default when using the WSGIScriptAlias directive all deep links under that alias are handled by the script as well (usually demonstrated by visiting the /admin page). For me that seems not to be the case. Requests to the root at api.mydomain.com/v1/ are handled by my Django app, but api.mydomain.com/v1/users/ (with or without trailing slash) generate Apache's 404 "Not Found. The requested URL was not found on this server." message. Is there a setting I've missed somewhere that handles these deep links? For example for SPA's I'm used to having to redirect all requests to a front controller. Here's my Apache configuration: <VirtualHost *:80> ServerName api.mydomain.com ErrorLog /var/www/api.mydomain.com/log/error.log CustomLog /var/www/api.mydomain.com/log/requests.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =api.mydomain.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost *:443> ServerName api.mydomain.com RedirectMatch ^/$ https://api.mydomain.com/v1/ WSGIPassAuthorization On WSGIScriptAlias /v1/ /var/www/django_app/django_app/wsgi.py ErrorLog /var/www/api.mydomain.com/log/error.log CustomLog /var/www/api.mydomain.com/log/requests.log combined SSLCertificateFile /etc/letsencrypt/live/api.mydomain.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/api.mydomain.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> -
Deploy a django project on Heroku (Windows) :
I'm trying to deploy a Django app from the first time using Heroku. But my http://myapp.herokuapp.com is always returning an Application error. When I check heroku logs --tail I get: ... FileNotFoundError: [Errno 2] No such file or directory: '/app/CandiBot/logs/08/16.log' The tree structure of my project looks like this, I think I missed a folder called "myproject" but I guess the issue is not related to that. CandiEnv/ (venv) βββ Candispo/ (app) β βββ models.py β βββ urls.py β βββ views.py β βββ ... β βββ static/ β β βββ(empty) β βββ **logs/** β βββ **08/16.log** βββ myproject/ (yea IDK why I've named it differently) β βββ settings.py β βββ urls.py β βββ wsgi.py βββ... βββ manage.py βββ Procfile Maybe it has to do with my settings.py, the static part looks like this: STATIC_URL = '/static/' BASE_DIR= os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( #Not sure it's useful os.path.join(BASE_DIR, 'static'), ) What am I missing here ? -
Delay time between form submissions django
I have a form in my website and I want to make it that the user can submit it only once every 90 minutes. -
How to serve a temporary file (non-static) via HTTP request?
I have a Python REST server, that is able to download and write a temporary file using Python TempFile. That is, at request time I have a a file in the filesystem of the server, but it is not permanent so the client cannot access it statically (I.e. via http://myserver/path-to-my-file ). I need a way to access an endpoint, and then get a file returned based on the request. (I.e. http://myserver/myendpoint/myrequestparameters) How does that work over HTTP? Is it possible? (For context, right now I am serving the file encoded as string using base64 encoding and utf-8 decoding, but my frontend application needs a direct download link) -
Django adds route address when looking for static files
Im trying to do a blog. My project has 2 urlpatterns [ path('', views.main, name='home'), path('users/<str:username>/', views.view_profile, name='profile'), ] Home page shows all posts, post includes avatar of post's author and avatars are visiable. When i change page to profile to see all posts of one author, django is looking for static files in weird way, by adding users/str:username/ at the beginning of path. e.g. '/users/TestUser/static/images/male.png', when correct path is 'static/images/male.png'. Why django looking for static files in that way and how to 'fix' it? Tree looks like this: project app app_stuff project project_stuff static images male.png Settings are like this: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
how to get a value from radio and date input using request.GET[] in django
I am working on one app in which i have to add all the form input data in csv file.Instead of Django forms i used normal bootstrap forms and accessing form input data using request.GET[]. everything works fine but radio and date input not working and getting this error MultiValueDictKeyError at /abc/. here is my code views.py from django.http import HttpResponse #from django.templatetags.static import static from django.shortcuts import render #from django.contrib.staticfiles.templatetags.staticfiles import static import csv from csv import writer def index(request): return render(request, 'filedata/home.html') def abc(request): if request.method == "GET": sid = request.GET['sid'] sname = request.GET['sname'] gender = request.GET['gender'] dob = request.GET['dob'] city = request.GET['city'] state = request.GET['state'] email = request.GET['email'] quali = request.GET['quali'] stream = request.GET['stream'] alist = [sid, sname, gender, dob, city, state, email, quali, stream ] print(alist) # Open file in append mode with open('students.csv', 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(alist) print("Added Successfully!!!") print(sid) flist = [] flist.append({'sid':sid}) flist.append({'sname':sname}) flist.append({'gender':gender}) flist.append({'dob':dob}) flist.append({'city':city}) flist.append({'state':state}) flist.append({'email':email}) flist.append({'quali':quali}) flist.append({'stream':stream}) return render(request, 'filedata/abcd.html', {"flist": flist}) home.html <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> β¦ -
Django MultiChoiceField form invalid
I asking for help sorting the reason for the form being invalid. In the application, Programmes run on specific dates, stored in the 'DAY' model. One or more Profs may be added to one or more days of a programme. In FORMS, I've filtered the day=ModelChoiceField so that only the dates related to the programme to which the prof should be added are available for selection. However on save, I'm getting a form invalid. All help much appreciated. Thank you. Models: class Programme(models.Model): name = models.CharField('Programme Name', max_length=50, editable=True) slug = models.SlugField(unique=True, max_length=10) class Prof(models.Model): programme = models.ForeignKey(Programme, on_delete=models.CASCADE) prof = models.ForeignKey(User, on_delete=models.CASCADE) day = models.ForeignKey(Day, on_delete=models.CASCADE) class Day(models.Model): programme = models.ForeignKey(Programme, on_delete=models.CASCADE) date = models.DateTimeField(editable=True) start_time = models.TimeField(editable=True, blank=True, null=True) end_time = models.TimeField(editable=True, blank=True, null=True) class Role(models.Model): role = models.CharField(max_length=50, editable=True, unique=True) Views: class ProfCreate(CreateView): model = Prof form_class = ProfCreateForm context_object_name = 'obj' template_name = 'programme/prof_create.html' extra_context = {'page_title': 'Add Prof'} success_url = reverse('programme:programme_detail') def get_form_kwargs(self): #pass programme_id to form modelchoicefield filter kwargs = super().get_form_class() programme = Programme.objects.get(slug=self.kwargs['slug') self.kwargs['programme_id'] = programme.id return self.kwargs def form_valid(self, form): if form.is_valid: prof = form.save(commit=False) prof.programme_id = self.programme_id prof.save() return redirect('programme:programme_detail', self.kwargs['slug']) def form_invalid(self, form): print ('FORM INVALID - - WHY?') return β¦