Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with django request,get user from bd
I have little problem with request to bd. I cant get users from bd.Maybe I didnt something wrong.I think,problem in request. Maybe, I think, I have error in views.py. view.py def registerform(request): ##registerform form = SightUp(request.POST or None) if form.is_valid(): user_obj = form.save()#Сохранение значений в датабазе методом .save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') email = form.cleaned_data.get('email') user = authenticate(username=username,password =raw_password,email=email) login(request,user) return redirect('/userprofile/')# ЗАМЕНИТЬ context = {'form':form } return render(request,'user.html',context) #def userprofiles(request): # userall = detailsuser.objects.all() # context = { # 'objects':userall # } # return render(request,'userprofile.html', context) class UserView(ListView): model = User template_name = 'userprofile.html' context = 'detailsuser' def get_queryset(self): return detailsuser.objects.filter(user = self.request.user) forms.py class SightUp(UserCreationForm): first_name = forms.CharField( widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name') last_name = forms.CharField( widget = forms.TextInput(attrs={'class':'form-control','placeholder':'Last name'}), max_length=32) email = forms.EmailField(widget =forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Email'}), max_length =64,help_text='Enter valid Email') username = forms.CharField(widget =forms.TextInput(attrs={'class':'form-control','placeholder':'Username'})) password1 = forms.CharField(widget =forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password1'})) password2 = forms.CharField(widget =forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password2'})) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('first_name','last_name','email') user.html {% for i in detailsuser %} <h1> yourname: i.email </h1> {% endfor %} <h1>Your last name:</h1> <h1>Your nickname:</h1> models.py class detailsuser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
Errno 5 Input/output error when closing console
I have a video converter which is converting audio and video files. Everything works but if I close my terminal from my server the audio file convert doesnt work anymore. I use PyTube for converting and moviepy for converting the mp4 from pytube into mp3. (I think the problem has something to do with moviepy bc. before I didnt have it.) This is my code for converting audio: if format == "3": yt = YouTube(videolink) downloads = MEDIA_ROOT + "/videos/" ys = yt.streams.filter(file_extension='mp4').first().download(downloads) base, ext = os.path.splitext(ys) basename = os.path.basename(base + uuid + '.mp3') videoclip = VideoFileClip(ys) audioclip = videoclip.audio audioclip.write_audiofile(base + uuid + ".mp3") audioclip.close() videoclip.close() maybe something with the os code is wrong. But I cant figure out why it works if I leave the console open. Im thankful for every help I get. -
REST Django - How to Modify a Serialized File Before it is Put Into Model
I am hoping that I can find a way to resize an uploaded image file before it is put into the database. I am new to Django with REST, so I am not sure how this would be done. It seems that whatever is serialized is just kind of automatically railroaded right into the model. Which I suppose is the point (it's certainly an easy thing to setup). To clarify, I already have a function tested and working that resizes the image for me. That can be modified as needed and is no problem for me. The issue really is about sort of "intercepting" the image, making my changes, and then putting it into the model. Could someone help me out with some ideas of tactics to get that done? Thanks. The Model: class Media(models.Model): objects = None username = models.ForeignKey(User, to_field='username', related_name="Upload_username", on_delete=models.DO_NOTHING) date = models.DateTimeField(auto_now_add=True) media = models.FileField(upload_to='albumMedia', null=True) file_type = models.CharField(max_length=12) MEDIA_TYPES = ( ('I', "Image"), ('V', "Video") ) media_type = models.CharField(max_length=1, choices=MEDIA_TYPES, default='I') user_access = models.CharField(max_length=1, choices=ACCESSIBILITY, default='P') class Meta: verbose_name = "MediaManager" The View with post method: class MediaView(APIView): queryset = Media.objects.all() parser_classes = (MultiPartParser, FormParser) permission_classes = [permissions.IsAuthenticated, ] serializer_class = MediaSerializer def post(self, … -
how to add new option for select tag in select2 - remote data
I've implemented an application, in one the forms there are alot of data in its drop down field, it takes some time to load that page, so i want to load it in ajax call, but the calling back data not creating new option tag and append to select tag, here is what i tried i tried all of these codes but non of them worked ! $(document).ready(function () { $('#guestinfo').select2({ ajax: { url: '{% url "booking:return_ajax_guests" %}', dataType: 'json', processResults: function (data) { console.log(data.length) if(data.length > 0){ for(i=0;i <= data.length;i++){ //var options = data[i].full_name //console.log(options) //$('#guestinfo').append("<option value='"+options+"'>"+options+"</option>") //$('#guestinfo').trigger('change'); //var opts = new Option("option text", "value"); //$(o).html("option text"); //$("#guestinfo").append(o); $('#guestinfo').append($('<option>', { value: options, text : options })); } } //return { // results: $.map(data, function (item) { // $('#guestinfo').append("<option value='"+item.full_name+"' selected>"+item.full_name+"</option>") // $('#guestinfo').trigger('change'); // return {full_name: item.full_name, city: item.city__name}; // }) //console.log(results) //}; } }, minimumInputLength: 0 }); }) <div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "full names" %}</label> <select name="guestinfo" id="guestinfo" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white"> <option value="------">---------</option> </select> </div> select2 version : 2.0.7 and here is my server side code (django) @login_required def return_ajax_guests(request): if request.is_ajax(): term … -
CSRF verification failed: is token not persisting between GET and POST? Django
I checked a lot of the older CSRF questions, but they seem to be from 5+ years ago and a lot of the solutions aren't applicable due to now being handled with render() or other built-in methods. So, here's my question: I'm rendering a form template from a class-based view. It loads fine when I hit the initial GET request, but when I try to submit, it throws a 403: CSRF verification failed error. I'm not sure why this is happening - I feel like I'm doing everything right. Could it have something to do with saved cookies that override the CSRF token getting changed every time render is called? Here's my code: class Intake(View): form_class = IntakeFormSimple template_name = "intake.html" def get(self, req: HttpRequest): form = self.form_class(None) return render(req, self.template_name, {"form": form}) def post(self, req: HttpRequest): form = self.form_class(req.POST) if form.is_valid(): return HttpResponse("submitted form!") return render(req, self.template_name, {"form": form}) and the form template (boilerplate removed for clarity): <body> <section class="section"> <div class="container"> <form action="" method="post" novalidate> {% csrf_token %} {{ form.non_field_errors }} {% for field in form %} <div class="field"> <label class="label" for="{{field.id_for_label}}" >{{field.label}}</label > <div class="control">{{field}}</div> {% if field.help_text %} <p class="help">{{field.help_text}}</p> {% endif %} <ul class="errorlist"> {% … -
Why we write this, form = StudentForm(request.POST) in django?
This is my views function, def studentcreate(request): reg = StudentForm() string = "Give Information" if request.method == "POST": reg = StudentForm(request.POST) string = "Not Currect Information" if reg.is_valid(): reg.save() return render('http://localhost:8000/accounts/login/') context = { 'form':reg, 'string': string, } return render(request, 'student.html', context) Here first we store form in reg variable then also we write reg = StudentForm(request.POST) why? acutally why we write this? -
AWS elastic beanstalk Linux 2 with Django application failed to deploy
I am in this strange situation where I could not deploy the same code base to elastic beanstalk Linux 2 server after first time. The first deployment(after intentionally crashed server or new environment) works with no error but if I deploy the same code base again, It would fail at python manage.py migrate command in my .config file. I tried to put all my eb container commands in .config into .platform/hooks as .sh scripts, the deployment works, but I would get 502 Bad Gateway error and unable to see my site. Any insight? -
Read a uploaded excel file that have equations and images in cells django and store it in db
Read a uploaded excel file that have equations and images in cells using django and store it in db -
Getting Module not found error on terminal
I am building a react-django app for which I have created a css folder to add external css to my components and a image folder which has all the images which are required in the components but when I run the app I get this error on my terminal which shows module not found: ERROR in ./src/components/HomePage.js 5:0-39 Module not found: Error: Can't resolve './images/insta.png' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components' resolve './images/insta.png' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components' using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components) Field 'browser' doesn't contain a valid alias configuration using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components/images/insta.png) no extension Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png doesn't exist .js Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.js doesn't exist .json Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.json doesn't exist .wasm Field 'browser' doesn't contain a valid alias configuration C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png.wasm doesn't exist as directory C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\images\insta.png doesn't exist @ ./src/components/App.js 3:0-34 10:90-98 @ ./src/index.js 1:0-35 ERROR in ./src/components/css/Homepage.css (./node_modules/css-loader/dist/cjs.js!./src/components/css/Homepage.css) 5:36-149 Module not found: Error: Can't resolve '"C:UsersKuldeep PÞsktopRAMANGymWebsite☼rontendsrc♀omponentspublicSergi2.jpeg"' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\css' resolve '"C:UsersKuldeep PÞsktopRAMANGymWebsite☼rontendsrc♀omponentspublicSergi2.jpeg"' in 'C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\src\components\css' Parsed request is a module using description file: C:\Users\Kuldeep P\Desktop\RAMAN\GymWebsite\frontend\package.json (relative path: ./src/components/css) using description … -
Attempted relative import beyond top-level package in django
Trying to build a Django app with a signup app within the main app itself I receive this error message: from ..signup import views as signup_views ValueError: attempted relative import beyond top-level package This is the structure of my app ---PeerProgrammingPlatform ------peerprogrammingplat --------->peerprogrammingplat --------->signup This is my views (in signup): from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup(request): if request.method == 'POST': form = UserCreationForm() if form.is_valid(): form.save() username = form.cleaned.data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup/register.html', {'form':form}) my urls.py (peerprogrammingplat): from django.contrib import admin from django.urls import path from ..signup import views as signup_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', signup_views.register, name="register"), ] -
React app won't connect to django-rest database
I'm to update the frontend of this site https://github.com/ildebr/store-repository it has a react frontend and a django backend, auth is made with django-rest-framework. Originally the database was using PostrgreSql but due to some trouble with my pc I changed it to sqlite. When I try to register I'm unable to do it, I get error 200. I don't know what could be causing trouble cause it should not be having trouble functioining. When trying to register I get Internal server error: /auth/users I already have cors implemented and set like: CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] -
Expected Indented Block with DJANGO Rest framework
I have just started with django and I am getting the error on line 1 in models.py, I have not created a virtual environment and I have created app called wallet. from django.db import models # Create your models here. class Wallet(models.Model): raddress = models.CharField(max_length=100, blank=False) //Expected Indented Block here Error balance = models.TextField(max_length=50) sent = models.TextField(max_length=50) received = models.TextField(max_length=50) def __str__(self): self.raddress self.balance self.sent self.received Also when I put my app in name in the installed apps under settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', /// 'wallets', I am trying to put it here ] It gives me an error saying ModuleNotFoundError: No module named 'rest_frameworkwallet' It just concatinates the two? -
<django.db.models.query_utils.DeferredAttribute object at 0x0000021299297100> SHOWING INSIDE INPUT FIELDS for updating an Todo task
Hy, I am trying to solve an issue, I am new to Django and while doing a project I am getting <django.db.models.query_utils.DeferredAttribute object at 0x0000021299297100> inside the input fields. The function is for updating existing data and inside that its shows models. query instead of the actual values. HTML input fields HTML CODE THIS IS MY views: Views.py THIS IS MY forms.py forms.py THIS IS MY models.py models.py Please let me know where is the issue coming from. Thanks. -
How to fix url 404 issue in Django? Help needed
I hope anyone can help me with this. I am trying to build an Ecommerce website for myself. I used this [tutorial] and followed all it's steps. The issue is that in browser whenever I don't add '/' after the admin in 'http://127.0.0.1:8000/admin' it give's me this error: 404 Error Image Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URl = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') urls.py: (project urls) from xml.dom.minidom import Document from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py: (app urls) from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('store/', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('update_item/', views.updateItem, name="update_item"), path('process_order/', views.processOrder, name="process_order"), ] This is same for all of the urls defined in the apps urls.py. If I put manually '/' it works just fine. I will be thankful for guidance and help. I have tried searching, reading docs and just figuring out just nothing has came up. Hope anyone here will shed some knowledge on it. And Yes! … -
IntegrityError at /merchant_create
UNIQUE constraint failed: f_shop_customuser.username Request Method: POST Request URL: http://127.0.0.1:8000/merchant_create Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: f_shop_customuser.username Exception Location: C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe Python Version: 3.9.10 Python Path: ['F:\Git\Client Git\f_worldSHop', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\win32', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\win32\lib', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\Pythonwin', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\site-packages'] Server time: Fri, 18 Feb 2022 17:29:24 +0000 -
Django Form - Override standard validation message from within custom validator function
In my forms.py file, I have a custom validation function that I pass to the EmailField's validators attribute. However, when I test this in browser, I get BOTH the standard error message AND my custom message. How do I hide the standard message and just display my custom message? browser form behavior: Email: bademail123 # Enter a valid email address. <-- default validation error # Email does not match expected format: example@email.com <-- my custom validation error msg forms.py # VALIDATORS FOR FORM FIELDS def clean_email(email): if not re.match("\S+@\S+\.\S+", email): raise forms.ValidationError( "Email does not match expected format: example@email.com" ) class IntakeFormSimple(Form): email = forms.EmailField( label="Email", widget=forms.TextInput(attrs={"placeholder": "example@email.com"}), validators=[clean_email], ) -
DRF APIClient Delete data arrives in request.data, not request.query_params
I use DRF's APIClient to write automated tests. And while is was writing the first delete test, I found it very strange that the data passed through arrived in request.data, while if I use Axios or Postman, it always arrives in request.query_params. Any explanation as to why this is, and preferably a method to use APIClient.Delete while the data arrives in query_params would be great! My test: import pytest from rest_framework.test import APIClient @pytest.fixture() def client(): client = APIClient() client.force_authenticate() yield client class TestDelete: def test_delete(client): response = client.delete('/comment', data={'team': 0, 'id': 54}) And my views from rest_framework.views import APIView class Comments(APIView): def delete(self, request): print(request.query_params, request.data) >>> <QueryDict: {}> <QueryDict: {'team': ['0'], 'id': ['54']}> Looked into DRF's APIClient. Feeding towards params doesn't seem to help. The delete method doesn't seem to have direct arguments that could help as well. So I'm a bit stuck. -
I am not getting expected result when I am multiplying price with quantity
I am working on a billing application. When I need to generate a bill, I open the CREATE form and I enter the quantity and price of two items. The quantity, price and total of both the items are stored in the django. suppose i want to change the quantity in Bill then i have made a similar form i call edit form. So when I edit the quantity and price of both the items in the edit form, then the first item's multiplication is getting correct but the second item's multiplication is getting wrong. You can see the problem in the rectangular box error Image <script> var item = {{itemid}}; var itemname = "{{itemname|escapejs}}"; services = itemname.replaceAll("'",'"') a =JSON.parse(services) itemid_list = '<option value="">Select Item</option>'; console.log((a)) console.log((a.length)) for(var x=0; x<item.length; x++){ itemid_list = itemid_list+ "<option value='"+item[x]+"'>"+a[x]+"</option>" } console.log(itemid_list) const maxPoints = 5; let count = 1; // Adds new point const deleteThisPoint = (target) => { target.parentNode.remove(); var sum = 0; $('input.extended_total').each(function() { var num = parseInt(this.value, 10); if (!isNaN(num)) { sum += num; } }); $("#totalcount").text(String(sum)); }; const addNewPoint = (target) => { const parentContainer = target.parentNode.parentNode; const addIn = parentContainer.querySelector('.multiple-points'); const childCounts = addIn.childElementCount; if(childCounts > maxPoints - … -
How to update post in Django with out using Django forms
I want to update a post in Django, but I don't want to use Django forms for this is there any way to do that. -
Python -Django - send rest request get http client get error - TypeError: expected string or bytes-like object
I create a Django App and send rest http request to Plaid. if I start up django alone(python manage.py run server), it works fine. But if I use Nginx + Gunicorn + Django, I will get error. The error message is: File "/var/www/sp_plaid/api/views.py", line 91, in create_link_token response = client.link_token_create(p_request) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 769, in __call__ return self.callable(self, *args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api/plaid_api.py", line 6863, in __link_token_create return self.call_with_http_info(**kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 831, in call_with_http_info return self.api_client.call_api( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 406, in call_api return self.__call_api(resource_path, method, File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 193, in __call_api response_data = self.request( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 452, in request return self.rest_client.POST(url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 264, in POST return self.request("POST", url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 150, in request r = self.pool_manager.request( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 78, in request return self.request_encode_body( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File "/usr/lib/python3/dist-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.9/http/client.py", line 1279, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1320, in _send_request self.putheader(hdr, value) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line … -
IntegrityError FOREIGN KEY constraint failed - Django custom user model
I am new to creating custom user models in Django, so bear with me. My problem is that I get a IntegrityError at /admin/accounts/customuser/add/ FOREIGN KEY constraint failed when I delete a user in Django admin. This also happens when I try to add a user in Django admin. Code models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, null=True, blank=True) verification_code_time = models.IntegerField(_('time left for session id'), null=True, blank=True) … -
Group name not taking spaces django-channels
I am working on a chat app with django channels, everthing is working but messages don't get send when room name has spaces or other special carachter, ideally I'd like to be possible to the user to have spaces in their room name. /* consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from web socket async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'timestamp': timezone.now().isoformat() })) @sync_to_async def save_message(self, username, room, message): if len(message) > 0: Message.objects.create(username=username, room=room, content=message) routing.py: websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] urls.py: urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] index.html: <script> document.querySelector('#room-name-input').focus(); document.querySelector("#room-name-input, #username-input").onkeyup = function(e) { if (e.keyCode === 13) { document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var … -
AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint'
Sys: Windows 11 Prof; Python v3.9.7 I've tried to install Wagtail Colour Picker but I got this error message back. Do I need to install or remove something? Please Help ! models.UniqueConstraint(fields=['page'], condition=Q(status__in=('in_progress', 'needs_changes')), name='unique_in_progress_workflow') AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' -
Is there a method to create a Django token for user objects with no last_login timestamp?
I have a Django app that contains advertisement recipients with no login timestamps (since they do not need to have an account anyways), is there a method to customize the Django default token generator to exclude the timestamp requirement? -
Strange behaviour when rendering X-Axis ticks
I'm rendering a chart with matplotlib through panda's df.plot() method, but somehow the tick labels on the X-Axis seem to be messed up. There seems to be a layer of numeric text above my "real" tick labels. I have no idea where this comes from. Strangely enough, this only happens in our production and staging environment, not in dev. Maybe it also has to do with gunicorn or django's dev server. Has somebody made this experience before? Here's the plot result: and this is the output when I clear the ticks with .set_xticks([], []): Here's a portion of my code, there's some abstraction but I think it should be understandable. self.data is a pandas dataframe. It outputs base64-encoded png data: class Line(ChartElement): def draw(self): self._plot = self.data.plot(kind='line', color=self.colors) self._rotation = 'vertical' self._horizontalalignment='center' # self._plot.set_xticks([], []) # ... class ChartElement(): # ... def base64(self): self.draw() figfile = BytesIO() if not self._plot: raise ValueError("Plot not generated.") if self._legend: self._plot.legend(self._legend, **self._legend_args) #plt.legend(self._legend, loc='upper center', bbox_to_anchor=(0.4, .05), ncol=5, fancybox=False, prop={'size': 6}) plt.setp(self._plot.get_xticklabels(), rotation=self._rotation, horizontalalignment=self._horizontalalignment, fontsize=8) self._plot.set_ylabel(self.y_title) self._plot.set_xlabel(self.x_title) #plt.figure() fig = self._plot.get_figure() fig.autofmt_xdate() if self.size and isinstance(self.size, list): fig.set_size_inches(inch(self.size[0]), inch(self.size[1])) fig.savefig(figfile, format='png', bbox_inches='tight') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) plt.clf() plt.cla() plt.close('all') plt.close() return figdata_png.decode('utf8')