Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Guidance to connect multiple Raspberry Pi's (v3) to Django for a SPA
So I'm trying to make a SPA to read different raspberry pi's sensor values on real time, and to change them as well. I've got some knowledge on Django, SQL, React and JS. As I lack experience using Rpi's, I've done some research and found that I need to set up Django in the Rpi's. However, this causes me the following concern: Should I set up a different Django Project for every Rpi that I have? (lets say I got 10 RPi3) If true how can I coordinate all Rpi's so that I can display all of them and their status in the same page? (React component to be specific). On the other case, should I have only one Django Project that gathers the information of all Rpi's? How can I make this possible? Thanks for your time. -
Django Rest Framework: How to custom serializer.data's value?
When I call serializer.data, ManyToManyField will be displayed as list of ids, but I want it to show tags's names instead of ids. models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=20) class Story(models.Model): title = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) serializers.py from rest_framework import serializers from stories.models import Story, Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name',) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ('title', 'tags') def is_valid(self, raise_exception=False): self.initial_data['tags'] = self.get_tags_ids(self.initial_data['tags']) return super().is_valid(raise_exception) def get_tags_ids(self, tags): tags_ids = [] for tag in tags: tag, _ = Tag.objects.get_or_create(name=tag) tags_ids.append(tag.id) return tags_ids then in shell In [1]: from stories.serializers import StorySerializer In [2]: StorySerializer() Out[2]: StorySerializer(): title = CharField(max_length=100) tags = PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=Tag.objects.all()) In [3]: TEST_DATA = { ...: 'title': 'A story', ...: 'tags': ['horror', 'action'], ...: } In [4]: ser = StorySerializer(data=TEST_DATA) In [5]: ser.is_valid() Out[5]: True In [6]: ser.data Out[6]: {'title': 'A story', 'tags': [1, 2]} How to let ser.data return {'title': 'A story', 'tags': ['horror', 'action']} instead? -
My update function is not working i have been stuck on this method assistance required with update method to wrk in srilizer.py modelSerializer?
Serializer.py follwing is my code i have created create method like this is working perfectly but when i tried to make update function its not working it is just updating title and type but i am not able update category question and choice in real they have there own serializer and models i am newbie to python def update(self,instance,validated_data): data = request.data print(data) evaluationtest = EvaluationTest() admin= User.objects.get('username') cat=Category.objects.get('id') print(cat) instance.category=cat instance.category = validated_data.get('id',instance.category) instance.title = validated_data.get('title',instance.title) instance.type = validated_data.get('type',instance.type) instance.save() instance = EvaluationTest() for q in instance['questions']: newQ = Question() newQ.question=q['title'] newQ.order = order newQ.save() for c in q['choices']: newC = Choice() newC.title = c newC.save() newQ.choices.add(newC) newQ.answer = Choice.objects.get(title=q['answer']) newQ.instance = instance newQ.save() order += 1 return instance -
Conditional statement in django template
This is my models: class Profile(models.Model): date = models.DateTimeField(auto_now_add=True) full_name = models.CharField(max_length=32,blank=True) name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) class Organisation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,related_name='organisation_user',on_delete=models.CASCADE) name = models.CharField(max_length=100,blank=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='organisation_members',blank=True) I have to create a condition in my template that if member in the manytomany field is already there it will show 'Already added' or else 'Add Member' and I want to do it in the profile list view template. So I have done the following in my template: {% for prof in profile %} {% if member in prof.Name.organisation_user.members %} <a href="{% url 'userprofile:add_member' pk=prof.pk %}" class="btn btn-info" role="button"><i class="fa fa-plus" aria-hidden="true"></i>Already added</a> {% else %} <a href="{% url 'userprofile:add_member' pk=prof.pk %}" class="btn btn-info" role="button"><i class="fa fa-plus" aria-hidden="true"></i>Add member</a> {% endif %} {% endfor %} -
Need to show related model specific field on admin changelist - Django 1.11
I have a model like this: class MyModel(models.Model): status = models.CharField(choces=ChoicesModel.MY_CHOICES, max_length=128, blnk=True, null=True) I have a separate model with the choices, for a matter of reusability. That works well so far. Now, on the admin view, I need to show these choices, but in another model's list_display. I have tried many things with no success. These models are related with a ForeignKey. So, specifically, I need the parent model list_display, to show the choice made on the child model related by the ForeignKey. The ForeignKey is defined on the child model, so it is related to the parent with this ForeignKey field. So, how can I read this choice made on the child object from the parent and show it on the list_display of it's parent? I'm using Django 1.11 -
Return a value from a marker in a Leaflet Map to Django
I want to choose an object for further data analysis by clicking on a Leaflet map marker. So, by clicking on a button on the information popup on the leaflet map, a API is called that sets the values for the following actions. I have the following questions: How do I build that interactive popup that allows communication between the map and the database? How do I construct this communication? AJAX? -
how to create web app using django like plugshare? [on hold]
I want to make web app like plugshare , map tracking , and share home Charger on map or what the Technology should i have use Thank you -
Selenium has stopped working, chrome versions do not match
On my CI, selenium started failing recently with: selenium.common.exceptions.WebDriverException: Message: chrome not reachable (Session info: headless chrome=73.0.3683.75) (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.4.0-141-generic x86_64) This is in a django SeleniumTestCase, with a custom webdriver as follows: class WebDriver(web_driver_module.WebDriver): """Our own WebDriver with some helpers added""" def __init__(self, *args, **kwargs): chrome_options = kwargs.get("chrome_options", Options()) chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") kwargs["chrome_options"] = chrome_options super().__init__(*args, **kwargs) The weird thing is that when I apt install chromedriver (beforehand) I get the following: Preparing to unpack .../36-chromium_72.0.3626.122-1~deb9u1_amd64.deb ... which is a different version from that referenced in the WebDriverException. What is going on? -
AWS S3: Collectstatic from multiple path
I have my static asset files in a folder assets and other static files in the default folder myProject | myProject | assets | jquery | bootstrap | default | css | js | urls.py | settings.py | uwsig.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [os.path.join(BASE_DIR, PROJECT_NAME + "/" + TEMPLATE_THEME), os.path.join(BASE_DIR, PROJECT_NAME + "/assets")] AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID', "") AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY', "") AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME', "") AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = None AWS_PRELOAD_METADATA = True AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400', } AWS_STATIC_LOCATION = 'static' if USE_LOCAL_MEDIA: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_URL = "/static/" MEDIA_URL = '/media/' else: STATICFILES_STORAGE = 'core.overrides.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) AWS_PUBLIC_MEDIA_LOCATION = 'media/public' DEFAULT_FILE_STORAGE = 'core.overrides.storage_backends.PublicMediaStorage' AWS_PRIVATE_MEDIA_LOCATION = 'media/secured' PRIVATE_FILE_STORAGE = 'core.overrides.storage_backends.PrivateMediaStorage' STATICFILES_DIRS should collects all the static files and this works well when USE_LOCAL_MEDIA is True. But, if I want to switch S3 SORAGE by turning USE_LOCAL_MEDIA to False and then run "python manage.py collectstatic", it collects all the static files except the ones in assets folder. Please what am I doing wrong here -
Adding form validation to django modelform by overriding clean
I have a long modelform with mostly modelform validation, and I'd like to have a 'Please correct the errors below' error at the top of my form, when any of the individual fields fail to validate. I attempted to do this by overriding the clean method on the modelform, but there are no errors at this point. # models.py class MyModel(models.Model): myfield = models.IntegerField(default=0, validators=[MinValueValidator(0)]) # forms.py class MyModelForm(forms.ModelForm) class Meta: models = MyModel fields = ['myfield'] def clean(self): cleaned_data = super().clean() if any([field.errors for field in self]): raise forms.ValidationError("Please correct the errors below.") return cleaned_data When I enter an invalid value, such as -1, the field still shows the correct error message beneath it, but the form does not have any errors. I'm using {% crispy %} to render the form, which automatically places the form errors at the top, so it's not a template issue. The issue (from the debugger) is that at the point when clean() is being called, form['myfield'].errors is empty. -
Django returned more than one Book -- it returned 3
I don't know what to do in this error. MultipleObjectsReturned at /premium/1/ get() returned more than one Book -- it returned 3! i have list of book.. user will be customer if admin put him in Customer model at will have an access in full content of the book. i have this code where i suspect where the error came from views.py def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) book content in the same views.py class PageDetailView(LoginRequiredMixin, generic.View): def get(self, request, *args, **kwargs): book = get_object_or_404(Book) page = get_object_or_404(Page) user_membership = get_object_or_404(Customer, user=request.user) user_membership_type = user_membership.membership.membership_type user_allowed = book.allowedMembership.all() context = {'object': None} if user_allowed.filter(membership_type=user_membership_type).exists(): context = {'object': page} return render(request, "catalog/page_detail.html", context) and my models.. class Book(models.Model): ////Some field for book info//// allowedMembership = models.ManyToManyField(Membership, blank=True) def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) def __str__(self): return self.title @property def pages(self): return self.page_set.all() content part β¦ -
Failed to start gunicron.service: Unit gunicron.service not found
When I try to run gunicorn: sudo systemctl start gunicron It shows me this Error. It also gets stuck while creating the wsgi file enter image description here gunicorn service configuration enter image description here -
Not able to login due to CSRF Error in Angular-Django
I am trying to login to my back-end written in django-rest-framework from my frontend written in Angular 7. Whenever I tries to login, I gets an error Access to XMLHttpRequest at 'http://localhost:8000/api-auth/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. When I tried the same API from postman, I got another error - CSRF verification failed. Request aborted. I am not sure how to include csrf token in my app to resolve this error. my login.html <form [formGroup]="loginForm" (ngSubmit)="login()"> <div class="row"> <div class="col-md-12 align-content-center py-3"> <mat-form-field> <input matInput placeholder="Enter your username" formControlName="loginUsername"> </mat-form-field> </div> <div class="col-md-12 align-content-center py-3"> <mat-form-field> <input matInput placeholder="Enter your password" type="password" formControlName="loginPassword"> </mat-form-field> </div> <div class="col-md-12 align-content-center py-3"> <button mat-raised-button type="submit">Login</button> </div> </div> </form> and login.serivce file is as follows: import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Injectable} from '@angular/core'; export interface Login { username: string; password: string; } export interface Signup { username: string; email: string; password: string; } @Injectable() export class LoginSignUpService { loginObject: Login; signupObject: Signup; constructor(private http: HttpClient) { } public login(username: string, password: string) { this.loginObject = { username, password }; const headers = β¦ -
Cancel linkedin authorization is not working
If a user tries to cancel linkedin authentication with python_social_auth in django, it gives an error: This is my redirect_uri on my linkedin app: http://www.localhost:8000/complete/linkedin-oauth2/ I honestly dont know what to do -
Create a chat thread only if user sends a message
I'm using Django Channels 2.1.2 with my Django 2 project and need some assistance in configuring the thread to only be saved if a user actually sends a message. Right now, if a user clicks on chat, they go to the chat message page and the thread is created and saved in their inbox. Even if they decide to not end up messaging, the empty chat is still visible in both users inboxes. The thread needs to be saved only after either user has sent a message. Would someone mind helping me with this as I'm not sure what to do? I assume this line somehow needs to be modified obj, created = Thread.objects.get_or_new(self.request.user, other_username) views.py class InboxView(LoginRequiredMixin, ListView): template_name = 'chat/inbox.html' context_object_name = 'threads' def get_queryset(self): return Thread.objects.by_user(self.request.user).order_by('-timestamp') # by_user(self.request.user) class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url = '#' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created = Thread.objects.get_or_new(self.request.user, other_username) if obj == None: raise Http404 return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) β¦ -
queryset not loaded in ModelSelect2Widget in Django Select2
Here is my database: class Student(models.Model): name = models.CharField(max_length=25) class Subject(models.Model): title=models.CharField(max_length=25) marks = models.FloatField() student = models.ForeignKey( Student, related_name='student', on_delete=models.PROTECT, ) Now I want to use django select 2 to view those details in django admin panel. Here is my form class AddressForm(forms.ModelForm): student = forms.ModelChoiceField( queryset=Student.objects.all(), widget=ModelSelect2Widget( model=Student, search_fields=['name__icontains'], ) ) subject = forms.ModelChoiceField( queryset=Subject.objects.all(), widget=ModelSelect2Widget( model=Subject, search_fields=['title__icontains'], dependent_fields={'student': 'student'}, ) ) I want to select each student and select each subject. but i am getting this output : my output I can view anything -
Django: Is it possible to exclude fields in view?
I need to exclude some of my form's fields in the view. I know it is possible to do in the actual form with .exclude function, but in that case I'd need to make one form for each case. I can't do this in the template because I'm using crispy_forms.helper, calling it in the template with {% crispy form %}, otherwise I would iterate over fields and exclude which I need. I would need to do something like: form = ArtiForm(instance=Articulo.objects.get(codigo=arti), filter_on=request.session['codEmp']).exclude(field) But exclude is not a form attr in view. Any way to handle this? -
How to use Last-Modified header with Django Rest Framework ViewSet?
Let's say I have following Django Rest Framework's ViewSet: from django.contrib.auth import get_user_model from rest_framework.viewsets import ViewSet from rest_framework.response import Response class SubscriptionViewSet(ViewSet): def list(self, request): data = {'user_count': get_user_model().objects.count()} return Response(data) How to use it together with last_modified decorator from Django? Or how to implement such functionality? -
python Django hear my two album and album in two name 1) red and 2) high school but red and high school does not open
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/%7B%20%25%20'music:detail'%20album.id%20%25%7D Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: ^admin/ ^music/ ^$ [name='index'] ^music/ ^(?P[0-9]+)/$ [name='detail'] ^music/ ^(?P[0-9]+)/favorite/$ [name='favorite'] The current path, music/{ % 'music:detail' album.id %}, didn't match any of these.enter code here You're` enter code here ` seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Relation made on calculated field
Let's assume i have a models.py like this: class Employee(models.Model): name = char... code = int... email = email... evaluations = fk(Evaluation) <----- class Evaluation(models.Model): date = date... points = int... emp_code = char... <----- is it possible to do a relation based on a computed field? i mean in the DB i can not store de emp_code from Evaluation in plain text so i have a function to hide the code but i dont know how to make the relationship based on a function. Thanks in advance. -
Django max_length of another model attribute
I want to have the integer value of one model attribute be the max_length of another model attribute like mentioned below "capacity = models.IntegerField(max_length=Concerthall.capacity)". class Concerthall(models.Model): name = models.TextField(max_length=254) capacity = models.IntegerField() employees = models.IntegerField() def __str__(self): return self.name class Events(models.Model): name = models.TextField(max_length=254) capacity = models.IntegerField(max_length=Concethall.capacity) timeFrom = models.DateTimeField() timeTo = models.DateTimeField() concerthallName = models.ForeignKey(Concerthall, on_delete=models.PROTECT, null=True) Maybe it is also working with validators but I searched for several hours and wasn't able to find any solution to this. -
passing the values dynamically (eg: innerHTML) to another element as a value
I've a form with three fields, which are rendered via the jinja2 template & the fields are part of a Django ModelForm. The fields are: CharField, FileField, and Textarea. And, I've also a textarea like <div> element which exactly works like Stackoverflow's editor, omitting some options like <code>, <image> ... But, it's totally JavaScript based. Which when rendered on the page disabling that existing TextArea that was rendered from the ModelForm. As, I defined on the page... <script> $(document).ready(function () { $('#txtArea').TxtEdtr(); }); </script> I've mentioned both the element's IDs same, to always render the second textarea by overriding the first one. And, by hiding that element by - display: none. And to pass the context of the 2nd created textarea to that modelform textarea, I've used: $('.myeditor').keyup(function () { $('#txtArea').innerHTML = $('.myeditor').html(); }); By looking at the browser console I can see that keyup is working but, the context or the 1st element isn't affected. And, as it's a required element I can't submit the form also. For example, I want to pass that html context as a string to that ModelForm's textarea element before the form is submitted: $('#txtEditor').innerHTML = $('.editor').html(); result to pass: "<span style=\"font-style: italic;\">hi there β¦ -
Static files of django, nginx and gunicorn app using docker?
I am not able to get the static files to come up. I've tried various settings and directory configurations and so on, but they just turn up as 404s. The folder structure of application as below . βββ config β βββ nginx β βββ conf.d β βββ local.conf βββ docker-compose.yml βββ Dockerfile βββ aggre β βββ aggre β βββ manage.py | βββ static βββ requirements.txt Settings.py look like STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR),'static'] STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static') Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/django/src WORKDIR /opt/services/django/src COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY . /tmp/ COPY . /opt/services/django/src RUN python aggre/manage.py collectstatic --no-input # <-- here CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait" EXPOSE 8000 ADD . /opt/services/django/src CMD ["gunicorn", "--chdir", "aggre", "--bind", ":8000", "aggre.wsgi:application"] docker-compose.yml version: '2' services: djangoapp: build: . volumes: - .:/opt/services/django/src - static_volume:/opt/services/django/static/ networks: - nginx_network nginx: image: nginx:1.13 ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/django/static/ depends_on: - djangoapp networks: - nginx_network networks: nginx_network: driver: bridge volumes: static_volume: local.conf server { listen 80; server_name ***.***.io; location / { proxy_pass http://djangoapp:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { alias /opt/services/django/static; β¦ -
Integrating a module's login view with my own login view in Django
I'm trying to use this library to add two factor authentication to my project. I noticed that the module's has its own login view, that you can find right here, see class LoginView(IdempotentSessionWizardView):. The problem i'm having with this it's that i already have my own login view to handle an authentication form, so why would i use the module's view? I would just need to add the 2FA part to my own view, instead of using another one, but unfortunately that module is not really clear on this part. So the problem is: how do i integrate their login view into my own login view? How can i just add the 2fa part to my own one without using another login handler? Any advice is welcome, here is my already existing login view: def login_request(request): if request.method == "POST": if result['success']: form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") -
filter ForeignKey(user) model based on certain group_name
In Django i have created a model which use USER model data this holds all user id form database, BUT i it filtered by certain group userId = models.ForeignKey(User, on_delete=models.CASCADE) model.py form displayed(with all user_id)