Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Revolution Slider integration on Django application
I am making a E-shop site with Django framework. For front-end I have downloaded free bootstrap template. There is some problem with Revolution Slider and static file service. When I use static tag for html file everything works fine but there are many ajax calls in a Revolution Slider js file. All ajax request on that file goes with out static prefix so Django server can provide it as a static file. Please let me know how can I fix this issue. -
How to send a data URI collected via javascript to a Django Model field?
I'm trying to use the signature_pad from https://github.com/szimek/signature_pad to attach a signature pad to a Django form that gets saved to a server. Right now I can place the DIV into my form, create a signature, but I don't know how to send it along with the form/model field. Currently I don't have a preference as to whether it is sent to the server as a Data URI, SVG, or PNG. I imagine once I sort this out, I can easily modify the code to do one or the other. Here's my models.py from django.db import models class testModel(models.Model): name = models.CharField(max_length=50) signature = models.FileField() forms.py: from django import forms from .models import testModel class testForm(forms.ModelForm): class Meta: model = testModel fields = '__all__' widgets = {'signature': forms.HiddenInput()} views.py: from django.shortcuts import render from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from .Forms import testForm from .Models import testModel def testFormPage(request): if request.method == 'POST': form = testForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') else: form = testForm() return render(request, 'client_visits/testFormPage.html', {'form': form}) and the the HTML form: <form action="{% url 'testFormPage' %}" method="post"> <div id="signature-pad" class="signature-pad"> <div class="signature-pad--body"> <canvas></canvas> </div> </div> <input type="hidden" name="signature" value="formSig.value" id="formSig"> <input type="submit" value="Submit"> … -
Django: Is it wise to prefetch when you only need a fraction of the queryset?
I have the following statement which prefetches the cousin objects related to each user and then slices the queryset to get the last 10 elements: Users.objects.prefetch_related("cousins")[:10] Is it wise to prefetch in this case? I think the api might be doing a lot more calculating than required specially if we have 1000 users or more. And as a follow up: when is it a good idea to prefetch? -
Parse XML API response and display on Django Template
I am using the Microsoft translate api that gives me the result in this format <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hey wie geht es dir?</string> Now in Django and I tried to transform the reply into a dictionary as suggested in this answer so I have response = requests.request("GET", url, headers=headers, params=querystring) print (response.text) translated = xmltodict.parse(response.text) print (translated) return render (request, 'conjugator/translated.html', {'translated': translated}) but what I get now is OrderedDict([('string', OrderedDict([('@xmlns', 'http://schemas.microsoft.com/2003/10/Serialization/'), ('#text', 'Hey wie geht es dir?')]))]) here is my template {% block content %} <h2>{{ translated }} </h2> {% for key, value in translated.items %} {{ value }} {% endfor %} {% endblock content %} Given that this API (translation) will return a single result what is the easiest/most efficient way to format the XML for display on a template ? -
Django Rest Framework - how to handle update of an item with order field
Hello Folks ! In my DRF app, I've got this model : class Item(models.Model): label = models.TextField() order = models.IntegerField() class Meta: ordering = ['order'] unique_together = ['order', 'invoice'] I am looking for a way to update an instance, possibly changing his order value, and keep the ordering sequence correct. Currently, the serializer validation failed because of the unique_together. But I don't want to update my DB before checking that the data are corrects... Any idea on how to do that ? Thanks a lot Swann -
django get to know what submodel is associated to the main model
I have a model called Ad and there are multiple models that have Ad as OneToOneField class Ad(models.Model): name = models.CharField(max_length=100) description = models.TextField() class Car(models.Model): ad = models.OneToOneField(Ad, on_delete=models.CASCADE) name = models.CharField(max_length=20) class Boat(models.Model): ad = models.OneToOneField(Ad, on_delete=models.CASCADE) name = models.CharField(max_length=20) class Truck(models.Model): ad = models.OneToOneField(Ad, on_delete=models.CASCADE) name = models.CharField(max_length=20) (nb . there are 50 submodels) Only When an ad is created , so it will associated to only one of three submodel car,boat or truck so after that i am creating a view to display the name of the Ad but how can i know what is the sub model associated to the ad to get the data from it to. def get_ad_details(request, id): ad = Ad.objects.get(id=id) #need to call a method to get a boat or car or truck or .... that is associated to the ad so how? -
How could I use ajax to update buttons and counts without redirecting?
I'm trying to make like/dislike functionality so if a user is watching a video (for example) the page doesn't refresh and make them lose the progress in the video. I understand how to modify content of a <div> tag but have no idea how to deal with the logic that I would need to use to change the text/url of the button (example: if they click 'like' then the 'like' should become 'unlike' and the url attached to 'like' should be changed). The way I've tried to tackle this is below, I haven't figured a way to code the logic into the replacement template yet and deleted what I had before so forgive me for not putting up the HTML. handle_likes.js // Handle button clicks $(".like-btn").on('click', function(){ console.log("Like button was clicked!"); // sanity check // Get the value of the original button if ($(".like-btn").val() == "not-liked") { like_post(); // I figured I could change the value to change the linked url } if ($(".like-btn").val() == "is-liked") { unlike_post(); } }); // Functions to handle likes/dislikes function like_post(){ console.log("Like post called...") // sanity check $.ajax({ url: "posting/liking_post/", data: { post_id : $("#post_id").val(), // Need this to get the post post_type : … -
How to return django template with a form in celery task?
I need to return a form from inside a django celery task. My task is called from the following view: class CreateView(CreateView): model = MyModel form_class = MyForm success_url = '/create/form' def form_valid(self, form): form.save() # I call my task in here period.delay() print("Loading task...") return super(CreateView, self).form_valid(form) My task is: from .views import MyView # others imports... @shared_task(serializer='json') def period(): event = MyModel.objects.get(id=1) # I limited my model to receive only one object request = RequestFactory.get('/another/form') view = MyView() week_d = week_day(event.day) # day is a field of my model event_d = event_day(week_d, event.hour) # hour is a field of my model conf_d = presence_confirm(event.before_days, event.begin_hour, event_d) # before_days and begin_hour are fields of my model utc_now = pytz.utc.localize(datetime.utcnow()) n = utc_now.astimezone(pytz.timezone('America/Recife')) t_str = '{}-{}-{}'.format(n.year, n.month, n.day) t_hour = ' {}:{}'.format(n.hour, n.minute) today = t_str + t_hour today = datetime.strptime(today, '%Y-%m-%d %H:%M') if (today >= conf_d) and (today < event_d): # how to call my formulary??? print("Call my formulary") view.setup(request) else: # another thing I'm trying with RequestFactory.get to cacth a URL and setup view (MyView()), but It returns ImportError: cannot import name 'MyView' I appreciate if anyone can help me!! -
Django no referer CSRF error only on iPhone
I have a Django 2.2/nginx/uwsgi web-site (https://rodichi.net), which works fine on Windows, MacOS, Android, on all browsers—but not on iPhone. The browser doesn't matter. The error I get is "no referer". I am stuck. I don't have any experience with iPhone myself (using BrowserStack to reproduce the behaviour). Is it an expected situation? I cannot find anything like that on the internet, which puzzles me. Please comment if more info is needed from my side to narrow down the problem. -
Is there a way to get selected object in Django form?
I'd like to get the Customer object (which is a foreign key selection) when it is selected. I want to be able to display attributes/fields of that customer when it is selected (and I want them to change if/when a different selection is made). I imagine I could use jquery to get the text and then query the db for the customer name. But if I have two customers with the same name I run into issues. So is there any way to grab that exact object that is selected? To complicate things I am using django-autocomplete-light (which is awesome but may make this more difficult). But assuming this was a normal fk drop-down is there a way to get the object that the user selects? -
Annotate a django field
Is it possible to add some extra arguments to a field definition so I can parse that at a later time, such as: class Item(models.Model): field = models.CharField(max_length=40, something='yes') Later on: for field_obj in Item._meta.fields[1:]: # ignore auto-pk field = field_obj.name something = field_obj.annotations['something'] print (field, something) -
How to store a primary key in a session variable
I am storing an object.pk in a session variable. E.g. in template.html: {{ request.session.myobject_pk }} <-- results in a numeric value e.g. 10 {{ myobject.pk }} <-- the same numeric value, 10 However, when I call these two values in an if statement, the primary key does not match the session variable: {% if myobject.pk == request.session.myobject_pk %} <-- results in a False Why is this? Is the object an integer and the session variable a string? How can I fix this to use them both in a conditional logic statement like this? -
Can I append an object from a QuerySet to a list?
for i in range(User.objects.count()): users = [] users.append(User.objects.all()[i]) # prints all of the objects which I need print(User.objects.all()[i]) # prints the correct number of objects (21) print(User.objects.count()) # when I print the list there is only the most recently added element #(i.e. the list only contains 1 object) print(users, '\n') I want a list with a length of User.objects.count(), where each element is an individual object in the QuerySet 'User.objects.all()'. When I print 'users', it prints the correct number of times, but each time it prints, the list only contains the most recent object. It seems to be overwriting the current object in 'users', and replacing it instead of adding a new object to the end of the list. -
How to configure MathJax to render chemical equations in HTML?
I am trying to render mathematical equations using MathJax in HTML. So far, here's what I have: <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']], ignoreClass: "math-editor", // put this here } }); </script> <script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"> </script> However, I am also trying to get MathJax to recognize chemical equations such as $\ce{Hg^2+ ->[I-] HgI2 ->[I-] [Hg^{II}I4]^2-}$ but so far I have no success. What would be a simple and straightforward way to modify MathJax so that it recognizes chemical equation scripts as well? I am using Django for my web application. -
Render DjangoRestFramework View As CSV In Browser
In DRF you're able to render a CSV file from the API by using the ?format=csv url parameter, but this causes a CSV file to be downloaded to your computer. Is there a way to prevent this CSV from downloading and simply display it in the browser? My config is: settings.py 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_csv.renderers.CSVRenderer', ), -
How can you make likes/dislikes without redirecting
I'm trying to figure out how to make likes and dislikes for a post. Am I going to have to use ajax or am I able to just return data to the template without having to redirect? The steps to do this that I have already are... 1. user clicks 'like' and like_post is called. 2. like_post goes through logic to see if user already liked (and somehow bypassed the template logic) and creates a Dislike object 3. redirects to the same template with a new like/dislike count. The main reasons I want to be able to do this without redirecting is 1. If the user is watching a video, it doesn't get interrupted. 2. I have two different templates the user can possibly view a post from and short of passing the template name to the view, I have no way of knowing what page the like is coming from. I've tried to use ajax but I ended up getting messed up on how to deal with the logic of switching the button from Like to Unlike in the secondary template that would replace the respective buttons with. -
How to check if a value is in a form POST
I want to query if an input value is in a form post and raise an error if it is not: try: next_page = request.POST.get('next_page') except AttributeError: raise ImproperlyConfigured( "No URL to redirect to. Either provide a url or define" " a get_absolute_url method on the Model.") However, if next_page is not provided this code results in next_page = None and the error is not raised. Where am I going wrong? -
how to get started with Django/Linux?
I am new to python Django frame work, i installed Django on my Linux system by seeing this YouTube video. https://youtu.be/mqlCk_WCK2E I have done what ever he says but after installing i don't understand how to get started. Thanks in advance. -
can't get html to link while using django
If anyone can help me on why my html wont link with my css that would be awesome! Thanks! I'm using Django 3.0.2 to make a website for a resume and I have already rooted my static files and that didn't seem to do anything. I have tried stopping and running my server multiple times as well as find solutions online but everyone is using an older version or their solutions don't help. HTML: <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}"> </head> <body> this is a test <div class="container"> <header> {% include 'navbar.html' %} </header> </div> </body> CSS: body { background-color: rgb(82, 70, 70); } .container{ background-color: rgb(128, 199, 172); } .navbar{ background-color: rosybrown; } SETTINGS: STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), '/pydir/mysite/static', ] STATIC_ROOT = '/pydir/mysite/static' STATIC_URL = '/static/' and I made sure that staticfiles and admin where in the installed apps. -
Django + Sass + Compressor: loading cached css files, unable to update or remove
Aloha! I have been working on a django project and recently switched to SASS for styling. The initial compiling on the css file seemed to work fine, but once I went to update the file I noticed the changes were not reflected in the browser. Upon further investigation, I have determined the issue is a cached file located at static/CACHE/css/output.ad5d8929a444.css however I am unable to find this file anywhere in the filesystem, and running commands such ./manage.py compilescss --remove ./manage.py collectstatic does not resolve the issue. I have tried looking around for other questions and it seems this question is most closely related however that suggestion did not work in my case. I have tried deleting all browser data and I typically only use incognito mode in Chrome for development anyways as to avoid caching files in the first place. I have tried searching for the file inside of my filesystem, however, it seems I am unable to locate the statice/CACHE folder. My question is how do I force django to use the new css file, and where do I find the cache folder? This is my first time using SASS for styling, so any advice in that department is … -
delete from many to many field but not from related model
Here is my code in django, class Comment(models.Model): text = models.CharField(max_length=400) writer = models.ForeignKey(Email, on_delete=models.DO_NOTHING) replied_to = models.ManyToManyField('self', related_name='replied') class Meta: db_table = 'Comment' when I add an instance of comment to replied_to, It adds to parent but replied instance keeps a pointer to related object in its replied_to field. Is there a way to remove pointer to related Comment without removing reply instace from parent? -
How to optimize annotate in django query?
This code is taking 55 seconds to run, is there any way to optimize this? It is unfeasible start_time2 = tm.time() _candidates_ext = _candidates.annotate(month=TruncMonth('apply_date')).values('month').annotate(jcount=Count('pk')).order_by('month') context['candidates_total'] = len(_candidates) #context['candidates_total'] = _candidates.count() context['candidates_ext'] = _candidates_ext print("--- %s seconds ---" % (tm.time() - start_time2)) print("===== Connections =====") print(len(connection.queries)) import pdb; pdb.set_trace() I'm new to the company and would like to start well Use python 2.7 and DJango 1.8 -
Form data POST vs Ajax POST
I am currently developing a UI where user enters their personal information in the form and when they click submit, the data gets inserted into the database. Now, I have two ways of sending the form data fro UI to the backend. 1) Using the Form POST method 2) Using Ajax POST method Out of both, which one is the best to follow (or) anything is fine? are there any limitations in certain cases? I am developing the website in Django -
API 403 Errors while logged into admin panel with Django
When I login to Django admin ('/admin') and, without logging out of Django admin, navigate back to my site's homepage ('/'), I get 403 errors on an axios post request (doesn't use any forms and happens on '/' page load). If I never login to Django admin, everything works as expected. This what my post request looks like: async function filterData(){ let categories = $('#category_selection').val(); showHideMessage.style.display = 'none'; await axios.post( '/tabulate/', { categories: categories, }, { headers: { 'Content-Type': 'application/json' } } ) This is what the endpoint (w/ Django Rest Framework looks like): @api_view(['GET', 'POST']) def tabulate(request): metrics = Field.objects.all() if request.method == 'POST': data = request.data if data['categories']: metrics = metrics.filter(category__in=data['categories']) metrics = clean_metrics(metrics.values()) return Response(data={'metrics': metrics}, status=status.HTTP_200_OK) I have left all Django default authorization middleware and just added 'rest_framework' to Installed_Apps. Would really appreciate any insights~ -
Django manage different forms in a same page in view.py
In my project i have to manage 3 different forms in my login html file, one for classic login, one for user registration and one for company registration (all in a single login.html file) I create in my forms.py three different Modelforms class for manage the different models but now i have just an url and in my views.py i dont know how to say for witch form the data come from and how make the binding and the elaboration: def user_login(request, log_err=None): context = RequestContext(request) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] return HttpResponseRedirect('/login/log_error') else: return render(request, 'login.html', {'l_err': log_err}) How can i discriminate the saving data into correct model if come from form1,2 or 3? So many thanks in advance