Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework: Unable to use custom template for login view
Gist: I'm trying to use a custom template for Django REST framework's login view by following the instructions from official documentation, but the template that I have put at <PROJECT_ROOT>/templates/rest_framework/login.html is not used to render the login page. Detail: I'm trying to properly set up Django REST framework's browsable API. In particular, after a successful login, the login view redirects to LOGIN_REDIRECT_URL, which has a default value of '/accounts/profile/' and is not what I need. I figured there are two possible solutions: to assign a value to LOGIN_REDIRECT_URL, or use a custom template for Django REST framework's login page and modify the HTML form to pass 'next': <MY_REDIRECT_URL> as the form data (I've tested this manually and it works). I decided to go with solution #2 because solution #1 is not ideal because that would be setting a global default to change behavior of one specific part of a subsystem. Solution #2 requires using a custom template for the login view, but I'm unable to get it to work by following the official instructions (link above). Things I have tried: I have tried the solutions in the following Stack Overflow questions: Django REST Browsable API Template Change django drf login … -
The view Expéditions.views.changelisteexpédition didn't return an HttpResponse object. It returned None instead
I'm new in django developpemnt , in my view i have some elif conditions that mastring some functions, in execution on the last condition i have this issue : The view Expéditions.views.changelisteexpédition didn't return an HttpResponse object. It returned None instead. def changelisteexpédition(request,id=id): if "Editer" in request.POST: ....... elif "Bloquer" in request.POST : ....... elif "Supprimer" in request.POST: ....... elif "Annuler" in request.POST: ....... elif "Débloquer" in request.POST : ....... elif "Top Départ" in request.POST : trsp = transporteur.objects.all().order_by('id') obj = get_object_or_404(Expédition,id=request.POST.get("choix")) form = TopdépartForm(request.POST) if form.is_valid(): Topdépart.objects.create( Expédition = obj, transporteur = request.POST.get("transporteur"), chauffeur = request.POST.get("chauffeur"), bl = request.POST.get("bl"), plomb = request.POST.get("plomb"), commentaire = request.POST.get("commentaire"), date = request.POST.get("date"), immatriculation = request.POST.get("immatriculation") ) obj.statut = "Expédié" obj.transporteur = request.POST.get("transporteur") obj.chauffeur = request.POST.get("chauffeur") obj.immatriculation = request.POST.get("immatriculation") obj.save() a = Commande.objects.get(numcommande=obj.numcommande) a.quantitélivrée = obj.quantitélivrée a.statut = "Expédié" a.save() j = Ligneexpédition.objects.filter(numcommande=obj.numcommande) for i in j : c = Articles.objects.get(sku=i.sku) c.stockexpedié = c.stockexpedié + i.quantitélivrée c.save() return HttpResponseRedirect("asnintransit") else : form = TopdépartForm() context = { 'form':form,`enter code here` 'obj':obj, 'trsp':trsp } return render(request,'topdépart.html',context) I need some help. Thanks. -
How to Create and Save File in Django Model
I have a view which generates a .docx file for whichever 'reference #' the user selects - I would like for the file to save to my Orders model whenever the doc is generated. models.py #model where I'd like to save the doc each time it gets generated class Orders(models.Model): reference = models.CharField(max_length=50, unique=True, error_messages={'unique':"This reference id has already been used"}) ultimate_consignee = models.ForeignKey(Customers, blank=True) ship_to = models.CharField(max_length=500, blank=True) vessel = models.CharField(max_length=100, blank=True) ... order_file = #not sure what data type to use here views.py #view generating the .docx def docjawn(request): if request.method == 'POST': reference = request.POST.get('Reference_IDs') referenceid = reference manifest = Manifests.objects.all().filter(reference__reference=referenceid) order = Orders.objects.get(reference=reference) doc = DocxTemplate("template.docx") totalCNF = 0 totalFOB = 0 for item in manifest: totalCNF += item.cases * item.CNF totalFOB += item.cases * item.FOB context = { 'ultimate_consignee' : order.ultimate_consignee, 'reference' : order.reference, 'ship_to' : order.ship_to, 'terms' : order.terms, 'date' : "12", 'ship_date' : "7/4/19", 'vessel' : order.vessel, 'POE' : order.POE, 'ETA' : order.ETA, 'booking_no' : order.booking_no, 'manifest' : manifest, 'totalCNF' : totalCNF, 'totalFOB' : totalFOB, } doc.render(context) doc_io = io.BytesIO() # create a file-like object doc.save(doc_io) # save data to file-like object doc_io.seek(0) # go to the beginning of the file-like object response … -
TypeError - string indices must be integers - Django rest framework
I'm retrieving a json response from an api, with this method: class MyView(APIView): def get(self, request): data = urlopen("https://url/api/").read() output = json.loads(data) objects = Model.objects.all() serializer = ModelSerializer(objects, many=True) for object in output: if object['id'] not in [i.id for i in objects]: Model.objects.create(id=object['id'], name=object['field1'], street=object['field2'], email=object['field3'], phone=object['field4']) return Response(serializer.data) Everytime I try to access this, it throws: Traceback (most recent call last): File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/user/.virtualenvs/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/user/django_projects/myproject/proj/app/views.py", line 37, in get if object['id'] not in [i.id for i in objects]: TypeError: string indices must be integers This is my model: from django.db import models class Model(models.Model): field1 = models.CharField(max_length=255, blank=True, null=True) field2 = models.CharField(max_length=255, blank=True, null=True) field3 = models.EmailField(max_length=254, blank=True, null=True) field4 = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return … -
Django UniqueConstraint on related model property
I have a model that looks like this, and it works ok: def BookModel(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE) bookname = models.CharField() class Meta: constraints = [ models.UniqueConstraint(fields=['user ', 'bookname'], name='StackOverflow.Question') ] Each user can only have one BookModel with a specific bookname. However, now I'd like to introduce the concept of LibraryModel class LibraryModel(TimeStampedModel): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=32) def BookModel(TimeStampedModel): library = models.ForeignKey(LibraryModel, on_delete=models.CASCADE) bookname = models.CharField() class Meta: constraints = [ models.UniqueConstraint(fields=['library_user', 'bookname'], name='StackOverflow.Question') ] Behavior should stay the same: the constraint should still be enforced based on the associated user, but the user id now lies within LibraryModel. When I run migrate, it says django.core.exceptions.FieldDoesNotExist: BookModelhas no field named 'library_user'. I've also tried fields=['library__user' and fields=['library.user', to no avail. Is this possible to do? Or should I put the user property in both models, violating some DRY principles? -
403 Forbidden error for Django app on Apache
I've followed this deploy tutorial of Django for Apache, and did everything as in there. When I try to enter the page with server's ip, I get Forbidden You don't have permission to access / on this server. Apache/2.4.29 (Ubuntu) Server at <my-ip> Port 80 Running the app with python manage.py runserver 0.0.0.0:8000 works fine and I can access the app. Via the apache2 logs I got: Current thread 0x00007fc84606fbc0 (most recent call first): [Wed Aug 14 01:11:51.141895 2019] [core:notice] [pid 31839:tid 140498145049536] AH00051: child pid 32108 exit signal Aborted (6), possible coredump in /etc/apache2 $preter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' My config file: ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ernest/[my-project-name]/static <Directory /home/ernest/[my-project-name]/static> Require all granted </Directory> Alias /media /home/ernest/[my-project-name]/datagather/uploaded_files <Directory /home/ernest/[my-project-name]/datagather/uploaded_files> Require all granted </Directory> <Directory /home/ernest/[my-project-name]/[my-project-name]/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ernest/[my-project-name]/[my-project-name]/wsgi.py WSGIDaemonProcess my_app python-path=/home/ernest/[my-project-name] python-home=/home/[my-project-name]/venv WSGIProcessGroup my_app </VirtualHost> I've done following changes to [my-project-name]/settings.py: DEBUG = False ALLOWED_HOSTS = ['[my-server-ip]', 'localhost'] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' … -
I don't know why my page isn't paginating i don't get any errors pls help :)
The page is suposed to get paginated but it doesn't i don't know what i did wrong if anyone can help me figure it out i will apreciate This is for a comment section on a site and i don't really know how to fix it i've been looking the problem up on the web with no results then came here from django.core.paginator import Paginator def Home_view(request): posts = Post.objects.order_by("-date_posted") all_experiences = Experience.objects.order_by("-id") all_educations = Education.objects.order_by("-id") all_skills = Skill.objects.all() paginator = Paginator(posts, 1) page = request.GET.get('page') post_list = paginator.get_page(page) context = { 'posts': posts, 'all_experiences': all_experiences, 'all_educations': all_educations, 'all_skills': all_skills, } return render(request, 'resume.html', context) Html Page suposed to get paginated {% if is_paginated %} <div class="pagination"> <span class="step-links"> {% if post_list.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ post_list.previous_page_number }}">previous </a> {% endif %} <span class="current"> Page{{post_list.number}}of{{post_list.paginator.num_pages}}. </span> {% if post_list.has_next %} <a href="?page={{ post_list.next_page_number }}">next</a> <a href="?page={{ post_list.paginator.num_pages }}">last&raquo; </a> {% endif %} </span> </div> {% endif %} {% else %} the page is supposed to show 5 posts at once but doesn't and doesn't throw out any errors it just doesn't work -
Sum column data model property
plz i need your help, i cant sum RESTE the return of model property , tried lot of methods but no success. have you any idea about that ? i'm using django framework 2.2 class Reglement(models.Model): """Model definition for Reglement.""" # TODO: Define fields here client = models.ForeignKey(Client, on_delete=models.CASCADE) montant = models.DecimalField(max_digits=10, decimal_places=2) date_reglement = models.DateField(default=timezone.now) date_expiration = models.DateField(default=timezone.now) actif = models.BooleanField(default=True) abonnement = models.ManyToManyField(Abonnement) class Meta: """Meta definition for Reglement.""" verbose_name = 'Reglement' verbose_name_plural = 'Reglements' def __str__(self): """Unicode representation of Reglement.""" return f'{self.client} {self.montant}' @property def get_tarif(self): data = self.abonnement.values_list('tarif',) newData = "" if len(data) > 1: list_data = [] for i in data: for j in i: list_data.append(j) newData = sum(list_data) else: newData = data[0][0] total = newData - self.montant return total -
Succesful migrations and migrate but "ProgrammingError: relation "Patient" does not exist LINE 1: ..." while trying to populate data
I have created a custom User model and have two models "Staff" and "Patient" having OneToOne relationship with my custom User model. I have successfully migrate but when I tried python populate_health.py , I get this ERROR: "django.db.utils.ProgrammingError: relation "Patient" does not exist LINE 1: ...el_no", "Patient"."address", "Patient"."NIN" FROM "Patient" ..." models.py class User(AbstractUser): #use email as authentication username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'labPeople'), (3, 'receptionist'), (4, 'patient'), (5, 'admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) def __str__(self): return self.email # class Meta: # db_table = 'auth_user' class Staff(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='staff') id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255,unique=True) department = models.ForeignKey('Department', on_delete=models.CASCADE, db_column='department', blank=True, null=True) hospital = models.ForeignKey('Hospital', on_delete=models.CASCADE, db_column='hospital', blank=True, null=True) class Meta: # managed = False db_table = 'Staff' class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='patient') email = models.EmailField(max_length=255,unique=True) fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255,blank=True,null=True) address … -
Add javascript to django admin change form
I'm trying to add the following https://github.com/ubilabs/geocomplete to a textbox on the admin pages in django that add/edit models. I'm unable to find out how I add the necessary scripts as said in the README, how to I add javascript to the admin pages? Some other similar solutions have not worked. -
Bootstrap Modal Not Submitting/Redirecting in Django
I have a bootstrap modal - it renders fine and submits fine, but when I change the url I would like for it to use when a user submits the form, it no longer submits. It also does not redirect to the url I want to use. views.py #view for the modal class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') #when this is set to 'index' it works fine #view I would like to land on when form is submitted def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() return redirect('manifest') else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) manifest_readonly.html #html file for page I am launching the modal from, as well as the one I would like to land back on <div class="container"> <div class="col-xs-12"> {% if messages %} {% for message in messages %} <div class="alert alert-success" role="alert"> <center>{{ message }}</center> </div> {% endfor %} {% endif %} </div> </div> <div class="container"> <form id="create_mani_form" method="POST"> <br> <br> <br> {% … -
User Acccount (login, logout, sign in, vv...) get error 500 when i get DEBUG = False
When I set DEBUG = False. User Account get Error 500. I done try fix it. But hopeless. Help me thanks. This is my setting.py file. """ Django settings for locallibrary project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECRET_KEY = '-ofza@cbrd#bn^ean07*0f7u1pkgy#4f(*uzb%y_j@pdx0nysd' SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '-ofza@cbrd#bn^ean07*0f7u1pkgy#4f(*uzb%y_j@pdx0nysd') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'widget_tweaks', 'rest_framework', 'crispy_forms', 'catalog.apps.CatalogConfig', 'django.contrib.admin', 'django.contrib.auth', # Core authentication framework and its default models. 'django.contrib.contenttypes', # Django content type system (allows permissions to be associated with models). 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'catalog.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions across requests 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # Associates users with requests using sessions. 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Store.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates") … -
Image files no longer appear in production how to fix the problem
Before anyone can tell me how to put the other question solved? Hello local site works well, but in Heroku the picture is not displayed anymore In production the static files are at the same level as the folder of the images according to the logging that's what breaks the problem thank you for your help. -
Query model for objects that do not have an associated child object
I am trying to display summary information about child objects, and about child objects that do and do not contain grandchild objects. Two of the three work, but not very well. I am not able to get a result set at all looking for child objects that do contain grandchild objects, though the result for objects that do not contain grandchild objects works. My models are Campaign, Lead, and leadQA. Models (relevant) class Campaign(models.Model): id = models.IntegerField(primary_key=True, unique=True) class Lead(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) class LeadQA(models.Model): lead = models.ForeignKey(Lead, on_delete=models.CASCADE) Views (relevant) lead_count_with_qa = list(Lead.objects.filter(campaign__id=pk, leadqa__lead=True).values_list('cid').annotate(Count('id'))) lead_count_without_qa = list(Lead.objects.filter(campaign__id=pk, leadqa=None).values_list('cid').annotate(Count('id'))) lead_qa_count = list(LeadQA.objects.filter(lead__campaign__id=pk).values_list('qa_status').annotate(Count('id'))) I get only an empty list for lead_count_with_qa. I've tried multiple permutations, and there are definitely related leadQA objects that have that object as the foreign key. -
Python social auth "AuthForbidden"
I am trying to get google authentication working with django using social-auth and I haven't had any luck as of yet. Other questions with similar error messages suggest that it could be caused by whitelisting, but I'd like to accept all gmail suffixes in my app. (no whitelist required) INSTALLED_APPS = [ 'livereload', # TODO Remove when finished 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard.apps.DashboardConfig', 'user.apps.UserConfig', 'social_django' ] Both 'social_django.context_processors.backends' and 'social_django.context_processors.login_redirect' are in my context processors in settings.py. AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) urlpatterns = [ path('dashboard/', include("dashboard.urls", namespace="dashboard")), path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(), name="login"), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('auth/', include("social_django.urls", namespace="social")), ] When I sign in with google and am redirected to my auth url, I get the message: AuthForbidden at /auth/complete/google-oauth2/ Your credentials aren't allowed How do I get this to work properly? -
Cannot make requests to APIs without auth token after added "WSGIPassAuthorization On"
We had a issue after deploying Django to AWS. The problem is that We cannot make requests to the APIs whose permission classes is set to "IsAuthenticated", even if we put the auth token in the header. permission_classes = (IsAuthenticated,) We can only make requests to the API whose permission_classes is set to "Allowany" After reading this post Authentication credentials were not provided. when deployed to AWS, We have figured out that it was the authorization header did not pass through. after we used the following command: 01_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' The exact opposite thing happended. The auth token somehow become mandantory. We can make request with auth token in the header only to the API whose permission classes is set to "IsAuthenticated". Making requests to the APIs with permission_classes set to "Allowany" returns 401. How do we fix it? Thanks in advance. -
How to host multiple site in single droplet
I just hosted my website on the digital ocean by following below link. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 It works like a charm. But i also want to host multiple site on the single drop let. I've no idea that how to host multiple site on the single droplet. Does name matters while creating gunicorn service file and socket file. I mean do I need to create separate service and socket file for separate project and also do i need to create separate sock file for separate project. -
.env reload with django-environ on uwsgi
I really need some punch. I do have fully setup and running project. Django, nginx, supervisor, uwsgi - emperor with touch reload enabled. # {{ ansible_managed }} [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown {{ deploy_user }}:{{ deploy_group }} /run/uwsgi' ExecStart=/bin/bash -c '{{ uwsgi_path }}/uwsgi --emperor /etc/uwsgi/vassals' Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target uwsgi.ini # {{ ansible_managed }} [uwsgi] project = {{ project_name }} uid = {{ deploy_user }} gid = {{ deploy_group }} base = /home/%(uid) chdir = %(base)/www/{{ project_url }}/%(project) home = %(base)/.pyenv/versions/%(project) module = config.wsgi ;logto = /tmp/uwsgi.log master = true processes = 10 harakiri = 30 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):%(gid) chmod-socket = 660 vacuum = true touch-reload = {{ project_path }}/{{ project_name }}.touch LANG=en_US.UTF-8 env = DJANGO_READ_DOT_ENV_FILE=True ;todo version for prod env = DJANGO_SETTINGS_MODULE=config.settings.{{ version }} when I make changes and touch file, it reloads everything as should, project running perfectly. But I do have an issue with .env file. django settings.py import environ ... env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file env.read_env(str(ROOT_DIR.path('.env'))) If I change something in .env file and upload it to the server, touch wsgi file, it does not … -
Django Channels Adding (Different Communicator) User to Group
I am writing a web-application using websockets from django-channels. In which: Customer users can make orders from store users. When a user requests an order via their communicator, I create a channel group using the order's id. The store related to this order should be added to this channel group as well. This is what I'm struggling to achieve. This logic can be seen in my pytest below: async def test_store_is_added_to_order_group_on_create(self, settings): customer = await create_customer() store = await create_store() product = await create_product(store=store) store_communicator = await auth_connect(store) # Log in as customer and create order customer_communicator = await auth_connect(user) await communicator.send_json_to({ 'type': 'create.order', 'data': { 'product': str(product.id), 'customer': user.id } }) response = await communicator.receive_json_from() data = response.get('data') await communicator.disconnect() # Send JSON message to new order's group. order_id = data['id'] message = { 'type': 'echo.message', 'data': 'This is a test message.' } channel_layer = get_channel_layer() await channel_layer.group_send(order_id, message=message) # Store should receive JSON message from server. response = await store_communicator.receive_json_from() assert_equal(message, response) await communicator.disconnect() The communicator function create_order should create a new channel_layer group to which both the customer and store should be added. async def create_order(self, event): order = await self._create_order(event.get('data')) order_id = f'{order.id}' # Add the … -
How do I solve this TemplateSyntaxError in Django that says "Could not parse the remainder"
I am trying to render a block of HTML code repeatedly using for loop. But Django throws a TemplateSyntaxError when I reload my browser <div class="carousel-item active"> {% for number in range(3) %} <!--Slide {{ number + 1 }}--> <div class="row"> {% for number in range(6) %} <!--Slide 1 Col {{ number + 1 }}--> <div class="col-lg-2"> <div class="card" style="width: 100%;"> <img class="card-img-top" src="..." alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> {% endfor %} </div> I expected a repeated rendering of the blocks inside the for loop but got "TemplateSyntaxError at / Could not parse the remainder: '(3)' from 'range(3)'" instead -
How to design a database for ecommerce django website
I'm new to django and I'm trying to build ecommerce website but I'm facing a problem of storing data of products that don't share the same attributes , I'm wondring which database technologies to use and how design database in such way that i could store different products attributes without problems. Please help me solve this problem Thank you -
Auto Fill Text field from one text field to another with small change
Is there anyway to auto populate fields based on user input from the 1 text field, then update rest of the fields with small changes in each field. For example: [user input] Field 1 Network: 192.168.0.0 [auto] Field 2 Network_Util: 192.168.1.0 [auto] Field 3 Network_Util2: 192.168.2.0 I tried to for following code, but it copies the text, how to change the third octet value? <input type="text"id="network1" name="Network1" value="" > <input type="text" id="network2" name="Network2" value=""> $("#network1").keyup(function(){ var net = network1.split("."); var octet3 = net[2]; $("#network2").val(this.value); }); Thank you for your help -
Are atomic transactions supposed to produce more connection.queries in Django?
I have the following in my models: from django.db import models class X(models.Model): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) In one of my views, I am updating all my models like so: from .models import X, Y, Z from django.db import connection, transaction def do_something(bro, z_pk): z = Z.objects.select_related('y__x').get(pk=z_pk) y = z.y x = y.x ... with transaction.atomic(): z.save() y.save() x.save() print(len(connection.queries)) With the transaction.atomic(), the length of queries is 5. However, without it, the length returned is 4. That is, the following code: from .models import X, Y, Z from django.db import connection def do_something(bro, z_pk): z = Z.objects.select_related('y__x').get(pk=z_pk) y = z.y x = y.x ... z.save() y.save() x.save() print(len(connection.queries)) Returns a length of 4. Is this normal or am I missing something? Moreover, with the transaction.atomic(), am I hitting my database less times? Its difficult to understand that based on the connection.queries. Note: The extra query in the atomic function is the following: {'sql': 'BEGIN', 'time': '0.000'} -
A Desktop application for Django
I'm making a little Time Attendance Django Application where I want two parts of that program. A web part and a Desktop part. The Web Part would be used to view the Employees, Manager them, get payroll whereas the Desktop Part would be used to add attendance and stuff. And before anyone asks, I'll be using facial recognition for the attendance. So unless there's a way to use good and fast facial recognition on the web, I can't do it all on the Web. I was thinking of using electron. Make things simple. Have two login types, one for the web and the other for the Desktop. If that's the case, I would like to have different views and templates for the both of them without making a new app. Maybe add an option on the login page where you can choose either Desktop login or Web login. (Let me clear this here that by Web Login, I mean the Website like how you put in the URL in the browser and by Desktop Login, I mean the same thing but outside a browser. I understand that Electron is a browser but I hope you understand xD) If this is … -
How to fix empty custom user fields submission on custom user model requested from rest-auth/registration?
I am just a beginner here. Please help me out. I am using Django REST Framework, with django-rest-auth, I created a custom user model with extra fields. I want to use the django-rest-auth registration endpoint to register a new user in one request, and thus sending all the data to create a new user, including the data for the extra field but the extra field are not receiving the data. I am using AbstractBaseUser. This is how i created my custom user class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password=None): user = self.model( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name, role_id=role_id, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self,username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password): user = self.create_user( username=username, email=email, first_name=first_name, last_name=last_name, role_id=role_id, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password): user = self.create_user( username=username, email=email, first_name="True", last_name="True", role_id=0, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, password=password, ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user #custom user table class User(AbstractBaseUser): username = models.CharField(max_length=120, unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) role_id = models.PositiveIntegerField(default=0) contact_num = PhoneNumberField(null=False, blank=False) …