Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing values from the forms from one view (one url) to another view (second url) in Django
So I have two forms, and a view which enables users to fill them: def input_view(request): if request.method =="POST": simulation_form = SimulationSettings(request.POST) strategy_form = StrategySettings(request.POST) if simulation_form.is_valid() and strategy_form.is_valid(): simulation_settings = simulation_form.cleaned_data strategy_settings = strategy_form.cleaned_data return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) else: simulation_form = SimulationSettings() strategy_form = StrategySettings() return render( request, "strategy_simulator/input_view.html", {"simulation_form": simulation_form, "strategy_form": strategy_form}, ) With this code, it works and after submitting the forms results_view.html template is displayed properly, but the url does not change and I want results to be under different url. So I've created second view and url to it, but I do not know how to pass forms values from one view to another and then redirect to the url connected to the specific view (results_view in this case). Here is the view: def results_view(request): simulation_settings = request.POST.get('simulation_settings') strategy_settings = request.POST.get('strategy_settings') return render( request, "strategy_simulator/results_view.html", {"simulation_settings": simulation_settings, "strategy_settings": strategy_settings}, ) And here are urls: from . import views from django.urls import path app_name = "strategy_simulator" urlpatterns = [path("results/", views.results_view, name="results_view"),path("", views.input_view, name="input_view"), ] Thanks for help in advance. -
Affiliate marketing in django model
I have a django travel blog, now im looking to find a way to integrate extern city widgets and scripts from my associates inside my articles, what is the best option to do so? I tried in Django CkEditor from Richtextfield(model) in django admin inside scripts to insert the code provided from associated but it's not working at all. -
No module found [my_app] with Apache and mod_wsgi
This is my directory structure, in /var/www: team_django --team_db ---- __init__.py -----settings.py -----wsgi.py My wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'team_db.settings') application = get_wsgi_application() My /etc/apache2/mods-available/wsgi.load: LoadModule wsgi_module "/usr/local/py_ptracker/lib/python3.11/site-packages/mod_wsgi/server/mod_wsgi-py311.cpython-311-x86_64-linux-gnu.so" WSGIPythonHome "/usr/local/py_ptracker" My /etc/apache2/sites-available/vhost.conf: WSGIScriptAlias / /var/www/team_django/team_db/wsgi.py <Directory /var/www/team_django/team_db> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The mod_wsgi is enabled, as the vhost configuration, and everything gets loaded fine. I get this in the error.log though: ModuleNotFoundError: No module named 'team_db' [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Failed to exec Python script file '/var/www/team_django/team_db/wsgi.py'., referer: ... [wsgi:error] [pid 225277] mod_wsgi (pid=225277): Exception occurred processing WSGI script '/var/www/team_django/team_db/wsgi.py'., referer: .... Why isn't the os.environ.setdefault not finding team_db? I've checked all permisions and I also set everything to 777, changing owners and group to www-data or root and all that; to no avail. I can't understand why it's not finding the team_db. Te server runs correctly with Django's runserver and also with the mod_wsgi-express runserver. The mod_wsgi has been built with the same version of Python, within the virtual environment. -
Any Microsoft Dataverse database backend for Django?
I'd like to write a frontend for my Microsoft Dataverse database backend so as to manage Dataverse data easily. Django comes with an easy-to-configure admin which suits my needs fine. I would like to know if there has been any third-party backends for Dataverse already, or I just need to implement the backend by myself because few people care about using Dataverse as the backend for their Django Applications. Craving for your insights! -
how to post an image from react native to django
I'ive been trying to post an image file from react-native but i can't seem to get it right this is the code I tried: const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); if (!result.canceled){ delete result.cancelled; setImage(result.assets[0].uri) } }; and this is the fetch request: const handleSubmit = (name, description, image, email, phone) => { let uri = image.replace("///", "//") var myHeaders = new Headers(); myHeaders.append("Authorization", `Bearer ${userInfo.access_token}`); myHeaders.append("Content-Type", "multipart/form-data"); var formdata = new FormData(); formdata.append("name", name); formdata.append("description", description); formdata.append("photo", uri, uri.split("/").pop()); formdata.append("phone", phone); formdata.append("email", email); var requestOptions = { method: 'POST', headers: myHeaders, body: formdata, redirect: 'follow' }; fetch(`${Url.base}/api/realtor/create-profile`, requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); } this is the error i keep getting: {"photo":["The submitted data was not a file. Check the encoding type on the form."]} -
I'm trying to create multiple user in Django using flags and a custom user model but keep getting something went wrong error
I have created my custom user model with the following code. class UserManager(BaseUserManager): def create_user(self, email, name, phone, password=None): if not email: raise ValueError("Users must have an email address") email = self.normalize_email(email) email = email.lower() user = self.model(email=email, name=name, phone=phone) user.set_password(password) user.save(using=self._db) return user def create_vendor(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_vendor = True user.save(using=self._db) return user def create_superuser(self, email, name, phone, password=None): user = self.create_user(email, name, phone, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=15, unique=True) otp = models.CharField( max_length=6, ) is_vendor = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name", "phone"] objects = UserManager() def __str__(self): return self.email I have also created my view and i don't know where the issue is in the following code also: class RegisterAPIView(views.APIView): permission_classes = (permissions.AllowAny,) def post(self, request): try: data = request.data print(data) email = data["email"].lower() name = data["email"] phone = data["phone"] password = data["password"] re_password = data["re_password"] is_vendor = data["vendor"] if is_vendor == "True": is_vendor = True else: is_vendor = False if … -
django admin autocomplete filter without foreign key
I have this model: class Person(models.Model): first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) gender = models.CharField(choices=Gender.choices, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) I need autocomplete filter for "city" field https://github.com/farhan0581/django-admin-autocomplete-filter didnt do the job -
Django-React integration Django port does not actualize
I made changes to the src/app.js when I use npm start inside the react_app, in port 3000 changes and gets rendered but when I do that using python manage.py runserver I only see the default react-app welcome how can I fix that? views from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index') ] Heres is my react_app inside my django project here is the app.js import "./App.css"; function App() { return ( <div className="App"> <p>Calendar App</p> </div> ); } export default App; using python manage.py runserver: enter image description here using npm run inside react app: enter image description here -
Set initial data in Django Form forms.Select()
I want to set initial value for my staus field that is forms.Select() widget in django ModelForm but it does not work. I cant debug my code. My model form class is: class CRMFollowUpStatusLogForm(ModelForm): class Meta: model = CRMFollowUpStatusLog fields = ['status'] widgets = { "status": forms.Select() } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) status_id = kwargs["data"]["followup"].current_status.id # status_id is correctly passed here self.fields['status'].initial = status_id status_id is correctly passed to init method. but self.fields['status'].initial = status_id does not work correctly. CRMFollowUpStatusLog is: class CRMFollowUpStatusLog(models.Model): status = models.ForeignKey( "CRMFollowUpStatus", related_name="follow_up_logs", on_delete=models.CASCADE ) follow_up = models.ForeignKey( "CRMFollowUp", related_name="status_logs", on_delete=models.CASCADE ) and CRMFollowUpStatus is: class CRMFollowUpStatus(models.Model): name = models.CharField(max_length=256, unique=True) status_id in init method of CRMFollowUpStatusLogForm is pk of CRMFollowUpStatus. -
Django is not accepting my nested for loop with double zip
In views.py I have: mylist1 = ["peru", "germany", "japan"] mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]] mylist3 = [[1,2], [3,4], [5]] mylist = zip(mylist1, zip(mylist2, mylist3)) In templates for country, info in mylist: {{country}} for city, number in info: {{city}} {{number}} error: Need 2 values to unpack in for loop; got 1. I feel my double zip definition is not being accepted or properly read. any ideas on how to fix this: -
Flask AppBuilder add_registration function is not redirecting to activation page
I am using Flask AppBuilder to build a web application. I am having trouble with the add_registration() function. The function is sending the registration email successfully, but it is not redirecting to the activation page. Instead, it is redirecting to the index page. def add_registration(self, username, first_name, last_name, email, password=""): """ Add a registration request for the user. :rtype : RegisterUser """ print("first passed") register_user = self.appbuilder.sm.add_register_user( username, first_name, last_name, email, password ) print("second passed") if register_user: print("third passed") verification_code = self.send_email(register_user) if verification_code: print("fourth passed") flash(as_unicode(self.message), "info") verfication_info = ( f"{verification_code}/{username}/{first_name}/{last_name}/{email}/{password}" ) print("fifth passed ") # Redirect to activation page only if email was sent successfully. return redirect( url_for(".activation", _external=True, activation_hash=register_user.registration_hash) ) else: print("fith faild") flash(as_unicode(self.error_message), "danger") self.appbuilder.sm.del_register_user(register_user) # Redirect to index page if email failed to send. return redirect(self.appbuilder.get_url_for_index) even it is printing "fifth passed" to ensure if the email is sent -
What is wrong with this django view?
in this django view I'm trying to do the following: Check if there is a "chartentry" with today's date In that case, do not substitute the description with the new value, but just append it to the old value I can't for the life of me figure out why it is always repeating twice the new value (e.g. the description ends up as "newvalue;newvalue" instead of "oldvalue;newvalue" Help appreciated @login_required def chartentry_create(request, chart_id): obj = get_object_or_404(Chart, id=chart_id) todaysentry = obj.chartentries.filter( created_at__gte=timezone.now().replace(hour=0, minute=0, second=0), created_at__lte=timezone.now().replace(hour=23, minute=59, second=59), ).first() # if it's today's entry, append data to it instead of creating a new one if todaysentry: form = ChartEntryForm(request.POST, instance=todaysentry) else: form = ChartEntryForm(request.POST or None) if form.is_valid(): # if it's today's entry, append description if todaysentry: form.instance.description = ( todaysentry.description + ";" + request.POST["description"] ) form.instance.chart = obj form.save() messages.success(request, "Entry updated successfully") else: for error in form.errors: messages.error(request, form.errors[error]) if is_ajax(request): context = {"chart": obj} return render(request, "chart_entries_by_patient_partial.html", context) else: return redirect("chart-detail", patient_id=obj.patient.id) -
Could not find 'price' in DJ4E assignment
I've got a problem with DJ4E course by dr.Chuck. On Building Classified Ad Site #2 assignment my site can't pass a validation and checking form keeps throwing an error "Could not find 'price' The price field is missing on the create form - check the field_list in views.py" for URL http://meredan.pythonanywhere.com/ads/ad/create I have re-checked multiple times and can't find why this is raised, because price field is available in the UI and also present when I checked manually in a shell. I am not very experienced with Django, maybe I'm missing something, would appreciate any help. creation class in views.py class AdCreateView(LoginRequiredMixin, View): template_name = 'ads/ad_form.html' success_url = reverse_lazy('ads:all') def get(self, request, pk=None) : form = CreateForm() ctx = { 'form': form } return render(request, self.template_name, ctx) def post(self, request, pk=None) : form = CreateForm(request.POST, request.FILES or None) if not form.is_valid() : ctx = {'form' : form} return render(request, self.template_name, ctx) # Add owner to the model before saving ad = form.save(commit=False) ad.owner = self.request.user ad.save() return redirect(self.success_url) forms.py class CreateForm(forms.ModelForm): max_upload_limit = 2 * 1024 * 1024 max_upload_limit_text = naturalsize(max_upload_limit) picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text) upload_field_name = 'picture' class Meta: model = Ad fields = ['title', … -
how to connect mysql and django in vscode virtual environment
If l try to run pip install mysqlclient in virtual environment l get this pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [41 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\lib\mariadb', 'C:/mariadb-connector\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\include\mariadb', 'C:/mariadb-connector\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\FLAG.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants running egg_info writing src\mysqlclient.egg-info\PKG-INFO writing dependency_links to src\mysqlclient.egg-info\dependency_links.txt writing top-level names to src\mysqlclient.egg-info\top_level.txt reading manifest file 'src\mysqlclient.egg-info\SOURCES.txt' reading manifest … -
Please how I do fix [ModuleNotFoundError: No module named 'config.settings']?
I have already installed pip requests, installed config file but it keeps showing the same thing.I even created a new virtual world and a new project but anytime I run "python manage.py runserver" or "python manage.py migrate" it keeps tell me (ModuleNotFoundError: No module named 'config.settings'). pip install requests -
foreign key daterange filtering in django admin
for a hotel booking system using django admin, I'd like to filter the rooms available for a given date range, models are as follow class Room(models.Model): id = models.AutoField(primary_key=True) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) class Booking(models.Model): id = models.AutoField(primary_key=True) start_date = models.DateField(verbose_name=_("Start date")) end_date = models.DateField(verbose_name=_("End date")) room = models.ForeignKey(Room, on_delete=models.CASCADE) how can I filter the rooms in the admin so I can pick a date range and return only the rooms that have no bookings on the select range? thanks a lot -
Set Boolean value in hidden input
I have a form that lets users send new product to database, But I want to be able to review them before sending them, So I want to set a Boolean input the the form so when User sends new product they wait in admin panel for review and after reviewing them admin can change the Boolean field and the product is published. I made a hidden field in form and I want to give it the default value. now no matter what I did, I cannot make the form to submit with the hidden boolean field value forms.py : class AccountProductForm(ModelForm): class Meta: model = AccountProduct fields = ('name','price','description','image','is_agahi') labels = { 'name': '', 'price': '', 'description': '', 'image': '', } widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'price' : forms.NumberInput(attrs={'class': 'form-control'}), 'description' : forms.Textarea(attrs={'class': 'form-control'}), 'image' : forms.FileInput(attrs={'class': 'form-control'}), 'is_agahi' : forms.HiddenInput(), def __init__(self, *args, **kwargs): self._user = kwargs.pop('account_owner') super(AccountProductForm, self).__init__(*args, **kwargs) def save(self, commit=True): inst = super(AccountProductForm, self).save(commit=False) inst.account_owner = self._user if commit: inst.save() self.save_m2m() return inst views.py def sell_account(request): submitted = False if request.method == 'POST': form = AccountProductForm(request.POST, request.FILES, account_owner=request.user) if form.is_valid(): form.save() messages.success(request, 'Product Sent') else: form = AccountProductForm(account_owner=request.user) if 'submitted' in request.GET: submitted … -
TypeError: DatabaseWrapper.display_name() takes 0 positional arguments but 1 was given
I am getting the following error when running "python manage.py migrate" in cpanel terminal. I am using mysql for database. The library that I am using is mysql-connector-python. TypeError: DatabaseWrapper.display_name() takes 0 positional arguments but 1 was given The following are the settings of my settings file: DATABASES = { "default": { "ENGINE": "mysql.connector.django", "NAME": "my-database-name", "HOST": "localhost", "PORT": "3306", "USER": "my-database-username", "PASSWORD": "my-password", } } -
Django for loop with parentheses for zip command
In Python this code works mylist1 = ["peru", "germany", "japan"] mylist2 = [["lima","cusco"], ["berlin","munich"], ["tokyo"]] mylist3 = [[1,2], [3,4], [5]] for country, (cities, numbers) in zip(mylist1, zip(mylist2, mylist3)): print(country) for city, number in zip(cities, numbers): print(city) print(number) I'm able to print what I want: peru lima 1 cusco 2 germany berlin 3 munich 4 japan tokyo 5 However in Django I have an issue with the parenthesis. In views.py I can set mylist=zip(mylist1, zip(mylist2, mylist3)), so I will have {% for country, (cities, numbers) in mylist %}: print(country) {% for city, number in zip(cities, numbers) %}: print(city) print(number) The first for loop is where I'm stuck. what should I do to use (cities,numbers). I think parenthesis is not accepted. python approach doesn't work -
Offcanvas dismiss button does not work when instance initialised via Javascript
I have offcanvas as part of the page layout. It does not show by default, but I want it to always show on large screens. On small screens it should have a button to dismiss it. Another button to show the offcanvas is placed on the menu panel underneath it. I'm using JavaScript on page load and on page resize to show the offcanvas when if screen is large. If the user then scales the screen down, the offcanvas should remain visible until dismissed. The issue is that the dismiss button works on the offcanvas only if it has not been initialised via JS. I.e. if opened on a small screen, the offcanvas is not visible and the two bottons can be used to toggle back and forth. But once the offcanvas has been triggerd via JS on a large screen, the dismiss button no longer works when the screen is downsized. I'm struggling to figure out if it has lost an EventListener and how to add it back, if so. Layout: <!-- Button to show offcanvas (positioned underneath it) --> <div> <button class="btn" type="button" id="off-canvas-body-toggle" data-bs-toggle="offcanvas" data-bs-target="#floating-menu"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#422543" class="bi bi-arrow-bar-right" viewBox="0 0 16 16"><path fill-rule="evenodd" … -
Why is this react-django app not rendering anything
my App.js is in appname/src/components : import React, { Component } from "react"; import { render } from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <h1>This is the App.js</h1> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); My index.js in appname/src: import { App } from "./components/App"; why is the server not rendering anything? see my templates app name index.html in appname/templates/appname seems to be doing just fine: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Testing DJREACT with Yarn</title> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div id="main"> <div id="app"></div> </div> <script src="{% static 'frontend/main.js' %}"></script> </body> </html> I think I did the installation correctly. The title of the web is indeed getting rendered but the body is not ???????????????????????? -
Cannot visualize ImageField in Django Rest Framework
I have a model with an ImageField: image_url = models.ImageField(upload_to=upload_to, blank=True, null=True) I did include it in my serializer in this way: image_url = serializers.ImageField(required=False, use_url=True) This is my viewset: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.order_by('-id') serializer_class = ProductSerializer parser_classes = (MultiPartParser, FormParser) permission_classes = [ permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save() The media root and url: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py: urlpatterns = [ path("users/", include("user.urls")), path("products/", include("products.urls")), path("utils/", include("utils.urls")), path("auth/", include("djoser.urls")), path("auth/", include("djoser.urls.jwt")), path("graphql/", csrf_exempt(GraphQLView.as_view(schema=schema, graphiql=True))), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It get listed properly: But the problem is that once I click on the url of the image (that is inside the media folder), it shows me a 404 error in this url: http://127.0.0.1:8000/media/images/base_bWxtftQ.png. But the image is in that folder. -
Creating A Responsive / Dynamic Form for Business Users, Efficiently
I am a data engineer and I've found myself in a position of needing to develop advanced frontend forms for nontechnical business users. These business users do not want or need to understand complexities of data modeling, and this is my strategy to try and remove the manner by which the complexities of data modeling impact the data entry process. As I said though, I am a data engineer- not a web developer. Before I reinvent the wheel here, what would be some feedback for this approach? Form Components and Their Expected Behaviors: Selection Fields: Behavior: Prepopulated with unique values from a column, allowing users to select or search for an option. Initialization: Start as empty fields. Input Fields: Behavior: Accept raw input from the user. Update Fields: Behavior: Corresponds to a table column that should receive updates. Also listens to a single Invisible Field for state changes. Visibility: Not editable until their corresponding Invisible Field is populated with a row-id value. Edit State: Require a double-click to enter an editable state. Value Update: Leaving the editable state with a changed value results in an UPDATE to the database record matching the ID value in the corresponding invisible field. Invisible … -
UserAccountManager superuser not loggin in
I am trying to add to my UserAccountManager, a way of creating a superuser so that I can easily manage my database, my problem is that when I create the super user from the terminal, everything seems ok, I don't get errors, but when I try to log in the default django admin page, it says that no staff account with those credentials is found. I have tried deleting my database, removing and redoing migrations. This is my models.py class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('User must have an email') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, first_name, last_name, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, first_name, last_name, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=128) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] -
Daphne refuses to connect websocket requests
I have a developed a complex Django server consisting of several applications, making use of channels in combination with the Daphne server an reverse proxy uplink from Nginx. This is the site configuration from /etc/nginx/sites-available: server { listen 80; server_name django.mydomain.eu; return 301 https://$server_name$request_uri; } server { client_max_body_size 100M; listen 443 ssl; server_name django.mydomain.eu; ssl_certificate /etc/letsencrypt/live/django.mydomain.eu/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/django.mydomain.eu/privkey.pem; access_log /var/log/nginx/django.mydomain.eu.access.log combined; error_log /var/log/nginx/django.mydomain.eu.error.log info; location /ws/ { proxy_pass http://127.0.0.1:8000/ws/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { proxy_pass http://127.0.0.1:8000/; } } Both HTTP and Websocket requests are forwarded to Daphne on port 8000. HTTP works fine. Websocket works fine if coming from the Python client, the connections are made somewhat like this: from websocket import WebSocket while self.do_run: try: self.ws = WebSocket() self.ws.connect(self.dbline.wsserver+'ws/predictions/') break except (BrokenPipeError, TimeoutError, WebSocketBadStatusException, ConnectionRefusedError, WebSocketConnectionClosedException, WebSocketAddressException, OSError, ): self.logger.warning('BrokenPipe or Timeout while resetting ' + 'prediction websocket server') sleep(djconf.getconfigfloat('long_brake', 1.0)) Websocket does not work when coming from the JavaScript section of a Django template, where the connections are made like this: function WSAsync(url) { return new Promise((resolve, reject) => { let result = {}; result.tracker = 0; …