Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is pre_saved called if you delete an object
I'm using the Django signal pre_saved. From the documentation I though that this signal is only called If you save an object. But why is this method called if you delete an object? -
Django Custom User Error: FOREIGN KEY constraint failed
I'm following the Django document Customer user and proxy model to create a custom user model. The code is exactly same, I just copy the while brunch of the code into my project. But it's showing up an error. django.db.utils.IntegrityError: FOREIGN KEY constraint failed Page Error I have no idea how to fix this error. -
django and ajax dropdown based on selected dropdown
I am trying to do a dropdown menu based on the selected dropdown and filter these results. Here what I did so far: project_dropdown_options.html: <option value="">---------</option> {% for sw in result %} <option value="{{ sw.pk }}">{{ sw.pk }}</option> {% endfor %} view.py: (I checked the result I am getting values.) def projects_dropdown(request): id = request.GET.get('id') print(id) result = list(SWTypes.objects.filter(proje=int(id)).values('swtype')) return render(request, 'project_dropdown_options.html', {'result': result}) url.py path('ajax/projects-sw/', views.projects_dropdown, name='ajax_projects_dropdown'), Ajax script: <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#projects").change(function () { var url = $("#personForm").attr("projects-drop-url"); var id = $(this).val(); // get the selected projectID from the HTML input $.ajax({ // initialize an AJAX request url: url, data: { 'id': id // add the project id to the GET parameters }, success: function (data) { $("#sw").html(data); } }); }); </script> html page where the dropdown is: <select name="projects"> {% for instance in projects%} <option value={{ instance.id }}>{{ instance.project_title }}</option> {% endfor %}</td> <td> <form method="post" id="personForm" projects-drop-url="{% url 'ajax_projects_dropdown' %}" novalidate> {% csrf_token %} <select name="sw" id="sw"> <option value="">Switch Type</option> </td> </form> I think I have error either with Ajax script or the html part where the dropdown menu is.Any idea where I am doing which error ? I am getting no error and I am … -
Django: How to iterate List containing Dicts
I get Json data and then convert it to python object. Here is the code: number = request.POST.get('num') url = "http://127.0.0.1:9000/findexclusive" querystring = {"num":number} response = requests.request("GET", url, params=querystring) response = response.json() response = json.loads(response) return render(request,'home.html',{'details':response}) Now I get a valid response. But not able to convert this data in to html page. Data I get is like below: [{u'pk': 1233, u'model': u'details.modelname', u'fields': {a': u'xyz', u'b': u'something', u'c': u'something', u'd': u''}}] How do I iterate this. These are not working: for data in b[0]: ... for key,value in data.items: ... print key ... Traceback (most recent call last): File "<console>", line 2, in <module> AttributeError: 'unicode' object has no attribute 'items' >>> a = data.json() -
Annotate and .get() in Jango
In my database I have a table card linked to a table amount, 1 card can have many amounts. So with django I try to get a specific card and aggregate the sum of all the amounts linked. But impossible to concatenate .get() and .annotate together. I tried this: last_year_amount = Card.objects.get(date__date=date(today.year - 1, today.month, today.day)).annotate(total=Sum(Amount.amount)) But of course it raises an error ''Card' object has no attribute 'annotate''. I understand that .get() return an object an not a QuerySet so .annotate doesn't exists as a method of this object. But how to get this object with the annotate? Thanks for your answers -
freenas old ui onflict with materialize material design
I need to introduce material design in my old freenas UI and make it look like new freenas UI (Angular Material Design) but In old freenas there is no Angular. So Now I am using materialize material design with dojo and dojango, but I continuosly face conflicts. Is there any Default Material Design for FreeNAS UI. I already tried: MDBootstrap Google Material Design Materialize Material Design MUI (Needs ReactJS) And many others But None of them helping me to change freeNAS Project UI. Please Help me to fix this issue Thanks in Advance -
Ajax function not working in Internet Explorer
I have a django form with two fields with choices. The goal is that options in field 2 change based on option selected in field 1. This is the code: function field1Ajax(args) { $.ajax(args).done(function(data) { $("select[name='field2'] option").each(function() { var $this = $(this); if($this.val() && $.inArray(parseInt($this.val()), JSON.parse(data)) == -1) { $this.hide(); } else { $this.show(); } }); }); } (function($) { $("select[name='field1']").change(function() { var $this = $(this); $("select[name='field2'] option:first").prop('selected', 'selected'); if($this.val()) { var args = { type:"GET", url:"{% url 'app:get_data' %}", data:{'field1': $this.val()} }; field1Ajax(args); ... } else { ... } }); })(jQuery); It works well in Chrome or Firefox, but not in IE11. The warning I see in IE is: DOM7011: The code on this page disabled back and forward caching. I was hoping someone might recognize why this code would fail in IE. -
How to assign default value using url parameter changelist_filters?
In Django 2.0.6, I want to assign default model field value when adding the data in Django Admin page. Here is my code. models.py class a_model(models.Model): a_field = models.foreignKey(~~) ~~~~ URL (Create page in Admin) http://127.0.0.1:8000/admin/~~~/a_model/add/?_changelist_filters=a_field__exact%3D586632 I want to get 586632 in above url and assign default value to a_field in that page. I try to this way in models.py class a_model(models.Model): @staticmethod def default_id(request): return 586632 a_field = models.foreignKey(~~,default=default_id.__func__,~~) then, I see the default value is 586632 like that I expected. I want to know how to get the url parameter value to assign default value in model class. Help me.. -
Implementing views functions in django
I'm struggling to show some model objects I've created through the admin GUI. I made three or four instances of the JobPost model (models.py is shown below), however I can't get them to show on the webpage through a view function. I'm not sure if the problem lies in the model, the view or the template. I've tried these template variations: jobs.html: {% block content %} <ul> {% for post in latest_post_list %} <li>{{ JobPost }}</li> {% endfor %} </ul> {% else %} <p>No posts are available.</p> {% endif %} {% endblock content %} I've also tried (just as a test): jobs.html: {% if latest_post_list %} {% for post in latest_post_list %} <li>show something</li> {% endfor %} </ul> {% else %} <p>No posts are available.</p> {% endif %} And jobs.html: {% extends "base.html" %} {% block content %} <li>{{ latest_post_list }}</li> {% endblock content %} None worked. The ones with else statements do show the result of the else statement. Views.py: from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.decorators import staff_member_required from .models import JobPost from django.utils import timezone def jobs(request): JobPost.objects.filter(published_date__lte=timezone.now()).order_by('published_date') latest_post_list = JobPost.objects.order_by('-pub_date') context: { 'deadline': deadline, 'created_at': created_at, 'wordcount':wordcount, 'jobtaken':jobtaken, 'JobPost':JobPost, 'latest_post_list':latest_post_list, } return render(request, … -
Implementing publish/subscribe django architecture, supporting realtime api with websocket and django-channels
Hi I'm building a python/django-powered backend that needs to integrate a react frontend and a separate deep-learning module. Our service workflow consists of 3 different modules(client, server, deep learning module), and basic workflow is as follows: Client gets user input in text Server get input text from client, and tosses the text SOMEHOW to deep-learning module that summarizes the text. Returned results from deep-learning module SOMEHOW needs to be push back to client I've been thinking about using django and django channels group for our service, which briefly looks like below: Django server get requests from client and create django-channel 'Group' Send the text using message broker(Redis, RabbitMq or AWS SQS) to deep learning module. The deep learning module is pre-trained and the message is returned by function defined in AWS lambda(serverless) The deep learning module publish the result in the django-channel group Clients(IOS, and desktop) is subscribing to the Group, and result is therefore push to the clients. My question is as follow: Does my idea sound look plausible? Is using message broker between django and deep-learning module best? What if I use websocket here too. Which would be better though? Is there any better way to implement the … -
Django admin UnicodeEncodeError with accent
Everytime I add a character with an accent to an entry in Django admin, such as "à", when I try to Delete it, I get the following error: UnicodeEncodeError 'ascii' codec can't encode character u'\xe0' in position 21: ordinal not in range(128) I defined the following method in my Model: def __unicode__(self): return u'%s' %(self.name) but it didn't change anything. I then tried to return str(self.id) but I still had the same issue, so it doesn't seem like the problem is from the unicode method. Any idea? -
Filter DateTimeField Django Rest Framework
I'm building an API with the django rest framework. I have this model: class Versement(models.Model): date = models.DateTimeField() organisme = models.ForeignKey(Organisme, on_delete=models.CASCADE, null=True) This is my view: class VersementViewSet(viewsets.ModelViewSet): queryset = Versement.objects.all() serializer_class = VersementSerializer pagination_class = StandardResultsSetPagination filter_backends = (filters.SearchFilter, DjangoFilterBackend,) filter_class = VersementFilter search_fields = ('organisme__nom', 'organisme__code') And my filter: class VersementFilter(django_filters.FilterSet): class Meta: model = Versement fields = ['organisme__id'] Is it possible to add the field "date" to my fields and only search for a special year ? For example: {{URL}}/versements/?date=2015 If you guys know how to proceed... Thank you in advance. -
How to only update part of db record parameters with django rest framework when do http put?
I encountered one issue when using django rest framework and want to get help from you. For following code, it is ok to use http GET/POST, but if I use following command to update field para1: curl -X PUT -H 'Content-Type: application/json' -i 'http://127.0.0.1:8000/info/my_key_1/' --data '{"para1": "hi"}' it tells me: { "para2": ["This field is required."], "para3": ["This field is required."], } I know, I can add para2 & para3 when call PUT method, but this is not what I need. I want to know if I can just update para1 without add para2 and para3 as I do not want to change them? Meanwhile, still can get all fileds if I do GET, and still check all fields if I do POST, I mean not discard para2 & para3 from serializer. Any solution? BTW, I use viewsets.ModelViewSet. Next is the main code: urls.py router = SimpleRouter() router.register(r'info', views.InfoView) serializers.py class InfoSerializer(serializers.ModelSerializer): class Meta: model = Info fields = ( 'id', 'key', 'para1', 'para2', 'para3' ) models.py class Info(models.Model): key = models.CharField(max_length=30, unique=True) para1 = models.CharField(max_length=30) para2 = models.CharField(max_length=30) para3 = models.CharField(max_length=30) views.py class InfoView(viewsets.ModelViewSet): lookup_field = 'key' queryset = Info.objects.all() serializer_class = InfoSerializer -
Django + Stripe: Webhooks
I am using Stripe Connect for my Django application. After I read the Stripe documentation I still have few questions unanswered and I wonder if anyone knows the answer. Case 1: Connected account refunds via Stripe Account Webhook sends back > charge.refunded Case 2: Connected account refunds via our platform Platform sends refund call via API and new refund entry is added to refund model in the database Webhook sends back > charge.refunded I hope it's clear how I explained it. But in both cases I receive a webhook. That means I can't just add a new entry to the refund model every time I receive a webhook, as in Case 2 I already added this event to my database. I now have two solutions in mind: 1) I create a new 'log' model containing the event id. Before adding any data to my models, I check if this event was already logged. 2) I only process events coming via webhook, as also API calls lead to an event which will catched sent via webhook. What solution did/would you choose? -
Django built in auth views for password reset - Form not showing
I am trying to use the django.contrib.auth views to allow website users to reset their password. However, the email field for users to enter their email address to reset password is not showing. The form tag is showing instead: This is how it looks like screenshot The following is what I have implemented, mainly only changes made in urls.py and templates. How can I solve this error? Thank you. urls.py from django.urls import path, include, re_path from django.contrib.auth import views as authViews urlpatterns = [ re_path(r'^account/password_reset/$', authViews.password_reset, {'template_name' : 'accounts/reset_password.html' }, name='password_reset'), re_path(r'^account/password_reset/done/$', authViews.password_reset_done, {'template_name': 'accounts/reset_password_done.html'}, name='password_reset_done'), re_path(r'^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', authViews.password_reset_confirm, {'template_name': 'accounts/reset_password_confirm.html'}, name='password_reset_confirm'), re_path(r'^account/reset/done/$', authViews.password_reset_complete, {'template_name': 'accounts/reset_done.html'}, name='password_reset_complete'), ] reset_password.html <p class="text-center">If you have forgotten your password, please type your email address so we can send you a reset link.</p> <form method="post"> {% csrf_token %} <p> {{ form | crispy }} </p> <button type="submit" class="btn btn-secondary mb-3 float-right">Reset Password</button> </form> And the forms.py file is below, although I don't think it's related. Additional information, just in case. forms.py from django import forms from django.forms import ModelForm from .models import Product, Category from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = … -
How to integrate razorpay with saleor?
I am trying to integrate Razorpay with saleor e-commerce app but could not find anything to start with. Can anyone help me in this? -
Django - How to use 3 model in one form?
i want use 3 models in one form to create the View ,i was used modelform when to use 2 models data but i don't know what to do with this. Can any one help me to resolve this class AuthUser(models.Model): id=models.AutoField(db_column='id', primary_key=True) username = models.CharField(unique=True, max_length=150) class AuthUserGroups(models.Model): id=models.AutoField(db_column='id', primary_key=True) user = models.ForeignKey(AuthUser, models.DO_NOTHING) group = models.ForeignKey(AuthGroup, models.DO_NOTHING) class AuthUserUserPermissions(models.Model): user = models.ForeignKey(AuthUser, models.DO_NOTHING) permission = models.ForeignKey(AuthPermission, models.DO_NOTHING) -
Error when trying to use Subquery in calculating time difference
I track how much time people spend on a specific page (I asked several questions regarding this issue here). I register a time when the page is loaded ('Enter' event). And in a separate model I register all 'Exits': when form is submitted, when page is unloaded, etc. This 'ExitEvent' model is connected to EnterEvent model via ForeignKey because one Enter event can and usually does have several corresponding Exit events. EXITTYPES = [(0, 'form submitted'), (1, 'page unloaded'), (2, 'client disconnected')] class EnterEvent(models.Model): page_name = models.CharField(max_length=1000) user = models.ForeignKey(to=User, related_name='enters') timestamp = models.DateTimeField() closed = models.BooleanField(default=False) class ExitEvent(models.Model): enter_event = models.ForeignKey(to=EnterEvent, related_name='exits') timestamp = models.DateTimeField() exit_type = models.IntegerField(choices=EXITTYPES) To calculate time spent by user on a page I use a following code which works correctly: def get_time_per_page(user, page_name): earliest = ExitEvent.objects.filter(enter_event=OuterRef('pk')).order_by('timestamp') delta = timedelta(days=1) a = EnterEvent.objects.filter(closed=True, user=user, page_name=page_name).annotate( earliest_exit=Subquery(earliest.values('timestamp')[:1]), ).values() sum_diff = sum([i['earliest_exit'] - i['timestamp'] for i in a], timedelta()) return sum_diff However when I try to use the results of the subquery in the following annotate queries it fails: b = EnterEvent.objects.filter(closed=True, participant=player.participant, page_name=page_name).annotate( earliest_exit=Subquery(earliest.values('timestamp')[:1]), ).annotate(timespent=ExpressionWrapper(F('earliest_exit') - F('timestamp'), output_field=DurationField())) Error log: Exception Type: TypeError Exception Value: can only concatenate tuple (not "list") to tuple Exception Location: /Users/chapkovski/otree2/lib/python3.6/site-packages/django/db/backends/sqlite3/operations.py … -
what is the best model for five star rating system?
Assume that we have shopping portal, each item has its own ID, Name, Date ... Logged in users can rate each item, see list of items that he/she rated before. What is the best way to implement relational database model? Here is what I wrote : class Item(models.Model): name = models.CharField(max_length=50) image_url = models.CharField(max_length=1000) item_id = models.IntegerField() rate = models.ForeignKey(Rate, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Rate(models.Model): ''' user field to get user id, to know who rated ''' user = models.ForeignKey(User, on_delete=models.CASCADE) # the rate value rate = models.IntegerField() '''to get item_id and the image_url of each item, for listing user rated item list''' ''' ManyToMany Relation, because each user can rate as many as items he wants and each item can be rated by many users''' item = ManyToManyField(Item, on_delete=models.CASCADE) and how to get all of items that user has rated including the rate and the image by queryset filter? -
Django: How to Edit Page with Foreign Key Field set (Unable to edit and post to models)
I am trying to edit a django database via html form. However I am unsure why the following error is appearing. The product category is a foreign key and I can't change it's value. How can I solve the error? Thank you. ValueError at /shop/polyester-cushions/eiffel/edit_product/ Cannot assign "'Polyester Cushions'": "Product.category" must be a "Category" instance. models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) def __str__(self): return '{}'.format(self.name) class Product(models.Model): CATEGORY_CHOICES = ( ("Cotton Cushions", "Cotton Cushions"), ("Polyester Cushions", "Polyester Cushions") ) name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, choices=CATEGORY_CHOICES) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return '{}'.format(self.name) edit_product.html <div class="form-group row"> <label class="col-sm-2 col-form-label">Category</label> <div class="col-sm-10"> <select name="category" class="form-control" value="{{ product.category }}"> <option {% if product.category == "Cotton Cushions" %} selected {% endif %} value="Cotton Cushions">Cotton Cushions</option> <option {% if product.category == "Polyester Cushions" %} selected {% endif %} value="Polyester Cushions">Polyester Cushions</option> </select> </div> </div> -
how to write django form to update the field value in database object(field value+giving value)?
in database table we have a single row with some columns with some values assigned.And now we have to write a django form to update that values and not to overwrite that value?for example 2 is the value assigned first and after we are passing 5,finally the value should be 2+5=7 -
Detect postback in Django
What's the most efficient way of detecting a postback in Django? Does Django provide any out-of-the-box function / property for this? I am using Django 2.0.7 if at all that helps. -
Unable to redirect from views.py
I want to redirect my url through views.py to an HTML page(Chatbot.html). Below is the code which I am using . I can see it is going inside if statement and giving me error errorSyntaxError: Unexpected token < in JSON at position 0 Below is my views.py code from django.shortcuts import render,get_object_or_404,render_to_response from django.http import HttpResponse import json from django.views.generic import TemplateView from django.views import View from .forms import HomeForm from django.http import JsonResponse from .models import Employee class Login(View): def post(self,request,*args,**kwargs): response_data={} response_data['email']= request.POST['email'] response_data['password']= request.POST['password'] data = Employee.objects.all() for emp in data: emailid = emp.usr_email passkey = emp.usr_password if emailid == request.POST['email'] and emp.usr_password == request.POST['password']: return render(request,'bot/chatbot.html') else: return HttpResponse(json.dumps(response_data), content_type="application/json") here is my ajax code $.ajax({ type: "POST", url: "/bot/login/", dataType: "json", async: true, data:{ csrfmiddlewaretoken: '{{ csrf_token }}', email: email, password: password }, success: function(json){ }, error : function(request, status, error) { var val = request.responseText; alert("error"+error); } }); -
relation "pages_page" does not exist
I'm trying to create an ideas landing page using Django, which will allow me to post pages and collect email addresses. Right, my app is up and everything is working fine when I run: python manage.py runserver or heroku local web However, when I try to deploy to Heroku and run; heroku run python manage.py loaddata pages.json I'm getting an error I cannot seem to decipher or fix: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "show_nav" of relation "pages_page" does not exist LINE 17: </div>', "show_nav" = true, "nav_color" = '#820000', "... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 64, in handle self.loaddata(fixture_labels) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 104, in loaddata self.load_label(fixture_label) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 167, in load_label obj.save(using=self.using) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/serializers/base.py", line 201, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, … -
How to send reset email to specific user using in-built django authentication system?
I have created a small app in django which contains authentication feature to save data. I am using django default authentication system for password change and reset. While doing password reset, It sends a mail to the mail id specified in the form. But the problem is, it is fetching the first user's name and sending mail. So the password is being reset to the first user itself. How to send the mail using the specific username entered in the log in page? urls.py: from django.contrib.auth import views as auth_views from django.conf.urls import url,include from . import views app_name = 'set_goals' urlpatterns = [ url(r'^$',views.index,name='index'), url(r'^(?P<pk>[0-9]+)/about/$',views.about,name='about'), url(r'^(?P<pk>[0-9]+)/download/$', views.download, name='download'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^register/$', views.register, name='register'), url(r'^password_change/$',auth_views.password_change,{'post_change_redirect':'set_goals:password_change_done'},name='password_change'), url(r'^password_change/done/$',auth_views.password_change_done,name='password_change_done'), url(r'^password_reset/$',auth_views.password_reset,{'email_template_name':'registration/password_reset_email.html', 'subject_template_name':'registration/password_reset_subject.txt', 'post_reset_redirect':'set_goals:password_reset_done', },name='password_reset'), url(r'^password_reset/done/$',auth_views.password_reset_done,name='password_reset_done'), url(r'^password_reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, {'post_reset_redirect':'set_goals:password_reset_complete'},name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'),] password_reset_mail.html: {% autoescape off %} To initiate the password reset process for your {{ user.get_username }} TestSite Account, click the link below: {{ protocol }}://{{ domain }}{% url 'set_goals:password_reset_confirm' uidb64=uid token=token %} If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. Sincerely, The TestSite Team {% endautoescape %} My question is, How to send the user id of the …