Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
calling create_superuser and create_user function in abstractuser in DRF
I have customuser model which inherits the Abstratuser from Django. However, I didn't understand the create_user and create_superuser. For eg when is the create_user function is called and when the create_superuser function is called. The model looks like this. class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self,first_name,last_name,email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) #user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name,last_name,email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(first_name,last_name,email, password, **extra_fields) ROLE = (('admin','ADMIN'),('manager','MANAGER'),('staff','STAFF')) class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] role = models.CharField(max_length=15, choices=ROLE, default='staff') objects = CustomUserManager() def __str__(self): return self.email For eg for other regular models like Contacts, … -
Token invalid : Token must be in class <'bytes'>
I am trying to decode the token from the user.Every Time I run the code it show Decode error class PasswordChange(generics.GenericAPIView): model = CustomUser serializer_class = PasswordChangeSerializer def patch(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) payload = jwt.decode(serializer['token'], settings.SECRET_KEY,algorithms=['HS256']) user = CustomUser.objects.get(id=payload['user_id']) if user.check_password(serializer['old_password']): user.set_password(serializer['new_password']) user.save() -
Django REST Framework - XMLRenderer modifying my simple XML response
I want to send a simple CXML text string as below as a response to a DRF POST request to a django view (see my django view below) <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.011/cXML.dtd"><cXML payloadID="2021-10- 19T03:57:08.416995@example.com" timestamp="2021-10-19T04:01:56.530426+00:00"><Response><Status code="200" text="Success" /></Response></cXML> (Above string is value of 'response_cxml' variable in my django view below) But what django sends and is received by the remote app is: <?xml version="1.0" encoding="utf-8"?> <root>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.011/cXML.dtd"&gt;&lt;cXML payloadID="2021-10- 19T05:10:41.115609@example.com" timestamp="2021-10- 19T05:10:41.115674+00:00"&gt;&lt;Response&gt;&lt;Status code="200" text="Success" /&gt;&lt;/Response&gt;&lt;/cXML&gt;</root> XMLREnderer I believe is adding extra duplicate version tag and 'root' tag.It is also urlencoding xml characters like <,> etc.How can I prevent XMLREnderer modifying my response? The sender HTTP headers are Accept= "text/xml and content-type='text/xml' My view: @csrf_exempt @api_view(['PUT','POST']) @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) @renderer_classes([XMLRenderer]) @parser_classes([XMLParser]) def purchase_order(request): """ Receives the purchase order cXML and saves PO details to database. Sends a 200 response back """ if request.method == 'PUT' or request.method == 'POST': po_cxml = request.body.decode() response_cxml = process_po_cxml(po_cxml) return Response( response_cxml.encode('utf-8')) -
How to automatically archive the content of a page when the csv file(the data holder) changes
I am developing a sports site that will require data feeding using csv file from a dynamic source. I am done with the scripting but what I don't know is how to still be able to show the previous information on the old csv file as the newly uploaded csv will automatically replace the view output. -
how to check if a model table is created or not
Im trying to create a tuple from another model's objects and use it in another model. it works just fine but when when I want to start my app and makemigrations, it gives me the error that the model you are trying to use is not created yet, obviously! therefore, I need an if statement to check if that model table is not created dont do anything. this is my Model: class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) and my tuple: INTERESTS = (Field.objects.values_list('slug', 'title')) and this is the error I get: django.db.utils.OperationalError: no such table: reg_field how can I bypass this error? I need something like this: if Field exists then: INTERESTS = the above, else INTERESTS = () -
Double AWS S3 model for Heroku
I have tried to figure out why my dynamic url that I deployed with heroku. Have anyone else experienced this with AWS s3 deploying to heroku. If so please give me some insight because it would be very helpful <img src="https://python-nailsent-demo.herokuapp.com/https://nailsent-demo.s3.amazonaws.com/media/media/abstract_art.jpg?AWSAccessKeyId=AKIAU7F3NAWYGCEKU6OL&amp;Signature=NsgA9TPSrDCw%2FwEdlr3bLP7tPew%3D&amp;Expires=1634627743" alt="0 Slide"> -
Error occur when trying to run server in django project
You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): appname. Run 'python manage.py migrate' to apply them. -
Django how to add html style for javascipt loadmore button?
I added load more button using JavaScript in my blog page which will dynamically load content. But I don't know how to implement my original html style to JavaScript load more button. This is my original html style: {% for filt in object_list %} <div class="card mb-4"> {% if not filt.blog_cover_image %} <img class="img-fluid rounded" style="max-height:1000px;max-width:1200px;" src="https://via.placeholder.com/900x300" alt="..." /> {% else %} <img class="img-fluid rounded" style="max-height:1000px;max-width:1200px;" src="{{ filt.blog_cover_image.url }}" alt="..." /> {%endif%} <div class="card-body"> <h2 class="card-title"><a href="{% url 'blog:blog-detail' filt.slug %}">{{filt.title}}</a></h2> <p class="card-text">{{filt.body|striptags|safe|slice:":250" }}</p> <a class="btn btn-primary" href="{% url 'blog:blog-detail' filt.slug %}">Read More →</a> </div> <div class="card-footer text-muted"> Posted on ({{filt.created_at}}) <div class="author">{{filt.author.first_name}}&nbsp{{filt.author.last_name}}&nbsp;{% if user.is_authenticated %}{% if user.id == blog.author.id or user.is_superuser %}<a href="{% url 'blog:blog-update' filt.slug %}"><b>(Edit Blog)</b></a>&nbsp;<a href="{% url 'blog:blog-delete' filt.slug %}"><b>(Delete Blog)</b></a>{% endif %}{% endif %}</div> </div> </div> {% endfor %} <----javascript load more html---> <div id="posts-box"></div> <div id="spinner-box" class="not-visible"> <div class="spinner-border text-primary" role="status"></div> </div> <div id="loading-box"> <button class="btn btn-primary" id="load-btn">Load more</button> </div> here is my javascript code: const postsBox = document.getElementById('posts-box') console.log(postsBox) const spinnerBox = document.getElementById('spinner-box') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loading-box') let visible = 3 const handleGetData = () => { $.ajax({ type: 'GET', url: `/posts-json/${visible}/`, success: function(response){ maxSize = response.max const data … -
Django send email: django.core.exceptions.ImproperlyConfigured error
I am trying to send a test email in Django with "send_email" function but getting an exception of "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Via py shell however everything works. I have tried to set "set DJANGO_SETTINGS_MODULE=mysite.settings" (Windows), and include it in PyCharm Env Variables and also run "django-admin dbshell --settings mysite.settings". The last produced an exception ModuleNotFoundError. I cannot get what it the problem, sending email via python smtp lib works and via django does not. -
Heroku error H10 when deploying Django app
my problem is that when i'm trying to deploy Django app on heroku, i get that H10 error, and obviously cant access the site. heroku logs --tail dont show anything specific beside that H10 error code at=error code=H10 desc="App crashed" method=GET My Procfile is loading web processes, so it's in the right place i guess, but i belive that maybe configuration of that web process is wrong. I had a problem with H14 error which was caused, because i had Procfile in wrong directory. It was directory of the project where manage.py file is sitting. I had to move it one directory above, because it was root file of my repository(.git file was sitting there). This is my Procfile: web: gunicorn api_project.wsgi My directory tree is like: ROOT/ ├─ .git/ ├─ Procfile ├─ api_project/ │ ├─ api_project/ │ ├─ manage.py │ ├─ robots.txt ├─ .gitignore And wsgi file is inside that send api_project dir. Maybe the path inside the Procfile should be diffrent? -
Django Having Error in Production on an ajax request
I am creating a django project and I tried with a guide. I have my code working in Development, but once I pushed code to production, I get errors on ajax requests. I see the error is happening on the views level where I get the keys and the key is a field named "text". In development, using this for submission of quizzes works perfectly well, but in development, it doesn't. I tried using pk for the submission and it returns errors and is unable to create an accurate result instance. Below are my model's instances and views. Error File "/home/django/.local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( quiz.models.Question.DoesNotExist: Question matching query does not exist. models.py from django.db import models import random from account.models import Profile from django.urls import reverse import datetime from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(publish_book=True) class Book(models.Model): name = models.CharField(max_length=120) description = models.TextField() created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL) number_of_questions = models.IntegerField() number_of_sections = models.IntegerField() time = models.IntegerField(help_text="duration of the quiz in minutes") required_score_to_pass = models.IntegerField(help_text="required score in %") start_date = models.DateTimeField(default=timezone.now) publish_book = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) objects = models.Manager() published = PublishedBookManager() def __str__(self): … -
Leaflet Vector grid call url only when map zoom/pan stops
I am using Leaflet.VectorGrid in my react frontend which is fetching dynamic vector tiles from django backend (ST_MVT). Everything is working fine but when user scroll or pan multiple times, all the requests are sent to the backend and after processing all the requests, vector tiles are shown in the front end. Is there any way to wait for the user to finish zoom/pan and only then send the requests to backend. Attached is a demo video -
django can't delete user getting this error "FOREIGN KEY constraint failed"
I am trying to delete an specific user from admin panel but I am getting this error FOREIGN KEY constraint failed. Why I can't delete the user? why I am getting this error? here is full error log of my console: return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed [19/Oct/2021 11:32:00] "POST /admin/members/usermanagement/ HTTP/1.1" 500 172740 -
How can I use this objectmixins in my functional based views?
I am trying to implement a user activity tracking app in my project. I want to track user each and every click. Can anyone help me in implementing this. although I have tried , I am stucked here while getting objects. Help me in implementing this object mixins into my functional based views. Here is my models.py: # Create your models here. from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.conf import settings from .signals import object_viewed_signal User = settings.AUTH_USER_MODEL class History(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() viewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s viewed: %s" %(self.content_object, self.viewed_on) class Meta: verbose_name_plural = "Histories" def object_viewed_receiver(sender, instance, request, *args, **kwargs): new_history = History.objects.create( user = request.user, content_type = ContentType.objects.get_for_model(sender), object_id = instance.id ) object_viewed_signal.connect(object_viewed_receiver) and this is my views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.views.generic import ListView, View from django.views.generic.detail import SingleObjectMixin from .models import History from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.views.generic import ListView, View from django.views.generic.detail import SingleObjectMixin from .models import History class HistoryList(ListView): def … -
I was trying this code with the help of folium and pandas but it is showing this error
import folium import pandas data= pandas.read_csv("Volcanoes.txt") lat= list(data["LAT"]) lon= list(data["LON"]) elev = list(data["ELEV"]) def color_producer(elevation): if elevation<1000: return 'green' elif 1000<=elevation<3000: return 'orange' else: return 'red' Fg= folium.FeatureGroup(name= "My Map") for lt,ln,el in zip(lat,lon,elev): fg.add_child(folium.Marker(location=[lt,ln], popup=str(el)+" m", icon=folium.Icon(color=color_producer(el)))) map.add_child(fg) map.save("Map1.html") this code returns the following error :"Object of type function is not JSON serializable" -
Reverse for 'profile_view' with arguments '('',)' not found. 1 pattern(s) tried: ['in/(?P<username>[^/]+)/$']
views.py User = get_user_model() class ProfileView(View): def get(self, request, *args ,**kwargs): username = kwargs.get('username') try: user = User.objects.get(username=username) except Exception as e: return HttpResponse('This page does not exist. ') if username == request.user.username: context = { 'user': user } return render (request, 'authprofile.html' , context=context) else: context = { 'user': user } return render (request, 'authprofile.html' , context=context)## urls.py from user.views import ProfileView urlpatterns = [ path('in/str:username/',login_required(ProfileView.as_view()),name='profile_view'), -
PM2 vs Gunicorn: Equivalent Gunicorn setup of PM2's fork_mode
We have a staging server for running our web app's current state under our develop git branch. It is running a Next.js component for frontend purposes, and Django for web API (using DRF). As a staging server, we have not fully set it up as that of a production server, where we would normally use Gunicorn. Instead, we are running both Next and Django app using PM2 in cluster_mode and fork_mode, respectively. In our production server, we are running Django on Gunicorn using parallelism with the most basic setup of just setting the workers without necessarily using worker_connection and threads like that of gevent or gthread, respectively. I am wondering, with PM2, what is the equivalent behavior of its fork_mode in Gunicorn? (Like does fork_mode work like that of gevent or gthread? Is it running on concurrency instead of being parallel?) I want to know if PM2's fork_mode is implementing threading or concurrency. If it is, then it might be the reason why Django API request thru our staging server running PM2 fork_mode is causing significant delays, or sometimes causes delays on initial request after some inactivity. With the current state of our Django app's codebase, parallelism works best, which … -
Django REST Framework - "Must be Device instance" error when calling PUT from javascript
I'm getting an error when trying to update an object instance using PUT using the rest framework: ValueError: Cannot assign "{'id': UUID('954...8b4')}": "DeviceConfig.device" must be a "Device" instance. view defn: class DeviceConfigViewSet(viewsets.ModelViewSet): #todo: secure authentication_classes = [] queryset = DeviceConfig.objects.all().order_by('device') def get_queryset(self): device = self.get_renderer_context()["request"].query_params.get('device') if device: return DeviceConfig.objects.filter(device=Device(device=device))[0:] else: return self.queryset serializer_class = DeviceConfigSerializer DeviceConfig model: class DeviceConfig(models.Model): device = models.OneToOneField(Device,primary_key=True,on_delete=models.CASCADE) bpm = models.DecimalField(max_digits=22, decimal_places=3, blank=True, null=True, default=0.5) duty = models.DecimalField(max_digits=22, decimal_places=4, blank=True, null=True, default=0.022) ledState = models.IntegerField( default=255, validators=[MaxValueValidator(255), MinValueValidator(0)] ) pressureMax = models.IntegerField( blank=True, null=True, default=70, validators=[MaxValueValidator(255), MinValueValidator(10)]) JS func FE side: function formSubmit(){ var myForm = document.getElementById("config-form"); var formObj = new FormData(myForm); var object = {}; formObj.forEach(function(value, key){ object[key] = value; }); object["device"] = DEVICE_UUID; const putMethod = { method: 'PUT', headers: { 'Content-type': 'application/json; charset=UTF-8' // Indicates the content }, body: JSON.stringify(object) } fetch("http://localhost:81/configs/"+DEVICE_UUID, putMethod); } I've tried not sending the device ID from the front end but it gives me a 400 then the ol' goog search didn't turn up much for me this time, but I'm not quite sure how to send a Device instance from the client side besides by it's pk which is what I've tried -
Django URL Path from DB file value
I am trying to create 'project' pages that have their paths generated with the {{ project.title }} values, rather than the current method I have which uses ints. I don't quite understand how I can do this, but feel I am close? Models.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='projects/static/img/') live = models.URLField() source = models.URLField() def __str__(self): return self.title Urls.py from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="projects"), path("<int:pk>/", views.project_details, name="project_details"), # PK for Primary Key ] Views.py from django.shortcuts import render from .models import Project # Create your views here. def project_index(request): projects = Project.objects.all() context = {'projects': projects} return render(request, 'projects/project_index.html', context) def project_details(request, pk): project = Project.objects.get(pk=pk) context = {'project': project} return render(request, 'projects/project_details.html', context) I figure path("<int:pk>/", will need to be a slug, but I just cannot figure out how to tie in the DB data. Potentially context = {'project': project}? Currently the url is http://127.0.0.1:8000/projects/1/ - I am looking for http://127.0.0.1:8000/projects/EXAMPLE/ Thanks -
Different serializer for Create view depending on request.data type?
I'm trying to set-up a Create view that allows for creating a single object or nested objects depending on if the payload is a dictionary or a list respectively. # views.py class CreateAPIView(generics.CreateAPIView): queryset = Item.objects.all() def get_serializer_class(self): print("get_serializer_class runs") if type(self.request.data.__class__.__name__) == "dict": return SingleItemSerializer else: return NestedItemSerializer # dictionary single_payload = {"name": "A"} # list multiple_payload = [ {"name": "B", children: [ {"name": "C", children: []} ]}, {"name": "D", children: []}, {"name": "E", children: []}, ] # Works fine. "get_serializer_class runs" is printed. Returns HTTP_201 response = APIClient().post(CreateAPIView_URL, single_payload) # Doesn't work. "get_serializer_class runs" is not even printed. Returns HTTP_401 response = APIClient().post(CreateAPIView_URL, multiple_payload) I've tried converting multiple_payload to JSON, including format="json" in the APIClient().post(), adding JSON renderer and parser to the view... but multiple_payload doesn't work. The part that's really throwing me off is the fact that get_serializer_class runs isn't even printed for the multiple_payload -
Heroku DB above limit's
Heroku send an email that my database is (Above limits, access disruption imminent). But the problem is I upgraded my DB a year ago from Hobby dev -> Hobby basic, I think hobby dev is still saving data from my app. It's okay to delete Hobby Dev DB? without affecting current data inside my app? heroku pg:info -
too many values to unpack (expected 2), while importing to django database
I am getting error on importing to data base in Django as shown below, I have more than this field on database, but it can be blank or having a default value. def user_upload(request): template = "super_admin/user_upload.html" data = User.objects.all() prompt = { 'order': 'Order of the CSV should be username, ' 'first_name, last_name, email, add_1, add_2,' ' suburb, state, postcode, country', 'Users': data } if request.method == "GET": return render(request, template, prompt) try: csv_file = request.FILES['file'] except MultiValueDictKeyError: csv_file = None if csv_file: if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') if csv_file: data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for row_count, column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 10: try: user = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], city=column[7], state=column[8], postcode=column[9], country=column[10], ) user.set_password('password') user.is_approved = 't-1' user.added_by_admin = True user.save() except (IntegrityError, ValueError) as e: pass return render_to_response('snippets/message_2.html') context = {} return render(request, template, context) else: messages.error(request, 'Please select a valid file!') return redirect('home') the csv file I am trying to upload is below, what would be the cause, seeking an advice. -
Prevent Double Click in JS for in browser game using Django 2.2
I have an issue where it requires the button to be clicked twice in order to initiate the functions. Except that the first click initiates gameOver() and a second click initiates a gameOver() again. But it takes two clicks to initiate showGame() and hideStartBtn() Therefore at the end of the timer ends it pops up two alerts since it loops twice. Question is: How can I prevent double click and activate all the functions in a single click? Here's a repo. $ git clone https://github.com/carlitos-206/js-browser-game-django.git JS - Snippet function showGame() { var game = document.getElementById("the-game"); if (game.style.display === "none") { game.style.display = "block"; } else { game.style.display = "none"; } }; function hideStartBtn() { var StartBtn = document.getElementById("game-btn"); if (StartBtn.style.display === "block") { StartBtn.style.display = "none"; } else { StartBtn.style.display = "block"; } }; var killCount = 0; function kill_1() { var killBtn = document.getElementById("kill-1") if (killBtn.style.display === "block") { killBtn.style.display = "none"; killCount ++; } else { killBtn.style.display = "block"; } }; //This function repeats kill_1 - kill_7 function kill_7() { var killBtn = document.getElementById("kill-7") if (killBtn.style.display === "block") { killBtn.style.display = "none"; killCount ++; } else { killBtn.style.display = "block"; }; }; function gameOver() { var timeLeft = … -
redirect to previous page after successful admin login
I have authorized.html page which needs a admin login to view so when I go to http://127.0.0.1:8000/authorized/ it takes me to http://127.0.0.1:8000/admin/login/?next=/admin/%3Fnext%3D/authorized/, which is expected. I used the below code in view.py file to built this functionality: class authorizedView(LoginRequiredMixin,TemplateView): template_name = 'home/authorized.html' login_url = '/admin/' But after the successful admin login it didn't take me back to authorized.html instead it directs to http://127.0.0.1:8000/admin/?next=/authorized/ which is just admin page and not the page that I want authorized.html. How to do this? Please provide the detailed steps, i'am new to django! -
Procfile problem when deploying django app on heroku
my problem is that i'm trying to deploy django app on heroku, but everytime when i deploy it and try to open it, i get that error at=error code=H14 desc="No web processes running" method=GET path="/"... I created plain file called "Procfile" with this inside: web: gunicorn api_project.wsgi Also checked few hundreed times if api_project is my root directory, and if Procfile is actually in that directory, and it is indeed. Also checked if i commited all changes, and i did many times. Also tried with heroku ps:scale web=1 command and got this error: Couldn't find that process type (web). Also tried with rebuilding packages and it didn't worked. Also checked if gunicorn is in my requirements file and it indeed is. I dont know what else i could try. Here is proof that my Procfile is in correct directory