Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flutter authentication with Django on the back
If I want to add login/logout and signup functionality in flutter with Django on the back authenticating my flutter app users, how would I go about doing it? -
Emacs. Is possible to use Flycheck and pylint django?
I use lsp-mode and flycheck My .pylintrc config: [MASTER] load-plugins=pylint_django What do I need to configure? -
how to create one-to-one related user roles with djoser
I have a Custom user model and 4 role models class User(models.Model): is_student = True is_teacher = True is_staff= True is_admin = True Class Student(models.Model): user = models.Foreignkey(User) Class Teacher(models.Model): user = models.Foreignkey(User) Class Admin(models.Model): user = models.Foreignkey(User) Class Staff(models.Model): user = models.Foreignkey(User) I'm using djoser for User authentication. Now what I want is when somebody POST to 'api/v1/{role name}/register' User is created automatically and so is the role model's object. Currently I know that only POST request to '/users' will create the user in djoser and I have to use post_save signal when is_{role} field in user model is true, to save any role model object. I'm trying to use a nested serializer but that is not compatible with djoser. -
Django Template Autor-reload
How can i disable Django 3.2 from reloading the server whenever i edit template files in development. This is actually making my productivity slow because it takes 1-4 secs to reload. -
How to force field mappings with a ManyToMany relationship on same model
I have a fairly simple model representing users: class Person(AbstractUser): students = models.ManyToManyField("web.Person", through="Supervision") ... with a many-to-many relationship to itself... class Supervision(models.Model): student = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="supervisor") supervisor = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="student") created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: unique_together = [['student', 'supervisor']] def __str__(self): return "{supervisor} supervises {student} ({id})".format( supervisor=self.supervisor, student=self.student, id=self.pk ) The problem comes when I create a relation between 2 persons: >>> prof = Person.objects.get(last_name="prof") >>> student = Person.objects.get(last_name="student") >>> prof.students.add(student) >>> prof.save() >>> Supervision.objects.all() <QuerySet [<Supervision: student, student (1130) supervises prof, prof (97) (2)>]> It seems that Django swaps the relation by default. I tried to swap the related names in the class definition of the Supervision: class Supervision(models.Model): student = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="student") supervisor = models.ForeignKey('web.Person', on_delete=models.CASCADE, related_name="supervisor") But it does not help. How can I get Django to put the fields in the correct order? -
get() keywords must be strings
I can't tell what is the problem, and where the problem is. I was able to upload files through django import export but now I am not able to do so. Here is my Traceback. Traceback (most recent call last): File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "D:\Python\Django\test projects\library manage\lib_system\Library-System\libman\import_export_views.py", line 227, in post result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 741, in import_data return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 788, in import_data_inner raise row_result.errors[-1].error File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 635, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 330, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\resources.py", line 323, in get_instance return instance_loader.get_instance(row) File "C:\Users\FR GULIK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance return self.get_queryset().get(**params) TypeError: get() keywords must be strings This si the resource file class ImportBooksResource(resources.ModelResource): def __init__(self, school_id,*args,**kwargs): super(ImportBooksResource,self).__init__() self.school_id = school_id self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Books,'id')) self.fields['department'] = fields.Field(widget=ForeignKeyWidget(Departments, 'name')) … -
Django configuration LDAP using Django-auth-ldap
I am trying to configure LDAP authentication on my django project. Before get into django, I have tested following shell command can return successfully. ldapsearch -H ldap://172.16.34.4 -b "dc=corp,dc=rate,dc=com" -D corp\\peter -W sAMAccountName=peter result: ... # search result search: 2 result: 0 Success # numResponses: 3 # numEntries: 1 # numReferences: 1 But when comes to django settings.py, You know there are many items to set. And I tried many combinations but with no lucky. AUTH_LDAP_SERVER_URI = 'ldap://172.16.34.4' AUTH_LDAP_USER_SEARCH = LDAPSearch( "DC=corp,dc=rate,dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "name": "cn", "email": "mail", "first_name": "displayName", "last_name": "sn" } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend' ) And I create a API to login: from rest_framework.views import APIView class LoginAuth(APIView): def post(self, request, *args, **kwargs): user_loggedin = 'guest' display_name = 'guest' username = self.request.data.get('username') password = self.request.data.get('password') usergo = authenticate(username=username, password=password) # usergo always returns None print('authuser', usergo) if usergo is not None: auth_login(self.request, usergo) user_loggedin = usergo.username display_name = usergo.first_name context = { 'username': user_loggedin, 'displayName': display_name, 'state': False } return Response(context, status=status.HTTP_200_OK) return Response( f'Failed to authenticate with {username} / {password}', status=status.HTTP_400_BAD_REQUEST ) When access the endpoint with post data, I got error as the following (usergo always returns None): … -
How to validate if user id in uidb64 format or plain id?
How to check in django view if passed id has uidb64 format or plain integer? -
Problem sending code from Azure DevOps to Azure App Service
I am having a performance problem between Azure DevOps and Azure App Service. I'm developing in Django. In Azure DevOps I have a build pipeline that creates a zip file, then I have a release pipeline that sends that file to Azure App Service. Doing this does not work, but if in Azure App Service, in the deployment center I remove the connection to Azure DevOps, I make a connection to GitHub and there I put the same code that I tried previously, then it works. I have invested many hours and I cannot find the problem. Are there ways to view logs in Azure App Services? Is there a file explorer? Build pipeline configuration: #Multi-configuration and multi-agent job options are not exported to YAML. Configure these options using documentation guidance: https://docs.microsoft.com/vsts/pipelines/process/phases pool: name: Azure Pipelines variables: python.version: '3.8' steps: task: UsePythonVersion@0 displayName: 'Use Python $(python.version)' inputs: versionSpec: '$(python.version)' script: 'python -m pip install --upgrade pip && pip install -r requirements.txt' displayName: 'Install dependencies' script: 'pip install flake8 && flake8' displayName: Flake8 enabled: false continueOnError: true script: 'pip install pytest && pytest tests --doctest-modules --junitxml=junit/test-results.xml' displayName: pytest enabled: false task: PublishTestResults@2 displayName: 'Publish Test Results /test-results.xml' inputs: testResultsFiles: '/test-results.xml' testRunTitle: … -
how to add a combobox with the groups in sqlite in sign up form django
I need help with the sign up form. I want to add a combo box in the form where the users register, this combobox have to have as options the groups that are created in sqlite. How can i do this, please help me -
Add data to a form in `CreateView`
I have a model which the user submits on a form, and I would like to handle that form with a CreateView. However, there is one field in the model which the user doesn't provide, which is their IP address. The problem is that the CreateView fails with an IntegrityError since the field is empty. I tried modifying request.POST to add the relevant field, but that's not allowed (and a bad idea). I figured I could use a hidden input on the form and put the IP there but that means the user can blank it or modify it if they like, I want the exact IP that did the POST request. If I understand correctly both the form_valid and form_invalid methods are too early in the process, since the object hasn't been created yet? Is there any other way of doing this? -
What should I do making a template using vue.js in django
I want to customize a template on django and use vue.js on that. What steps should I follow. What should I do first? Should I make a template on django and then vue? Please its urgent. -
How to get Nested array from local storage in javascript
I am storing user data in local storage after successful user login in angular let authObservable: Observable<any>; authObservable = this._authService.login(this.f.email.value, this.f.password.value); authObservable.subscribe( result=> { localStorage.setItem('id', result['id']); localStorage.setItem('username', result['username']); localStorage.setItem('email', result['email']); localStorage.setItem('tokens', result['tokens']); } but token contain another array "id": "user_id" "tokens": "{'access': 'access_token', 'refresh': 'refresh_token_value'}" "username": "username value" how can i get tokens value and access token value and store it in refresh_token and access_token variables. -
Djoser 400 Bad request login users
I'm creating an e-commerce app with django rest framework and vue, I'm using djoser.authtoken to handle authentications. I could successfully create a user with a post request to /users/ but whenever I try to log in I keep getting xhr.js:177 POST http://127.0.0.1:8000/api/v1/token/login/ 400 (Bad Request) in the console and [22/May/2021 03:06:11] "POST /api/v1/token/login/ HTTP/1.1" 400 68 on the server. The error messages aren't giving any useful info but here are some of the relevant snippets for my code: # myproject/urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'product', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:3000", "http://127.0.0.1:3000", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] // axios request await axios .post('/api/v1/token/login/', formData) .then(res => { const token = res.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common['Authorization'] = 'Token ' + token localStorage.setItem('token', token) const toPath = this.$route.query.to || '/cart' this.$router.push(toPath) }) .catch(err => { if(err.reponse){ for (const property in err.response.data) { this.errors.push(`${property}: ${err.response.data[property]}`) } } else { console.log(err) } … -
Handling images files on the backend in Django Rest sent from an array on the frontend
I am not sure the backend has to do anything with it ie this has to be solved by only frontend. I have post API where data is to be sent like this. { "merchant": 2, "category": [ 7 ], "brand":7 , "name":"picture55test", "best_seller":true, "top_rated":false, "collection":10, "description":"abc", "featured": false, "availability": "in_stock", "warranty": "no_warranty", "rating":5, "picture": [], "services": "cash_on_delivery", "variants": [ { "product_id": "OAXWRTZ_12C", "price": "500.00", "size": "not applicable", "color": "not applicable", "variant_image": null, "quantity": 10, "variant_availability": "available" }, { "product_id": "OGROUPIRZ_12C", "price": "888.00", "size": "not applicable", "color": "not applicable", "variant_image": null, "quantity": 10, "variant_availability": "available" } ] } I am here trying to create a product object creating the variants objects at the same time. The issue is it works the frontend is not being able to send image from array of variants which is vairant_image in the form-data. The payload headers look like this As you can the variant fields like coming like an object instead of a form-data. I dont know how to handle this in backend?? My view looks like this. I have used FormParser and Multipartparser just in case it handles the image. I just dont know if this is to be handled from frontend or … -
Pass a variable in the html template in django
I need to create an html django template a paragraph with a select dinamically created. I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything. This is my views: views.py def index(request): context = { 'variable': 'This has been sent' } return render(request, 'index.html', context) and this is the print in the html template: And this is the variable I'm calling in the HTML template: index.html <p>Hey Dear! {{variable}}</p> Can anyone help me? -
How to create files to avoid permission issues in docker?
I am new using docker and i have a task to create two containers: one for a django project and another for a mysql server. I made it using Dockerfile and docker-compose.yml. The project it's working with "docker-compose up", but i have permission problems when i try to create new files inside the container with "python manage.py startapp app_name". Basically i can't modify the files inside my ide(pycharm ubuntu). For what i can understand the user in the docker is root, so i need to have root permission to change those files but i don't want to modify them as root or change the permission of those files each time i make them. Here is my Dockerfile: FROM python:3.9.5 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 docker-compose.yml version: "3.9" services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - mysqldb mysqldb: image: mysql:5.7.34 restart: always environment: MYSQL_DATABASE: mydb MYSQL_USER: django MYSQL_PASSWORD: djangopass MYSQL_ROOT_PASSWORD: mysecretpassword volumes: - .dbdata:/var/lib/mysql ports: - 3306:3306 -
in react i had taken input file and trying to send to django server using redux dispatch action but file is empty in request.data
[ReportProblemActionTypes.SEND_REPORT_PROBLEM_FORM](state: reportProblemState):reportProblemState { return { ...state, sending: true, success: false, errors: {}, loading: true }; }, -
How to access 'related_name' of a model via intermediate model's Foreign key inside template tag?
models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) ... class Review(models.Model): paper = models.ForeignKey(Book, null=True, on_delete=models.CASCADE, related_name='book_class_related_name') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = RichTextField() status = models.CharField(max_length=10, choices=options, default='draft') ... class TrackReviewRequests(models.Model): paperid = models.ForeignKey(Book, null=True, on_delete=models.CASCADE, related_name='book_track') numberOfTimesReviewRequestSent = models.PositiveSmallIntegerField(default=0) ... views.py reviews_in_draft = Review.objects.filter(paper__active=True).filter(status='draft') return render(request, 'accounts/profile.html', { 'reviews_in_draft': reviews_in_draft, }) profile.html Here I tried accessing the 'numberOfTimesReviewRequestSent' using the following code: {% for review in reviews_in_draft %} {{ review.paper.book_track.numberOfTimesReviewRequestSent }} {% endfor %} But I am getting empty string. Then I wrote a method inside the Book model def get_TrackReviewRequests_numberOfTimesReviewRequestSent(self): return self.book_track.numberOfTimesReviewRequestSent and tried accessing the numberOfTimesReviewRequestSent in the profile.html using the following code: {{ review.paper.get_TrackReviewRequests_numberOfTimesReviewRequestSent }} But this time I got the error stating 'RelatedManager' object has no attribute 'numberOfTimesReviewRequestSent' Ultimately, I want to access the numberOfTimesReviewRequestSent in the template using the context variable. -
I'm trying to create a website through Vue and a DJango, and I wonder if this is right
As far as I know, Django processes the data as a back-end and delivers the data processed as a front-end. Then I'd like to process the API at back-end and deliver it to the front. I want to put API data in the designed model and hand over this model to Vue I wonder if it usually takes a long time to get 50 saved data. so I wonder if this is the right way and is there any solutions for this? -
How to have nested Orderables?
We have a content model with a couple of many-to-many (type) relationships: Issue has many Articles Article has many Authors In this specific case, our Article and Author models are fairly small. The use case is to construct a table of contents for a magazine Issue by creating a list of Article titles and one or more Authors for each Article. Ideally, the end-user could edit the entire Issue from a single form, since the articles are only used as a table of contents. I have tried to model this using the Page and Orderable classes, as follows. However, I am getting a KeyError when wagtail attempts to render the Issue edit form. class Author(Orderable): """ Represents authorship for an article allowing multiple authors per article and multiple articles per author """ article = models.ForeignKey( "magazine.Article", null=True, on_delete=models.PROTECT, related_name="authors", ) author = models.ForeignKey( "wagtailcore.Page", null=True, on_delete=models.PROTECT, related_name="articles_authored", ) panels = [ PageChooserPanel( "author", ["contact.Person", "contact.Organization"] ) ] class Article(Orderable): """ An article, which can have multiple authors """ title = models.CharField(max_length=255) issue = ParentalKey( "magazine.ArchiveIssue", null=True, on_delete=models.PROTECT, related_name="articles", ) panels = [ FieldPanel("title", classname="full"), # Multiple authors can contribute to an article InlinePanel( "authors", heading="Authors", help_text="Select one or more authors, … -
Django & Sqlite Database Access : No such table
I have a django & docker server running on my computer and I have created a database with code from outside this server. I am trying to access this database ('test.sqlite3') within the server. I made sure the path was the correct one and that the file name was correct as well. When I open the database with DB Browser, I can see the tables and all my data. But I still get the following error text: OperationalError no such table: NAMEOFTABLE When I use the exact same code from another python IDE (spyder) it works fine. I'm guessing there's something weird going on with django? Here is some of the code: conn = sqlite3.connect("../test.sqlite3") c = conn.cursor() c.execute("SELECT firstName, lastName FROM RESOURCES") conn.close() (Yes, I have also tried using the absolute path and I get the same error.) -
How to test Custom User model in Django fir a simple model used to track the data of other fields?
everyone. Hope you're doing well. So, I have two models, my main model where I have the data that goes to my endpoint, and a second model that I'm using to store the changes made to a field of the main model. They're very simple, like this: Main Model: . class MyModel(TimeStampedModel, models.Model): """A simple model""" field_1 = models.CharField(max_length=255, null=True, blank=True) field_2 = models.CharField(max_length=255, null=True, blank=True) choice_field = models.CharField( max_length=32, choices=ChoiceModel.choices, default=None, null=True, blank=False ) . . . 2.. And a Model used to store changing data of MyModel: Class MyModelHistory(models.Model): choice_field_from = models.CharField(max_length=32, null=True, blank=False) choice_field_to = models.CharField(max_length=32, null=True, blank=False) changed_at = models.DateTimeField() user = models.CharField(max_length=55) my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE) I'm only interested in storing the changes made to the choices field and the User who did it, with a timestamp. But since I have a Custom User model, I'm having some issues. To connect the two models is a little tricky. We could do it with signals or by modifying the __init__ and save methods of MyModel. For my application, I HAVE to do with the latter, so here's what I did for that: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #import pdb; pdb.set_trace() if self.pk is None: self._old_choice … -
reduce the same dockerfile for multiple services from running in each service
I have three services in the docker-compose file based on python and Django And I'm using a single dockerfile for these 3 services which have python image, pip install, apt install etc. Services one for WSGI services tow for Asgi (Channels) services Three for celery This return three large-size containers and use a lot of time How can I run this large process in one container and use the cache of other containers? Dockerfile FROM python:3.8.3-alpine WORKDIR /app ADD ./backend/requirements.txt /app/backend/ RUN apk add --update \ freetype-dev \ gcc \ gdk-pixbuf-dev \ gettext \ jpeg-dev \ lcms2-dev \ libffi-dev \ musl-dev \ openjpeg-dev \ openssl-dev \ pango-dev \ poppler-utils \ postgresql-client \ postgresql-dev \ py-cffi \ python3-dev \ zlib-dev \ bash RUN pip3 install --upgrade pip RUN pip install gunicorn RUN pip3 install -r backend/requirements.txt ADD ./backend /app/backend ADD ./docker /app/docker RUN chmod +x /app/docker/backend/wsgi-entrypoint.sh RUN chmod +x /app/docker/backend/asgi.entrypoint.sh RUN chmod +x /app/docker/backend/celery-entrypoint.sh docker-compose.yml version: '3.7' services: nginx: restart: unless-stopped build: context: . dockerfile: ./docker/nginx/Dockerfile ports: - 80:80 - 443:443 volumes: - static_volume:/app/backend/server/django_static depends_on: - backend - asgiserver backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/wsgi-entrypoint.sh volumes: - static_volume:/app/backend/server/django_static expose: - 8000 env_file: ./env/.django.prod environment: - SECRET_KEY=tv==u93r#vx(-f6xtt3&+npkjdl_h=zz6hgenha@_p=2s!!1fc - … -
I want make app in reactjs as front end and django as backend for AI project so how can I take live video feed from react
I try to run cammera on click event in reat from django url but it give error.I Want to build project using opencv .I am using reactjs as front end and django as back end from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def init(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livefe(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass