Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
difference between url pattern urls in django
What is the difference between 1. url(r'^$', views.Home.as_view(), name='home'), and 2. url(r'^.*', views.Home.as_view(), name='home'), in view.py: class Home(TemplateView): template_name = "index.html" Output of 1 is it will redirect only to index.html when clicked on the other it says Not Found The requested resource was not found on this server. output of 2nd is: it shows UI pages but backgroup django application apis doesnt execute. -
How to store simplejwt token into database
I'm using django-rest-framework-simplejwt for user registration. Following this tutorial enter link description here I code like following: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( style={'input_type': 'password'}, write_only=True, ) password2 = serializers.CharField( style={'input_type': 'password'},max_length=20 ) tokens = serializers.SerializerMethodField() class Meta: model = UserProfile fields = ['username', 'email', 'password', 'password2', 'tokens'] def get_tokens(self, user): user = UserProfile( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) user.set_password(password) tokens = RefreshToken.for_user(user) refresh = text_type(tokens) access = text_type(tokens.access_token) data = { "refresh": refresh, "access": access } return data def save(self): user = UserProfile( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) user.set_password(password) user.save() return user in view: class UserCreateView(generics.CreateAPIView): '''create user''' serializer_class = RegistrationSerializer The problem is each time I create a user,I can get the return of the 2 two tokens,however in data base I can't find the token. So I guess I didn't store them,so should I store the token? -
How to create a django package without setting DJANGO_SETTINGS_MODULE as environment variable?
I am creating a package that itself uses Django and I will be using it within other Django applications. The main issue I am facing is that I need to use to settings for various reasons such as logging and other extensive requirements. Since, this package does not have any views/urls, we are writing tests and using pytest to run them. The tests will not run without the settings configured. So initially I put the following snippet in the __init__ file in the root app. import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_package.settings") django.setup() Now, the test ran properly and the package as standalone app was working. But the moment I installed it in the main project, it overrides the enviroment variable with it's own settings and you can imagine the kind of havoc it would ensue. This is the first time I am packaging a django app. So I am not well-versed with best practices and the docs are a little convoluted. I read the structure and code of various packages that use settings in their package but I am still not able to understand how to ensure the package accesses the intended settings and the project's settings is not affected … -
How to pass image(any file) from VueJs front end to Django Rest Framework API?
I can upload a file on my Django admin site or from my API but I don't know how to do it from my index.html. I am using axios and tried let data = new FormData(); data.append('file', file) too i just dont know what DRF expect from me and if possible give me some example -
Django app loads slow only for a single view (queries are prefetched and posts are paginated too)
Background I created a free language learning service called LangCorrect.com. It's a place where you can practice writing in a language that you are learning and it will be matched with users who have that language set as their native language. Problem Originally I had all of the journal posts being loaded at once that means three tabs times x # of language posts written. It easily displayed over 70 journal entries at once. I then implemented pagination, but instead of that fixing the problem, it's taking around 3-5 seconds for the page to load. This is only happening on /journal/ On my old staging server which was running a clone of my one week old production server, it was loading super fast. I had to destroy that droplet for reasons, and I made a copy of the latest production server to use as the staging server. But now the staging server is having the same weird issue as my production server. I have no idea where to proceed from here. You can access the service with the following credentials (u: upworkdev pw: textcorrect) and the see the issue here https://langcorrect.com/journal/ What I checked There aren't any issues I can … -
Python: How to convert a list of dates into a list of days for meetings
I am working on a web app in Python/Django and I am trying to make a calendar. I am using Python's HTMLCalendar class found in the calendar module. I have the following in models.py: class Meeting(models.Model): id = models.AutoField(primary_key=True) admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) location = models.CharField(max_length=200, null=True) start_date = models.DateTimeField(default=None, null=True) end_date = models.DateTimeField(default=None, null=True) description = models.CharField(max_length=2000, null=True) The start_date of the meeting is displayed in the following format: 2019-12-03 00:00:00. I am overriding the formatday() function in HTMLCalendar. This function takes a day as a one of its parameters. I have a list of meetings, and if the meeting is on the day that is passed to the function, I want the calendar to display those meetings on the cell for that day in the calendar. For example, say that the day I am considering is the 3rd of a certain month. I want to somehow be able to extract the day of a meeting from the start_date value (e.g. extract the day 3 from the date 2019-12-03). However, I am not what is the best way to do this. Any insights are appreciated. -
Django Stripe SCA 3D Secure Authentication Failure Creates Open Invoice
When a customer tries to pay, but they fail the 3D secure authentication, an open invoice gets created which is undesirable. Then when a customer finally succeeds their 3D secure authentication, they will now have paid for their subscription PLUS they will have an additional count of open outstanding invoices they will need to pay depending on how many times they failed authentication. I need a way to void the invoice or stop the invoice from being created unless the customer succeeds authentication so that no open outstanding invoices get created. Video: https://streamable.com/2z8nk Code: https://dpaste.de/Jfxu https://dpaste.de/2Y37 Tried doing this: http://dpaste.de/561t https://dpaste.de/3Shs Options to fix: 1) Listen for the invoice.updated event, and if the invoice has status "open" fetch the payment_intent and if it's status is requires_payment_method then void the invoice. https://stripe.com/docs/webhooks/build#create-endpoint 2) Send an Ajax request from your client to your server when authentication fails here -> errorElement.textContent = result.error.message. 3) Do not create the new subscription at all. Re-use the incomplete subscription that was tried earlier. Customer comes, they try to pay, create a Subscription, but the charge fails, so you end up with an incomplete subscription. The subscription has its invoice in latest_invoice opened. That invoice has a … -
How to make a selection button inside a multistep form wizard in Django that renders an output without proceeding to the next step?
I am new to Django and I am making a project with a multistep form using django-formtools. The problem is, in my step 2 form, I have selection fields that I need to pass in the backend to perform some calculations and then render the output. The user can make changes anytime based on the output. I made an apply changes button which should trigger the backend process and a proceed to next step button if the user decides to finalize the selected changes. However, when I click the apply changes button, it leads me to the next step instead. Here's my HTML code: <form action="" method="POST"> {% csrf_token %} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ form }} # three selection fields <button name="apply_changes">Apply Changes</button> {% endif %} {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans '&#8249; Previous Step' %}</button> {% endif %} <input type="submit" value="{% trans 'Finish' %}"> </form> Here's my SessionWizardView method code snippet: def get_context_data(self, form, **kwargs): context = super(StepWizard, self).get_context_data(form=form, **kwargs) if self.steps.current == 'step_1': # save step 1 data to sessions if … -
Should I use JWT or Sessions for my eCommerce website?
I'm building an eCommerce website for a personal project. It uses React for the front-end and a REST API running on django for the back-end. I want the user to be able to add items to a shopping cart and place an order without the need for an account. For guest users, using a session/cookie to store info is great, but when it comes to logged in users, I would want to use the database to store items in a cart. That would require creating a user and giving them an auth token so they can perform necessary actions. So should I use session/cookie authentication or is there a better way to achieve what I want using JWT? -
django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
I want to save data from the Django model to PostgreSQL database with: mymodel.objects.create(title='test') this model only has title and id but it raises this error: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint how can I fix it? why id is not set automatically as always? -
How to concatenate a varibale from a function in a form action with Django?
i want to concatenate a variable in a form action. for example: <form action:"{% url 'addAlumn' ${id} %}" method="POST"> im sure im wrong but i dont have idea how to do this. this is my function: <script> function alumno(obj, obj2, obj3, obj4) { id = obj; var no_certificado = obj2; var nom = obj3; var curp = obj4; $("#nombre").val(nom); $("#cert").val(no_certificado); $("#curp").val(curp); } </script> -
Django 2 models referencing to each other
I'd like to have 2 models called OrderItem and Order in the same py file and they are connecting to each other. Here is my current code but I got the error when making a migration. I was looking at https://docs.djangoproject.com/en/2.2/ref/models/fields/#foreignkey orders.Order.order_items: (fields.E303) Reverse query name for 'Order.order_items' clashes with field name 'OrderItem.order'. HINT: Rename field 'OrderItem.order', or add/change a related_name argument to the definition for field 'Order.order_items'. class OrderItem(models.Model): """Model representing an order item. """ PIZZA_TYPE_CHOICES = [ ('MARGHERITA', 'Margherita'), ('MARINARA', 'Marinara'), ('SALAMI', 'Salami'), ] PIZZA_SIZE_CHOICES = [(i, i) for i in [25, 35, 40]] order = models.ForeignKey( 'Order', on_delete=models.CASCADE) pizza_type = models.CharField(max_length=20, choices=PIZZA_TYPE_CHOICES) pizza_size = models.IntegerField(choices=PIZZA_SIZE_CHOICES) quantity = models.IntegerField(validators=[MaxValueValidator(99)]) def __str__(self): return self.pizza_type class Order(models.Model): """Model representing an order.""" ORDER_STATUS_CHOICES = ( ('NEW', 'New'), ('PROCESSING', 'Processing'), ('DELIVERING', 'Delivering'), ('DELIVERED', 'Delivered'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='order', on_delete=models.CASCADE) order_items = models.ManyToManyField(OrderItem) order_status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default=ORDER_STATUS_CHOICES[0][0]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username How can I solve this? -
Laying out django-markdownx preview widget in a different place
I'm writing a simple notetaking app using Django, and I have come across django-markdownx. In short, it's great and it's exactly what I need, however I'm having an issue with laying out preview widget to be where I want. So, currently, the rendered text is displayed below my textarea, and I want them side by side. I found this, but haven't successfully tailored it so it suits my needs. The widgets seem to be dependant upon each other, i.e. they have to go into the same template, and I would like to lay them out the way I want in my own template which looks roughly like this: <div class="form-wrapper"> <div class="form-header"> Create a new note </div> [...] <form method="POST"> [...] </form> </div> <div class="preview"> <!-- Preview widget should go here --> </div> Can I somehow overcome this issue? -
how to pass multiple value from select element and pass to django views and print it in cmd
so i have a select element which i can append it depends on the user , i need to retrieve the multiple value(if the user need pick more than 1 options) and i need to pass it to django views after the user click submits #script to append box <script> function appendBox() { $('#test').append('<select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;margin-top:5px"></select>') } </script> #script to check wheter the multiple value that user choose is right <script> function passingval() { var inputs = $(".columnselect"); for(var i = 0;i<inputs.length;i++){ alert($(inputs[i]).val()); } } </script> #some snippet in my select element <div class="form-group"> <button class="btn btn-theme" onclick="appendBox()">Add</button> <label class="control-label col-md-3">Column Name</label> <div class="col-md-4" id ="test"> <div class="input-group bootstrap-timepicker"> <div class="btn-group"> <select class ="columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"> </select> </div> </div> </div> </div> #button <button class="btn btn-theme" onclick="passingval()" href="{% url 'polls:printvalue' %}">submit</button> #html in new page to make the option appear(because i use ajax) <option> -------------------- </option> {% for data in obj %} <option value="{{data}}">{{data}}</option> {% endfor %} urls.py urlpatterns = [ path('', views.login_view, name='login'), path('home/', views.index_view, name='indexing'), path('profile/', views.profile_view, name='profile'), path('chatroom/', views.chatroom, name='chat_room'), path('lockscreen/', views.lockscreen, name='lock_screen'), path('newsegment/', views.createsegment, name='newsegment'), path('definesegment/', views.list_all_table, name='definesegment'), path('manageuser/', views.manageuser, name='manageuser'), path('approvallist/', views.approvallist, name='approvallist'), path('approvalhistory/', views.approvalhistory, name='approvalhistory'), path('load-data/',views.list_all_tabledependent, name = 'load-data'), path('load-column/',views.list_all_column,name='load-column'), path('logout/',views.logout,name='logout'), path('definesegment/',views.printallvalue, name ='printvalue'), # … -
API state design pattern in python
as I understood, Is the following code sufficient for the attached question? please need your help to clarify the missing points or parts, should I add some exceptions catching, should edit_title & edit_description be only in the New class() or abstract in the TaskAPI class() and override it inside child classes , should i use the Django rest framework API, below the in-progress state is written 'link two tasks you should be able to call both of them using any id' what does that mean. # States of a Task class TaskAPI(object): """ Abstract base class of state of a task """ name = "state" allowed = [] def switch(self, state): """ Switch to new state """ if state.name in self.allowed: print('Current:', self, ' => switched to new state', state.name) self.__class__ = state # print( self.__class__) else: print('Current:', self, ' => switching to', state.name, 'not possible.') def __str__(self): return self.name class New(TaskAPI): """ New State being in progress """ name = "New" allowed = ['InProgress'] def edit_title(self,new_title): self.title = new_title def edit_description(self,new_description): self.new_description = new_description class InProgress(TaskAPI): """ State of being in progress after New state and need to switched to be done """ name = "InProgress" allowed = ['Done'] … -
Django: NullBooleanField value False not restored properly from MySQL Database
When I save a False value in a models.NullBooleanField in my database it is correctly stored as 0 in the DB. When reading it Django assigns None. Here is a small code snippet to reproduce: model.py: class Test(models.Model): foo = models.NullBooleanField() def __str__(self): return f'{self.foo}' test.py: from data.models import Test import subprocess def run(): print("created in Django:") for val in [None, True, False]: t = Test(foo=val) t.save() print(t) print("\nSQL from Database:") cmdResult = subprocess.getoutput("mysql -N -u user -ppass, -e 'select foo from data_test;' mydb") print(cmdResult) print("\nDjango read from Database:") for test in Test.objects.all(): print(test) and this is the result: created in Django: None True False SQL from Database: NULL 1 0 Django read from Database: None True None I would expect the last value to be False. I have also tried with a BooleanField with null=True. Since it is stated in the docs that this may be deprecated in future. Nevertheless the same error occurs. I also now how to workaround this problem using another field type. But I would like to understand where my mistake is. As this should be running as expected, shouldn't it? Thanks a lot for your time and hints. -
Is it possible to use my existing HTML/CSS/JS with a move to Django?
I'm working on a full stack web application for a class, and originally was going to use AWS S3 for hosting, Dynamo as a database, Lambda for passing data to and from Dynamo, and Gateway API to connect the front and back end, but have had nothing but issues with AWS. As this is just a class project, nothing needs to be remotely hosted, and a classmate suggested Django to allow us to completely ditch AWS. After looking through a lot of the introductory stuff for Django, it looks like it could be the magic bullet we need. However, we already have dozens of hours sunk into our frontend HTML/CSS/Javascript, as well as some Bootstrap. My only reservation about making a complete dive for Django for handling our database and enabling us to run everything off localhost is that it seems to do EVERYTHING in Python, and I don't immediately see any way to integrate our existing frontend. Our frontend JS is intended to receive data from the database and do rudimentary calculations with it before providing it to the HTML page, and I'm also not sure how this would integrate with Django and SQLite. -
How can I add custom fields when creating a sign up form using Django form?
I am very much a beginner to Django and just Python overall, but I am trying to create a relatively simple web app and I seem to be running into some obstacles. I would like to add custom fields to my Django UserCreationForm like first name, last name, email and ID number? Should I create a separate Profile model and if so how should I do that, or is there some other way to achieve this? Like I said, I am a beginner so I would appreciate as much detail as possible! -
Trying to update model data with ajax from DetailView?
I would like to do: I am trying to create a form input on a detail view that will update a particular data column ('status') of the detailed model instance. Here is a picture of what I have in mind: The selector would display the current status and the user could change it and update from the detail view without having to access the UpdateView. my idea here would be to have this happen: 1. On submit, get the new user entered value. 2. get the model instance of the currently detailed class 3. assign the model instance attribute as the user entered value 4. save the model instance I've tried: I don't know if this is the best way to do this but i've been trying to create an AJAX call, mostly by looking for examples online. Results: Terminal shows Post on submit: "[19/Nov/2019 17:50:33] "POST /task/edit/4 HTTP/1.1" 200 41256". However, the data is not saved to the db. On refresh, the selector returns to previously saved status. The console shows: "script is connected", and "Update Status" with no errors. On submit, the alert displays success message: "127.0.0.1:8000 says status updated". Task_detail.html <div class="deliv-box edit"> <form id="status-update-form" method='POST' action='{% … -
Why is a CSS file not changing the colors of HTML tags on Django project?
I've been working on adding css styles to my django web project, but I noticed something odd I can't understand. My page is succesfully adding or removing a gif when I add it or remove it in my css file, but the color of my labels, for instance, doesn't change. This is my simple css file that works this way: li a { color: green; } body { background: white url("images/background.gif") no-repeat; } When in my browser, I can see if I delete the second statement, the gif no longer appears, but whether I delete or not the first one, all text is still black. I also tried this: h1 a, h2 a { color: #C25100; } But it works the same, it doesn't change any text, and the document has many different tags, and none is affected. I include the css in my html file like this: <link rel="stylesheet" type="text/css" href="{% static 'app_name/style.css' %}"> When I first figured it out, I had bootstrap linked too, but I removed it and it changed nothing. -
How to update a single field from modal form in Django?
I have a form that keeps track of when people enter/leave different areas. Whenever there is a discrepancy, for example, someone forgets to "leave" an area before entering a new one, the user is prompted an "estimate" of the time they believe they left the previous area at(edited_timestamp). The only two required fields on the main form are the employee number and the work area, as these are used to verify/keep track of data. When I try to reproduce the situation that would make the modal show up, it works, but when I attempt to submit it, I get these messages: and these are the errors that are being returned. Now, while I don't understand why the "Enter valid date/time" error is showing, I'm guessing the other two errors are due to the main form requiring the employee_number and the work_area and probably for this request, even though it is updating by the ID, it still wants the other two fields. I guess my question is, how could I modify this so that these two fields are not required for the modal? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, … -
atomic requests in django form
I'm trying to implement atomic requests in CreateView, so I can check how many times users entered given code, so if they satisfy the condition they will be redirected to success page if not redirect to try again page, currently doing something like this: class IpadCodeView(CreateView): model = IpadCode form_class = IpadCodeForm template_name = 'giveaway/index.html' @transaction.atomic def form_valid(self, form): if form.is_valid(): instance = form.save(commit=False) if instance == COUNT_GAP: instance.save() return HttpResponseRedirect('success') else: return HttpResponseRedirect('you-lose') First time doing this, so does it make sense to use atomic transactions in form like this? -
deleting a user django rest framework knox
users are able to create an account and login. How would users be able to delete their own account? thought I would be able to do it with a delete request with the token. would i need to make another viewset for deleteAccount so users can remove their account by using the token? Currently use knox token authentication serializer from rest_framework import serializers from django.contrib.auth import authenticate from django.contrib.auth import get_user_model User = get_user_model() # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( validated_data['username'], validated_data['email'], validated_data['password']) return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") viewset from rest_framework import generics, permissions, viewsets from rest_framework.response import Response from knox.models import AuthToken from users.models import User from .serializers import UserSerializer, RegisterSerializer, LoginSerializer # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login … -
django postgresql CASE types interval and integer cannot be matched
In Django I'm creating a queryset query with annotation. This is part of it: days_calc = Case( When(Q(received_date__isnull=True), then=ExpressionWrapper(timezone.now().date() - F('due_date'), output_field=DurationField())), ) The query that it creates looks like this (the relevant part)- WHEN "item"."received_date" IS NULL THEN ('2019-11-19' - "item"."due_date") And I get this error: ERROR: CASE types interval and integer cannot be matched LINE 51: ...item"."received_date" IS NULL THEN ('2019-11-1... ^ What am I doing wrong? They are both dates (item.due_date is of type models.DateField). I noticed that if I'm using timezone.now() instead of timezone.now().date() it works, but then I get the value not in the required format. -
Django Database Structure for Time Series Data?
I am developing an app that allows users to choose an ocean buoy and then explore its historical time series data via interactive plotly plots. My end goal is that the user can input a location, which then loads a buoy's data, and the user can then choose filters for which data they'd like to have plotted (so basically a dashboard). For example, maybe they'd like to view only swells that were larger than 1 ft and occurred in the month of August. I know how to do this using pandas and plotly, but I'm struggling with how to transfer this to a django database framework. The code currently creates a buoy object that has a data attribute. This data attribute is a dictionary that is structured as follows: {'stdmet':{'meta':{dictionary of metadata}, 'data':[pandas dataframe of time series data]}} I have the data in a pandas dataframe as it allows me to easily manipulate and create plotly interactive plots. My question is how should I save this to a django model? I think I should have a buoy class which has fields for the meta data (e.g., buoy ID, lat/lon, etc.) and then I'd like to have a final field for …