Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Moving tables data from sqlite3 to postgressql
What is the simplest way to move data from sqlite3 tables to posgressql in Django project -
Print web application pages in pdf django
I am new in this field and currently learning Django and have pseudo project... I want to print in pdf my app pages which are represented as a group of tabs (5 tabs in total) with its own views/urls. Tab 2, 3, 4, 5 contents are related models of tab 1. I have looked to several tutorials about ReportLab also doing print() button set-up directly from browser side and I am able to print my 1st tab content successfully. I am wondering if there is any example to combine printing all related model tabs i.e. 2, 3, 4, 5 when I am printing 1st tab content? Similar like placing button on listview to print all data together from there? thanks in advance. -
Django - display an error message when form is invalid with "CreateView"
Here is my simplified "ProjectCreate" ClassBasedView : class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['name', 'creation_date', 'price'] class ProjectCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Project form_class = ProjectForm success_message = "Project successfully created" success_url = "project-list" def get_form(self, form_class=None): form = super(ProjectCreate, self).get_form(form_class) form.fields.pop('creation_date') return form def form_valid(self, form): if form.instance.name == "not_valid_name": return super().form_invalid(form) form.instance.last_editor = self.request.user form.instance.last_modification_date = datetime.datetime.now() return super().form_valid(form) I want to create the project only if the name isn't "not_valid_name" If the name is "not_valid_name", i want to display an error message (saying that the name isn't valid), and bring back the user to the 'project create' page If you need any additional informations to understand my problem, don't hesitate to ask me. Thanks :) -
error: dictionary changed size during iteration
I am trying to convert a model instance to a dictionary with the function "model_to_dict" from django.forms.models but im getting the error: dictionary changed size during iteration. obj_list = [] object_qs = Model.objects.all() for obj in object_qs: obj_list.append(model_to_dict(obj)) I don’t understand what’s happening and how do i achieve the desired result? -
django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")
I don't understand what kind of error is ? sometimes this code works and after 1-2 times submitting form then trying to submit form again with different details then i got this error, django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'") Here this is my views.py code @api_view(['POST', 'GET']) def add_info_view(request): if request.method == 'POST': form = GitInfoForm(request.POST) if form.is_valid(): form.save() try: git_Id = form.cleaned_data['git_Id'] s = Gitinformation.objects.filter(git_Id=git_Id).values('request_id') print('Value of S :', s[0]['request_id']) s = s[0]['request_id'] approve_url = f"http://127.0.0.1:8000/Approve/?request_id={str(s)}" print("Url : ", approve_url) try: send_mail( 'KSA Test Activation', approve_url, 'Noreplygcontrol@airlinq.com', ['sorav.parmar@airlinq.com'], fail_silently=False, ) request.session['approve_url'] = approve_url print('Approve Url sent : ', approve_url) except Exception as e: pass except Exception as e: pass form = GitInfoForm() form = GitInfoForm() return render(request, 'requestApp/addInfo.html', {'form': form}) How to getrid of this error, please help me. -
How to renderer reacj jsx file in django render without using api
I want to find a way to render react jsx instead of rendered plain html without using api or using indirect html method in django -
What fieldtype of Django model should I choose to store encrypted data?
I am working on a project the requirement is to store some encrypted data in the database. What is the preferred fieldtype of Django model for storing encrypted data? I am currently using CharField, however, I am not sure if this is the best approach. Also, should BinaryField be an option? -
Get product color in color filter by Category wise
I am trying to get a specific category products by category slug.I have Color model,Product model and product variation model in shop app. class Colour(models.Model): title = models.CharField(max_length=100) color_code = models.CharField(max_length=50,null=True) class Product(models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) content = RichTextUploadingField() price = models.IntegerField() images = models.ImageField(upload_to='photos/products') is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="procat") created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_featured = models.BooleanField() class ProductVaraiant(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) color = models.ForeignKey(Colour,on_delete=models.CASCADE,blank=True, null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True, null=True) brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True, null=True) amount_in_stock = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['product', 'color', 'size','brand'], name='unique_prod_color_size_combo' In my views.py, def shop(request,category_slug=None): categories = None products = None if category_slug != None: categories = get_object_or_404(Category,slug = category_slug) products = Product.objects.filter(category=categories,is_available=True).order_by('id') variation = ProductVaraiant.objects.filter(product__category = categories) print(variation) # color = color.objects.all() products_count = products.count() else: products = Product.objects.all().filter(is_available=True).order_by('id') products_count = products.count() variation = ProductVaraiant.objects.all() print(variation) context = { 'products' : products, 'products_count' : products_count, 'variation' : variation } return render(request,'shop/shop.html',context) my category model, class Category(MPTTModel): parent = TreeForeignKey('self',blank=True,null=True,related_name='children',on_delete=models.CASCADE) category_name = models.CharField(max_length=200,unique=True) category_img = models.ImageField(upload_to='photos/categories',blank=True) slug = models.SlugField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def img_preview(self): return mark_safe('<img src = "{url}" width = "50" height = "50"/>'.format( url = self.category_img.url )) def __str__(self): return … -
The scheduler seems to be running under uWSGI, but threads have disabled.You must run uWSGI with the --enable-threads option for the scheduler to work
I'm deploying django app to pythonanywhere where i used APScheduler for automatically send expire mail whenever subscription end date exceed. I don't know how to enable threads, so that my web app runs perfectly on pythonanywhere. -
Comparing Django project structure to ruby on rails
After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general. For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controllers folder which contains controller classes, again each in a separate ruby file. However, in Django it split the project into independent apps, which can be installed independently in other Django project, each app has a models.py file which contains all the models classes, a views.py file which contain all the views functions. But then how to group functions in views like rails? That is one controller per each model. In general how to structure my project when it contains one large app that can't be separated into multiple independent apps? I want for example to have a view index function for each model, but how to do this if all functions are in one file? If my project is about selling cars for example. I should have index function that maps to /cars, another index function to map to /users, etc... I searched … -
Import models from different apps to admin Django
I'm trying to create an admin page for my project including app1 and app2 myproject settings.py urls.py admin.py app1 app2 In myproject/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] In myproject/admin.py from django.contrib import admin from app1.models import User from app2.models import Manager, Employee, Task, Template admin.site.register(User) admin.site.register(Manager) admin.site.register(Employee) admin.site.register(Task) admin.site.register(Template) Why doesn't my admin page import any models at all? Thanks! -
Cache Auto Generated Django Admin Routes
I want to cache the sql queries result in Redis DB in the django admin.AdminSite autogenerated for registered admin.ModelAdmin's I am able to cache a custom url using cache_page and add it to CustomAdminSite I have installed Django debug toolbar to view cache requests. The custom url is getting cached. I am unable to cache other auto generated admin routes. Would it be possible to cache auto generated admin routes too? -
convert python/django built-in class "calendar" to local calendar (Persian)
I created a html calendar using built-in calendar class in Django , now I have to convert it to local calendar "Persian", I tried using django-jalali-date package but couldn't get success result . and another issue is prevmonth and next month buttons which redirect user to not found page. please advice how to handle those issues in utils.py: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(time_start__day=day) d = '' for event in events_per_day: d += f'<li> {event.title} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = tb_order.objects.filter(time_start__year=self.year, time_start__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal in Urls: path('testcal/',views.CalendarView.as_view(),name="cal"), in views.py : class CalendarView(generic.ListView): model = tb_order template_name … -
Why parentheses are not used with function in html template when model method is called in django?
I would like to know while in html templating process why model method does not use parentheses like normally we use it in views and it is being called direcly like varible e.g. class Main(models.Model): value=models.BigIntegerField(null=True, blank=True) #Model field variable = 505 # model variable def fun(self): return True # model function (method) The html template {% extends 'base.html' %} {% block content %} {{user.main.value}} it's value <br> {{user.main.fun}} it's function (why no parentheses here like user.main.fun()) <br> {{user.main.variable}} it's variable <br> {% endblock %} If this question is not good then tell me to delete but please do not down vote.Thank You. -
Docker socket is not accesible in Docker.prod
I have the following docker-compose file which builds and starts 4 containers one of them is Django container for which I am mounting the /var/run/docker.sock in volumes so that Django container can access the host docker engine. version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles - /var/run/docker.sock:/var/run/docker.sock expose: - 8000 env_file: - ./.env.prod depends_on: - postgresdb restart: always postgresdb: container_name: postgresdb image: timescale/timescaledb:latest-pg11 volumes: - ./:/imports - postgres_data:/var/lib/postgresql/data/ command: 'postgres -cshared_preload_libraries=timescaledb' ports: - "5432:5432" env_file: - ./.env.prod.db restart: always nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 80:80 depends_on: - web restart: always volttron1: container_name: volttron1 hostname: volttron1 build: context: ./volttron dockerfile: Dockerfile image: volttron/volttron:develop volumes: - ./volttron/platform_config.yml:/platform_config.yml - ./volttron/configs:/home/volttron/configs - ./volttron/volttronThingCerts:/home/volttron/volttronThingCerts environment: - CONFIG=/home/volttron/configs - LOCAL_USER_ID=1000 network_mode: host restart: always mem_limit: 700m cpus: 1.5 volumes: postgres_data: static_volume: media_volume: The content of the Docker.prod for django web container is following ########### # BUILDER # ########### # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk add … -
Django LocMemCache not caching data
I've got my LocMemCache set up in my settings.py: 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': None, }, I have then built a function decorator: from django.core.cache import cache def cache_function(func): def cache_result(*args, **kwargs): cache_key = '{},{}'.format( func.__name__, hashlib.sha256('{},{},{}'.format(func.__name__, args, kwargs).encode()).hexdigest(), ) try: result = cache.get(cache_key) if result is not None: print('function is cached') return result result = func(*args, **kwargs) timeout = 60 cache.set(cache_key, result, timeout) return result except Exception as exc: print('CACHE ERROR:') print(exc) return func(*args, **kwargs) return cache_result Then I've got my function: @cache_function def function_to_test(): return 'this is a test value' However, it seems like the cache is never used, no matter how many times I call the function. I know this because my print statement ('function is cached') is never printed. I even put a debugger there to see what happens, and it just seems like the cache is empty What am I doing wrong? -
Saleor admin dashborad Having trouble due to cors error?
Graphql API is working fine with the storefront but is not able to work with the admin dashboard on how to disable the cors policy for a certain domain. I am using the docker configuration for that. // api docker congig environment: - JAEGER_AGENT_HOST=jaeger - STOREFRONT_URL=https://react-storefront.dingpack.com/ - DASHBOARD_URL=https://admin.dingpack.com/ - ALLOWED_HOSTS=api.dingpack.com,localhost,api,140.238.230.137,admin.dingpack.com,react-app-checkout.dingpack.com,react-app-checkout.dingpack.com - ALLOWED_CLIENT_HOSTS=admin.dingpack.com,react-storefront.dingpack.com,react-app-checkout.dingpack.com,api.dingpack.com,localhost - ALLOWED_GRAPHQL_ORIGINS=admin.dingpack.com,react-storefront.dingpack.com,react-app-checkout.dingpack.com,api.dingpack.com,localhost // nginx conf are location / { add_header 'Access-Control-Allow-Origin' '*' always; proxy_pass http://localhost:8000/; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; include /home/ashish/Downloads/projects/saleor/core-api/uwsgi_params; include /etc/nginx/snippets/cors.conf; include /etc/nginx/snippets/cors-wildcard.conf; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { access_log off; log_not_found off; } location ~ /\. { deny all; access_log off; log_not_found off; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.dingpack.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.dingpack.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = api.dingpack.com) { return 301 https://$host$request_uri; } # managed by Certbot response from admin api query [ failed ] response from store-frontend [ pass ] i am expecting that api cors error will not occur for admin dashboard as well. -
How do we solve the quotation inside of a quotation problem while using django?
I can't use the same type of string in the same type of string in HTML I have a static folder in the root dierctory of my django project and I was changing a downloaded template's link to match the django project. Here is the HTML attribute style="background-image: url(\"{% static 'assets/img/why-us.png' %}\")" as you can see I tried using backslash () to resolve the problem but it was no avail. -
Using inline formsets with manytomany relationship
I have AbstractUser and Relationship models. The user model has a manytomany field through relationship model class User(AbstractUser): username = models.CharField( verbose_name="username", max_length=256, unique=True) first_name = models.CharField(verbose_name="first name", max_length=30) last_name = models.CharField(verbose_name="last name", max_length=30) slug = models.SlugField(max_length=255, unique=True, blank=True) date_joined = models.DateTimeField( verbose_name="joined date", auto_now_add=True) friends = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='following') is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) def __str__(self): return str(self.username) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) super().save(*args, **kwargs) class Relationship(models.Model): from_person = models.ForeignKey( User, related_name='from_people', on_delete=models.CASCADE) to_person = models.ForeignKey( User, related_name='to_people', on_delete=models.CASCADE) def __str__(self): return f"from {self.from_person} to {self.to_person}" How to create an inline formset with fields=['from_person' and 'to_person'] to assign users to each others That is what I tried to do but I couldn't have both fields because of fk_name Any help please! def staff_profile_view(request): user = User.objects.get_by_natural_key(request.user) AssignFriendsFormSet = inlineformset_factory( User, Relationship, fk_name='from_person', fields=('to_person', 'from_person',)) formset = AssignFriendsFormSet( queryset=Relationship.objects.none(), instance=user) if request.method == "POST": formset = AssignFriendsFormSet(request.POST, instance=user) if formset.is_valid(): formset.save() return render(request, 'staff_profile.html',{"formset": formset}) -
Filter data in django admin inline create view
this is my first post here and im hoping to find a solution for my situation: The thing is... I got a admin inline who show the relate info of a model. by this, i can see which contract_product belongs to current client. When im creating a new object in the inline, aka click in the following button enter image description here I cant see a list of option as follow: enter image description here The problem is... the client must see only their products, but here i see all products for all type of clients? PS: product and client has a direct relationship. Hope someone can understand my problem and helps me! Theres a kt if thing i've tried far now, but nothing succesful to talk about -
Django how to perform a query to get all occourences where object 1 has a foreign key on object 2 and a certain object 2 has a property
Okay, so I've got a question about performing queries. So, I've got one object called Job. A Job as a foreign key on StatusUpdate, meaning a single job can have many StatusUpdates. Basically, I need to get all Jobs with a LAST StatusUpdate with a certain property. I know that I can easily get all Jobs that have any StatusUpdate with a certain property like this: Job.objects.all().filter(statusupdate__status="Certain Property") But this will get jobs that have any StatusUpdate with status of certain property. I want to get only jobs with a last StatusUpdate with a status of certain property. Is it possible to do this with a single query? I read the through the Django documentation and couldn't find anything. Thank you! Diego -
How to make a queryset with a value coming from an javascript function?
When the user clicks a checkbox, the value will be sent to a javascript function that will take the value and check if has any occurrence in the database asynchronously, but I don't know if it is possible in Django, I have seen serializers, but I don't think it will work because it's not only catching data from the database, but making a query. There is a way of doing this? requisite = requisite.objects.filter(requisite__discipline__id=33) the code above will retrieve the data I want, but I need to get this number from the code below <input class="form-check-input" type="checkbox" value="{{ discipline.id }}" id="flexCheckDefault{{ discipline.name }}" onclick="checkRequisite(this.defaultValue)"> -
How do I create a view in Django to display only the images with a specific taggit tag?
I have followed this tutorial to create a website. I have expanded my page beyond the tutorial and am now trying to create a view that only uses the images of the tag 'fav'. I am trying to use the tag as a sort of favourite button, and the only display those images in a bootstrap carousel. All I have, to go by, is this different view that only uses the images of the tag you click on. class PhotoTagListView(PhotoListView): template_name = 'photoapp/taglist.html' def get_tag(self): return self.kwargs.get('tag') def get_queryset(self): return self.model.objects.filter(tags__slug=self.get_tag()) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = self.get_tag() return context But since I don't really understand it, it isn't really any help. How do I create a view for a specific tag? Or is there even a solution to this problem entirely feasible in html or js? Tried to modify the other view, but since I don't know enough about django and python it naturally didn't work. My modification: class CarouselView(PhotoListView): template_name = 'photoapp/carousel.html' def get_queryset(self): return self.model.objects.filter(tags__slug='fav') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["tag"] = 'fav' return context -
Django - Overwriting parent model's Meta
I am using the package django-polymorphic-tree inside of a Django application. The PolymorphicMPTTModel abstract model from said package has the following Meta: class PolymorphicMPTTModel(MPTTModel, PolymorphicModel, metaclass=PolymorphicMPTTModelBase): """ The base class for all nodes; a mapping of an URL to content (e.g. a HTML page, text file, blog, etc..) """ # ... fields class Meta: abstract = True ordering = ( "tree_id", "lft", ) base_manager_name = "objects" Here's a model I wrote that inherits from it: class MyNodeModel(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey( "self", blank=True, null=True, related_name="children", on_delete=models.CASCADE, ) # ... fields class Meta: ordering = ( "tree_id", "-lft", ) As you can see, I'm trying to overwrite the parent's Meta.ordering attribute. However, if I do this inside of an instance of MyNodeModel: print(self.Meta.ordering) it prints: ('tree_id', 'lft') which is the parent's value for that field. It appears as though the child class is failing to override that property. Why does this happen? -
Flutter WEB sending file to Django Rest Framework Backend
So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file. I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flutter app you can use fromFile. Now I send that to my backend as bytes. however, my django rest framework view isnt able to save the image to my model. here is the code and step by step: final imagetoSendToAPIasbytes = await cropImageFile.readAsBytes(); List<int> imageaslistint = imagetoSendToAPIasbytes.cast(); final response = await uploadImage(imageaslist, profileid); uploadimage function: var profilepic = await http.MultipartFile.fromBytes( "profilepic", imageaslistint); request.files.add(profilepic); http.StreamedResponse response = await request.send(); var responseByteArray = await response.stream.toBytes(); ofcourse this is not the full code. But I am able to send it to the back end. my django backend view to handle: @api_view(['PATCH', ]) @throttle_classes([updateprofileprofilepicThrottle]) @parser_classes((MultiPartParser, FormParser, JSONParser)) def updateprofileprofilepic(request,): try: user = request.user except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) try: if request.method == "PATCH": profileobjid= json.loads(request.data['profileid']) profileobj = Profile.objects.get(creator = user, id = profileobjid) profileobj.profilepic.delete(False) print(request.FILES['profilepic']) print(json.loads(request.data['profilepic'])) profileobj.profilepic= json.loads(request.data['profilepic']) profileobj.save() usualy (request.FILES['profilepic']) allows me to save a file (from ios/android) however thats when its sending as a mulitipart request.fromPATH. So now (json.loads(request.data['profilepic'])) im …