Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker: Unable to send task from Django to Celery
I have been working recently with Docker and I was able to set up certain services to be able to use Async functions but when I try to send a task to Celery from Django using RabbitMQ it never reachs. When I run the code outside Docker by running several commands on console everything runs perfectly. Not sure whats going on. Any help would appreciated. version: "3.7" services: rabbit: hostname: rabbit container_name: rabbitmq image: 'rabbitmq:3.7-management' environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: admin RABBITMQ_DEFAULT_PASS: admin RABBITMQ_DEFAULT_VHOST: "/" RABBITMQ_VM_MEMORY_HIGH_WATERMARK: 0.5 CELERY_BROKER_URL: "amqp://admin:admin@172.23.240.1:5672" ports: - "15672:15672" - "5672:5672" expose: - "5672" restart: on-failure networks: rabbitmq_net: aliases: - rabbitmq_host custom_app: build: . container_name: custom_app command: python manage.py runserver 0.0.0.0:8000 volumes: - static:/code/static - .:/code depends_on: - rabbit environment: - CELERY_BROKER='amqp://admin:admin@172.23.240.1:5672' - CELERY_BACKEND='amqp://admin:admin@172.23.240.1:5672' networks: - rabbitmq_net links: - rabbit nginx: image: nginx:1.13 container_name: nginx ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/code/static volumes_from: - custom_app depends_on: - custom_app networks: - rabbitmq_net celery: build: . container_name: celery command: celery -A djangoapp worker --loglevel=info -P eventlet debug volumes: - .:/code depends_on: - rabbit networks: - rabbitmq_net volumes: .: postgres_data: static: networks: rabbitmq_net: name: rabbitmq_network driver: bridge -
Django CKEditor - youtube embeded video disappear after saving at admin panel
There is no problem with uploading. But when I lookup to the article for editing then I can't see youtube video Before saving: After Saving: But actually the iframe block at there. The problem is I can't see it at admin panel again settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'CMS', 'width': '100%', 'toolbar_CMS': [ ['Format', 'Styles', 'FontSize'], [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'], ['TextColor', 'BGColor'], ['Link', 'Unlink'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Undo', 'Redo'], ['Copy', 'Paste', 'PasteText', 'PasteFromWord'], ['SelectAll', 'Find', 'Replace'], ['NumberedList', 'BulletedList'], ['Outdent', 'Indent'], ['Smiley', 'SpecialChar', 'Blockquote', 'HorizontalRule'], ['Table', 'Image', 'Youtube'], ['ShowBlocks', 'Source', 'About'] ], 'extraPlugins': 'youtube', 'contentsCss': ( '/staticfiles/ckeditor/customization-files/style.css', '/staticfiles/ckeditor/customization-files/bootstrap.css', ), }, } CKEDITOR_UPLOAD_PATH = 'content/ckeditor/' models.py class Article(models.Model): title = models.CharField(max_length=200) content = RichTextField( extra_plugins=['youtube'], null = False, blank=False, external_plugin_resources=[( 'youtube', '/staticfiles/ckeditor/extra_plugins/youtube/', 'plugin.js', )], ) updated = models.DateField(auto_now=True) created = models.DateField(auto_now_add=True) Django version: 3.2.3 django-ckeditor version: 6.1.0 Additionaly detail: When I click to "See HTML source" and save article then even the current video removing from database -
Django Form only show when i press Submit Button
my form is hide, its onlye display submit button, and when i click it the forms show. Crear Tarea= Create task. Its basically a crud for create task. Here are my Views: class Crear_Tarea(View): def get(self, request,*args,**kwargs): context = { 'form': TareaForm() } return render(request, "crear_tarea.html", context) def post(self, request,*args,**kwargs): context = { 'form': TareaForm() } formulario = TareaForm(request.POST or None) if formulario.is_valid(): formulario.save() messages.success(request, 'Tablero seleccionado con éxito!') context['crear_tarea']= formulario return render(request, "crear_tarea.html", context) My forms: class TareaForm(forms.ModelForm): class Meta: model = Tarea fields = ('nombre','descripcion','fecha_creacion','fecha_termino','user', 'id_columna' ,'id_tipo','detalle','id_documento','estado','estado_avance','posicion') def save(self, commit=True): user = super().save(commit=False) user.id = self.cleaned_data['user'] if commit: user.save() return user and my Models.py class Tarea(models.Model): id_tarea = models.AutoField(primary_key=True) nombre = models.CharField(max_length=99) descripcion = models.CharField(max_length=99) fecha_creacion = models.DateTimeField(null=True, blank=True) fecha_termino = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(Usuario, on_delete=models.CASCADE) id_columna = models.ForeignKey('Columna', on_delete=models.CASCADE) id_tipo = models.ForeignKey('Tarea_tipo', on_delete=models.CASCADE) detalle = models.CharField(max_length=255) id_documento = models.ForeignKey('Documento', on_delete=models.CASCADE) estado = models.IntegerField(blank=True, null=True) estado_avance = models.IntegerField(blank=True, null=True) posicion = models.IntegerField(blank=False, null=False) def __str__(self): return self.nombre crear_tarea.html {% extends "base.html" %} {% load static %} <!doctype html> <html lang="en"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}Crear Tarea Ari-J{% endblock %}</title> {% block content %} <div class="container-fluid"> <div class="row mt-5"> <div class="col-12 my-5"> … -
How to change edges (lines) color when filtering by a drop down menu javascript
I have a folim map drawing by a python code.I have a drop down menu on the left of the map. When selecting the Lane (input) value : all edgs associated to a Lanes value=1 should be colored as "#FF0000" all edgs associated to a Lane value=2 should be colored as "#FFF933" Could you please help me? {% load static %} {% block content %} <div class="row h-100"> <div class="col-md-2" id="destinationDiv"> </div> <div class="col-md-10"> {% include 'visualization/visualization.html' %} </div> <div class="form-group w-75 mx-auto"> <label for="linkSelector" class="sr-only">Links</label> <select id="linkSelector" class="form-control"> <option value="none">Links...</option> <option value="lanes">Lanes (input)</option> <option value="length">Length (input)</option> </select> </div> </div> <script src="{% static '/js/api/changeMapData.js' %}"></script> {% endblock %} My Javascript code which will fetch the data from the api. function changeMapData(){ fetch("http://127.0.0.1:8000/api/edges/") .then(response => { return response.json() }) .then((data) => { var linkSelector = document.getElementById('linkSelector') switch (linkSelector.value) { case "Lanes(input)": if($(edges.lanes)==1){ // Set all edges color = "#FF0000" with number of lanes=1 edges.setStyle ({ 'fillColor': "#FF0000", 'color': "#FF0000" }); } if($(edges.lanes)==2){ // Set all edges color = "#FFF933", with number of lanes=2 edges.setStyle ({ 'fillColor': "#FFF933", 'color': "#FFF933" }); } } }); } My html page containing the map. -
How can i create / Check permission using Django ? Real example
I'm working on a small project using Django / Rest Framework, and now i try to add Groups / Permissions options i don't know from where to start to do permissions checking. I surfed a lot on Google and here, i can't find any tutorial that explain how to use Groups and Permissions ( programmatically ), now I arrived to create a group / permission. like that : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Now how can i check if the user has X Permission or no ? where must i do this Logic ? also i heared some thing about default permission that any user has called ( Django Model Permission ) how can i use that ? my Goal is to create a Group and add user to a group, check if the user has the right permissions like any normal applciation can someone give me a small real example ? Thank you -
Get dynamic Form Value from Django Forms
I'm trying to get the totalPrice value from the changing value of the form field through JavaScript. My view part: if request.method == "POST": if (not closed): form = BookingForm(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.author = user booking.hotelName = hotel.name booking.save() success = "Success!" else: return render(request, "hotels/hotel.html", { "form": form }) messages.info(request, success) return HttpResponseRedirect(reverse("hotel", args=(hotel.id,))) else: return render(request, "hotels/hotel.html", { "hotel": hotel, "closed": closed, "message": message, "form": BookingForm() }) My HTML + JS Code: {% if not closed %} <div class="container login"> <h2>Book Now!</h2> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <div class="form-group"> <input type="submit" name="button" id="submit" value="Book"> </div> </form> </div> {% endif %} <script> let price = 0; const check = (id) => { if(document.querySelector(`#${id}`).checked) { price += 300; document.querySelector('#totalPrice').value = `${price}`; } if(!document.querySelector(`#${id}`).checked) { if (!price <= 0) { price -= 300; document.querySelector('#totalPrice').value = `${price}`; } } } document.addEventListener('DOMContentLoaded', function() { document.querySelector("#breakfast").addEventListener('click', () => check("breakfast")); document.querySelector("#dinner").addEventListener('click', () => check("dinner")); }) </script> And, my form (through ModelForm): class BookingForm(ModelForm): class Meta: model = Booking fields = ['includeBreakfast', 'includeDinner', 'totalPrice'] labels = { 'includeBreakfast': 'Include Breakfast', 'includeDinner': 'Include Dinner', 'totalPrice': 'Total Price (in USD)' } #Visual stuff the totalPrice is a FloatField in … -
i am getting an error while i am trying to add a user to a defined group while registration in django
#views.py def sign_up(request): if request.method == "POST": fm= SignUpForm(request.POST) if fm.is_valid(): messages.success(request,'account created') fm.save() group = Group.objects.get(name='groupname') User.groups.add(group) else: fm = SignUpForm() return render(request,'signup.html',{'form':fm}) and,i am getting AttributeError like this below:- Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'ManyToManyDescriptor' object has no attribute 'add' -
How can I convert/export HTML code returned by django-ckeditor's RichTextUploadingField to a docx file?
I want to convert html received from django-ckeditor Field to a docx file, for which I'm using htmldocx. The html code returned by ckeditor uses a css file which contains styles like background-color. So htmldocx is able to recognise bold, italics and alignment but it is not recognising the highlight color. contents of views.py: def home(request): if request.method == 'POST': htd = HtmlToDocx() document = Document() htd.add_html_to_document(request.POST.get('file'), document=document) document.save(settings.MEDIA_ROOT+'TEST.docx') form = File() return render(request, 'home.html', {'form': form}) else: form = File() return render(request, 'home.html', {'form': form}) contents of models.py: class Document(models.Model): file = RichTextUploadingField(blank=True,null=True) For example: for submitted text "Hello World" , where say 'World' is both, highlighted and in italics, the html code returned is: <p>Hello <em><span class="marker">World</span></em></p> #styles of marker class are defined in a separate css file by ckeditor but upon converting the html to docx, the document loses highlight color. Is there any workaround to this issue? Also, ckeditor provides an export to word feature but only through npm. If somehow I could use that feature in django-ckeditor, things would become much easier. How can I implement that feature in django-ckeditor? -
Why do I get an 404 Error in part 4 of the Django tutorial "Writing you first Django app"
I am trying to complete the Django tutorial: Writing your first Django app. I am currently stuck on part 4. After updating my template polls/templates/polls/detail.html, rewriting my polls/views.py and creating a results.html located at polls/templates/polls/results.html, I ran the server and tried to go to http://127.0.0.1:8000/polls/1/, but I get this Error: Page not found (404) No Question matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Raised by: polls.views.detail Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:question_id>/ [name='detail'] The current path, polls/1/, matched the last one. You’re 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. I see that the error is raised by the html-file detail wich looks like this: <form action="{ url 'polls:vote' question.id }" method="post"> { csrf_token } <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> { if error_message }<p><strong>{{ error_message }}</strong></p>{ endif } { for choice in question.choice_set.all } <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> { endfor } </fieldset> <input type="submit" value="Vote"> </form> My other two templates (html-files) index and result looks like this: … -
Django form validation fails when dynamically creating form by overwriting __init__
I'm writing a prediction app in Django. At a basic level it pulls matches from an API, populates the database, and finally allows users to make predictions on matches that have not yet been played. As I don't know how many matches will be in a tournament before the fact, I wanted to create a form that dynamically adds as many fields as is required. I currently have a "working" version but it would create issues further down the line. Here's the working version: (Fair warning, this is me testing, so excuse the naming conventions) views.py def ftest(request, contest_id): matches_list = Matches.objects.filter( matches_contest_pk__id = contest_id ).filter( matches_complete = False ).order_by( '-matches_start_time' ) matches = [ f'{match.matches_team_1} vs. {match.matches_team_2}' for match in matches_list ] if request.method == 'POST': form = TestForm(form_fields = matches, data=request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: print(form.errors) else: form = TestForm(form_fields = matches) context = { 'form': form, } return render(request, 'predictions/test.html', context) forms.py from django import forms from .models import Matches class TestForm(forms.Form): def __init__(self, *args, **kwargs): form_fields = kwargs.pop('form_fields', None) super(TestForm, self).__init__(*args, **kwargs) for field in form_fields: self.fields[field] = forms.CharField(label = f'{field}', max_length = 100) As I said, this works but I would, ideally, like to … -
open html file and add data into it with iteration
I have a html file for Invoice. and i want to display some data from my database which can be in multiple rows of a table. how can i use iteration to show the data in my Invoice. for example: In an organisation 3 people used a coupon to do a payment. and when invoice would generate all of the three people's name with date and amount i want to display. <thead> <tr> <th class="col-4 border-0"><strong>Sites</strong></th> <th class="col-4 border-0"><span><strong>Mode</strong></span></th> <th class="col-4 border-0"><span><strong>Amount</strong></span></th> </tr> </thead> <tbody> <tbody> ---for loop here--- <tr> <td class="col-4 text-1 border-0"> {var 1} </td> <td class="col-4 border-0"><span> {var 2} </span></td> <td class="col-4 border-0"><span> {var 3} </span></td> </tr> </tbody> </table> The way i am passing data from views is: my_dict=[{'var1':'my site', 'var2': 'DIY', 'var3':'111'}, {'var1':'my site2', 'var2': 'DIY', 'var3':'222'}] with open(BACKEND_TEMPLATE + 'Invoice_base.html') as inf: txt = inf.read() val = txt.format(date=today, invoice_id=str(identity), domain=FRONTEND_DOMAIN, customer_name=(obj.customer.first_name + " " + obj.customer.last_name), company=obj.customer.company_name, contact=obj.customer.phone_number, my_dict=my_dict) how can i achieve that. The html file is not supporting template tags or may be i am not using it correctly. if there is an easy solution please help me out! -
sliding key in Django how to
i am fairly new to python programing language and this year i challenged myself to build our project's app. We want the app to display certain features. To start with, this is our pseudo code : ' Inputs: Desired Max Temperature Tmax Intensity (in %) On or Off Tsurface Outputs LED0 LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off ' Python code ' from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ … -
Django Displaying Each User's Profile
I am building a website where there is a table at the homepage, and in that table there are people's names, numbers, their categories, the city they reside in, etc. I would like to create a link, that when a visitor clicks on any of the users' name, the visitor gets directed to that specific user's profile page. Right now, my code works partially. When I click any user, I get redirected to http://127.0.0.1:8000/profile/7/. That user ID number of "7" is the logged in user's ID. So no matter which user I click on, I get redirected to the profile page of the logged in user. Also, when I log out of the current user I am logged in to, I get this error message: "NoReverseMatch at / Reverse for 'profile_pk' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['profile/(?P[0-9]+)/$']" Here is what I have done with my code so far: views.py def ustaprofil(request, pk=None): if pk: user = get_object_or_404(User, pk=pk) else: user = request.user args = {'user': user} return render(request, 'user.html', args) urls.py path('profile/<int:pk>/', views.ustaprofil, name='profile_pk'), models.py class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) gizlilik_sozlesmesi = models.BooleanField("Gizlilik Sozlesmesini Okudum Onayliyorum*" , null=True) sartlar_sozlesmesi = models.BooleanField("Sartlar ve Kosullar … -
Best way to store heavily related values in relational database
I am trying to efficiently store heavily related data in a relational database. Table A stores the field names. Table B stores the type and Table C stores the values. I came up with the structure and the mappings as shown in this figure: Now when I want to query data from this table, we have to perform 2 hits for each relation. Also, for every insert I need to hit DB thrice(one for each table). Is there a better way to store this kind of structure? Is there a standard way to save this in Django models? -
Django path converter raises SynchronousOnlyOperation
I'm migrating an existing WSGI server to ASGI and I'm running into a problem where ORM usage in path converters raises a SynchronousOnlyOperation exception. My converter code is something like this class ModelPkConverter: regex = r'\d+' model = MyModel def to_python(self, primary_key): try: return self.model.objects.get(pk=primary_key) except self.model.DoesNotExist: raise ValueError def to_url(self, instance): return f'{instance.pk}' So when I go to a URL like /myapp/<MyModel:my_model>/ I get django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Where exactly am I supposed to put sync_to_async? If I do it in the converter like this @sync_to_async def to_python(self, primary_key): ... The converter outputs a coroutine object instead of a MyModel instance so I get AttributeError when I attempt to use it. AttributeError: 'coroutine' object has no attribute 'my_attribute' Am I supposed to await it in the view? That would defeat the purpose of using converters. I can just do get_object_or_404 instead. Is there a solution that doesn't involve setting DJANGO_ALLOW_ASYNC_UNSAFE to True? At this point, I'm considering refactoring everything away from the converters and using <int:mymodel_id> everywhere instead. Is there another way? -
how to make list of group by clickable django
i made a group by list of items based on two fields class Product(models.Model): type_of_product = models.CharField(max_length=30,default="electric) made_in = models.CharField(max_length=10,choices=countries,default="UK") product= models.CharField(max_length=30) views.py def categories(request): lists = Product.objects.values('type_of_product ', 'made_in').annotate( total=Count('pk') ).order_by('type_of_product ', 'made_in') return render(request,'shop/categories.html',{'lists':lists}) it returns something like this type_of_product : electric , made_in:UK , total:20 type_of_product : accessory , made_in:USA , total:23 and so on i want to make lists of categories clickable , when i click on one of them , it takes me to all products with the same features , for example i click on type_of_product : accessory , made_in:USA , total:23 it shows a list of products (23) item which made in from USA and type of product is accessory <div class="grid grid-cols-1 gap-6 pt-3 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 "> {% for i in lists %} <a href="{% url 'the link to products list' %}" class="transition transform cursor-pointer duration-400 hover:scale-105 hover:shadow-xl"> <div class="h-32 overflow-hidden rounded-tl-2xl rounded-tr-2xl room"></div> <div class="items-center p-2 rounded-bl-xl rounded-br-xl bglightpurple"> <div class="text-center rounded-lg" style="background: #534e70;"> <p class="inline textorange "><i class="bi bi-columns-gap"></i></p> <p class="inline text-white">{{i.type_of_product}}</p> </div> <div class="flex flex-wrap items-center justify-between mt-4 text-white"> <div class="text-sm"> <p class="inline ">{{i.product}}</p> <p class="inline px-1 text-sm bg-yellow-500 rounded-lg">{{i.total}}</p> </div> <div class="text-sm"> <p class="inline px-1 text-sm … -
DRF post to model with a many-to-many field which may only accept values that already exist
I have the following models: class Tag(TimeStampModel): name = models.CharField(unique=True, max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) featured = models.BooleanField(default=False, blank=True) class Deal(VoteModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deals', on_delete=models.CASCADE) title = models.CharField(max_length=1024, blank=False, null=False) slug = models.SlugField(max_length=1024, unique=True, blank=True) description = models.TextField(blank=False, null=False) poster = models.ImageField(blank=True) tags = models.ManyToManyField( Tag, blank=True) And the following serializers: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['id', 'name', 'slug', 'featured', 'created_at'] class DealSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) tags = TagSerializer(many=True, read_only=True) tags_ids = serializers.PrimaryKeyRelatedField(many=True, write_only=True, queryset=Tag.objects.all()) class Meta: model = Deal fields = '__all__' Views class DealList(viewsets.ModelViewSet, VoteMixin): serializer_class = DealSerializer permission_classes = [IsOwnerOrAdminOrReadOnly] def get_queryset(self): return Deal.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) I am able to get the data and also post it, but because of the many-to-many field (tags), I seem to have some issues as a Deal may have tags that only exist (created beforehand, and cannot be created through a post request to the Deal). I send data as the following: { title: 'some title', all_other_fields: 'some data', tags_ids: [2, 4] } The tags are sent as an array of tag ids, but I get an error as the following: "Incorrect type. Expected pk value, received str." I only added … -
How to filter related model rows of a django model?
Currently all related objects are being returned. I want to restrict related objects in such a way if I try to get PortfolioUser's education, I only get which has the value show=True models.py from django.db import models from django.db.models import Q from django.db.models.signals import pre_save, post_save # Create your models here. class PortfolioUser(models.Model): GENDER_CHOICES = [ ("M", "Male"), ("F", "Female") ] first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number = models.CharField(max_length=50) gender = models.CharField(choices=GENDER_CHOICES, max_length=1, null=True, default='M') about = models.TextField(null=True, default="Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad, blanditiis optio. Quia, corporis quidem. Nam aliquam officia rerum consequatur nisi ducimus nihil saepe aut excepturi, accusantium aspernatur possimus quod error!") is_active = models.BooleanField(default=False) class Meta: verbose_name = ("PortfolioUser") verbose_name_plural = ("PortfolioUsers") def __str__(self): return self.first_name+" "+self.last_name def get_absolute_url(self): return reverse("PortfolioUser_detail", kwargs={"pk": self.pk}) class Education(models.Model): education_name = models.CharField(max_length=254) institute_name = models.CharField(max_length=254) start_year = models.DateField(auto_now=False, auto_now_add=False) end_year = models.DateField(auto_now=False, auto_now_add=False) marks = models.CharField(max_length=50) show = models.BooleanField(default=True) portfolio_user = models.ForeignKey( PortfolioUser, on_delete=models.CASCADE, related_name="educations") class Meta: verbose_name = ("Education") verbose_name_plural = ("Educations") def __str__(self): return self.education_name+" -"+self.portfolio_user.first_name def get_absolute_url(self): return reverse("Education_detail", kwargs={"pk": self.pk}) class Project(models.Model): project_name = models.CharField(max_length=50) about = models.TextField(null=False) website = models.CharField(max_length=100, null=True, blank=True) github = models.CharField(max_length=100, null=True, blank=True) thumbnail … -
How to skip dummy model from django test
I have created one django admin page which is associated with a dummy model which doesn't exists. Here is the code. The statistic model doesn't exists in database. class StatisticModel(models.Model): class Meta: verbose_name_plural = 'Statistic' class StatisticModelAdmin(admin.ModelAdmin): model = StatisticModel def get_urls(self): view_name = 'changelist' return [ path('settings/', my_custom_view, name=view_name), ] admin.site.register(StatisticModel, StatisticModelAdmin) In my git workflow I have below command, python backend/django/manage.py test ./backend/django Which is failing with error, django.db.utils.ProgrammingError: relation "monitor_statisticmodel" does not exist Please advise how can I avoid or skip this error? -
how do I rewrite the following in order to make it work with model manager?
I'm scraping some sites and loading the results into a Postgres in a management command that I will later convert to a celery task. how can I convert my pseudo function In order to create_or_update_if_diff which means it will only update if detect changes def create_or_update_if_diff(self, model, defaults=None, **lookup): """Helper function which is similar to update_or_create(), but will compare defaults to database entry and only update when there is any difference""" defaults = defaults or {} instance, created = model.objects.get_or_create(**lookup, defaults=defaults) if created: self.log_database_create(instance) return instance else: for key, value in defaults.items(): attr = getattr(instance, key) if attr != value: # If any change detected just update without checking other entries. model.objects.filter(**lookup).update(**defaults) self.log_database_update(instance) instance.refresh_from_db() return instance return instance ``` -
how to build a orm query where says if the model doesnt exist (object) add , but if exist then change the modified fields?
I am new with django framework , and I would like to know how to build the following query where I can perform insert operation when the object doesn't exist, but update modified fields if there is an object with the following id from demo.models import Person update_values = {"name": "Alice", "age": 12, "is_manager":False} new_values = {"name": "Bob", "age": 25, "is_manager":True} obj, created = Person.objects.update_or_create(identifier='id', defaults=update_values) if created: print(f"created {obj}") else: print(f"updated {obj}") note: I want to do it with a single method update_or_create than using two get_or_create + update_or_create -
how to send random get request to the API endpoint using request and time modules in python
how to send random get request to the API endpoint using request and time modules in python -
Heroku local server (django) only prints to console when I press Ctrl+C and quit the server for some reason?
So I downloaded the hello world/getting started django heroku project. It's been working fine, but I decided to experiment with webhooks. So I have this: def webhooks(request): print("here") return HttpResponse('Hello, world. This is the webhook response.') And what happens is when the webhook is visited I can see that it's getting a response and it's going through (by looking at ngrok, if that matters). But it doesn't print out "here". Once I press ctrl+c on my machine (mac) to shut down the local running of heroku, for some reason THEN it prints out "here". Even if I visit the webhook 5 times, it won't print anything until I press ctrl+c and start shutting down. Then, and only then, it prints out "here" 5 times. Then it says exited successfully have to press ctrl+c again to fully quit not sure why. Here's what it prints below but I'm not sure if it helps. vv +0000] [17890] [INFO] Worker exiting (pid: 17890) 1:10:21 PM web.1 | here 1:10:21 PM web.1 | here 1:10:21 PM web.1 | here 1:10:21 PM web.1 | [2021-06-19 13:10:21 -0400] [17888] [INFO] Shutting down: Master 1:10:21 PM web.1 Exited Successfully -
User logged in using LDAP doesn't get logged out even after logging out using the default logout feature provided by django
The application is Django 2.2 based and allows users to login via Apache using Active Directory and LDAP. User is able to log in via the browser pop-up/modal (image shown below). Issue is when the user logs out, the user is actually still logged in and can access the application. The application uses the default logout functionality from django.contrib.auth. I'm working on creating a custom logout function that would delete the session data for currently logged in user. I have come out with the following, from django.contrib.sessions.models import Session from django.contrib.auth.models import User def logout_user(request): username = request.user.username logged_in_user = User.objects.get(username=username) for session in Session.objects.all(): session_data = session.get_decoded() if session_data.get('_auth_user_id') == logged_in_user.id: session.delete() I'm not sure if I'm going in the right direction or is there a better solution to this. Thanks for any help you can offer! -
How to set bounds to django leaflet map?
In my django app I have a CenterModel with a location (Point) field and a RouteModel with a geom (Linestring) field. I am using django-leaflet to represent those geometric fields in the views (UI). I can represent those fields, but in the general settings I had set the default center and zoom for every leaflet map, so when i represent the center or the route I have to zoom out amd move the map to see the marker and the line, Is there any way to set the bounding box of the map to see the point or the line without having to zoom out and move the map? The point is represented outside this area and I have to zoom out I have try with: map.setBounds(datasets.getBounds()); but it shows the error that the setBounds method does not exist Here is my code: This is how I represent the route: In the template: <div class="row"> {% leaflet_map "gis" callback="window.our_layers" %} </div> <script type="text/javascript"> function our_layers(map,options){ var datasets= new L.GeoJSON.AJAX("{% url 'riesgo:route_locate' route.id %}" ,{}); datasets.addTo(map); // this is showing an error map.setBounds(datasets.getBounds()); } </script> #the ajax views @login_required(login_url='/login/') def route_get_location(request,pk): route=serialize('geojson',RouteModel.objects.filter(id=pk)) return HttpResponse(route,content_type='json') representing the center in other template <div …