Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gradually add react elements to a Django project using Create React App and yarn build
I have a project using Django as backend and raw HTML, CSS and JS. I have tons of templates and I want to start migrating some parts of the frontend website to React. I started creating one single landing page in react using the official tutorial and until here everything went well, just a bit tedious having to build and manually move static js and css created to django templates: yarn build go to django static folder and replace minified js and css files by the new ones go to django templates (html) and replace new reference to new files But then I wanted to create a new independent component not related to the landingpage I created and i culdn't find the best approach to do it without duplicating react create app folder. The goal is to do yarn build and have one single js and css file per independent element. For example, if I have: index.js Element1.js Element2.js ... After doing yarn build, I have: build/ static/ css/ elem1.54aa3f3f.css elem2.jsby6syb.css js/ elem1.54aa3f3f.js elem2.jsby6syb.js The colser I've been to this, is having in my index.js file one render per independent element, but then it creates only one single js and … -
ImproperlyConfigured: Application labels aren't unique, duplicates: web
settings.py INSTALLED_APPS = [ 'rest_framework', 'web', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'realstate', 'Subscriptions', 'services', 'vendor', 'products', apps.py from django.apps import AppConfig class WebConfig(AppConfig): name = 'web' -
Can't move 'logout' button to the right
After several hours of research and variout attempts, I cannot seem to workout how to move this Logout button from within my Navbar to the very right of the screen. I have tried every example I can find online, creating a new nav bar, setting the float to right, text align to the right, etc. Please find the attached HTML/Django: navbar.html: <nav class="navbar navbar-expand-lg navbar-light bg-light p-0"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav" style="height: 4rem;"> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'signed in' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'add meal' %}">Add Meal</a> </li> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'view private profile' %}">View Private Profile</a> </li> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'view food log' %}">Food Log</a> </li> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'view friends' %}">Friends</a> </li> <li class="nav-item"> <a class="nav-link p-3" href="{% url 'settings' %}">Settings</a> </li> <li class="nav-item" style="float: right"> <a class="nav-link p-3" href="{% url 'logout' %}" style="background-color: #e85c29">Logout</a> </li> </ul> </div> </nav> Thank you for your time. -
Django with Pandas, access pandas df in a view with large set of data
I have a Pandas dataframe made of a large set of data, around 80mo. I would like that when kwargs are sent to a certain view, these ones were inserted in a Pandas function that then would be applied on this dataframe "living" in this view, problem is that I have to import the data in the view each time which is of course too long (download the file + pd.read + function itself) and would probably be costly in the long run since the clients would be downloading it from an S3 bucket each time. I tried to mitigate this using a Lambda function in AWS, it gives a good result after an initial download because I can cache the file but the problem is the cold start and also the fact that said AWS Lambda cache is quite short lived so I am back to Django and searching a new solution. I was thinking about maybe caching the already read dataframe but it seems a bit strange considering the size. Any ideas on what would be the best way to do this? Thanks a lot to you all -
Can anyone suggest best shared web hsoting for django in India?
I am building a basic site that requires minimum requirements So can anyone suggest the best shared hosting in India -
For loop in template django with prefetch_related
I got an issue when trying to access values from other models by using prefetch_related My model: class testimport(models.Model): id=models.AutoField(primary_key=True) so_hd=models.CharField( max_length=50, unique=True) ten_kh=models.CharField( max_length=500) tien_dong=models.IntegerField(blank=True, null=True) created_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() def get_absolute_url(self): return "/chi_tiet_hop_dong/%s/" % self.so_hd class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.DO_NOTHING, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.DO_NOTHING, null=True, blank= True, to_field="admin_id") noi_dung=models.TextField() My views: .... get_contract_detail=testimport.objects.filter(so_hd__in=get_user).order_by("id").prefetch_related().values() contract=get_contract_detail.filter(so_hd=so_hd).all() return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev, "so_hd":so_hd,"form":form,"form1":form1}) If I try to print out the content by values, it is ok: print(get_contract_detail.filter(so_hd=so_hd).values("so_hd","report__noi_dung")) In my template: {% for report in contract %} {% for content in report.so_hd.all%} <tr> <td>{{ forloop.counter }}</td> <td>{{content.noi_dung}}</td> </tr> {% endfor %} {% endfor %} There is no content in cells. How can I show the content Please help -
Django Display post time in user's timezone
I am new to Django. I have a model with a field that records the time a new entry is made and I want to display the times new entries are posted in the user's timezone. The time is recorded in UTC. So far I haven't been able to get this to work. I suspect I need to pass something additional info via the view but I haven't been able to figure this out. settings.py: TIME_ZONE = 'UTC' USE_TZ = True model: from django.db import models from accounts.models import CustomUser from tinymce import models as tinymce_models class CompanyAnnouncement(models.Model): title = models.CharField(max_length= 200) author = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) body = tinymce_models.HTMLField() date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title view: from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, FormMixin from django.urls.base import reverse from .models import CompanyAnnouncement from django.utils import timezone class CompanyAnnouncementList(ListView): model = CompanyAnnouncement template_name = 'company_accounts/announcements.html' ordering = ['-date'] template: {% extends 'base.html' %} {% load tz %} {% block content %} <div class="section-container container"> {% for post in object_list %} <div class ="announcements-entry"> <h2><a href=" ">{{ post.title }}</a></h2> <h3>made on {{ post.date }}</h3> {% localtime on %} {{ post.date }} {% endlocaltime %} <p>{{ post.body | … -
How to delete a specific item in django jsonfield
here is my model: class Log(models.Model): user = models.OneToOneField(UserProfile, verbose_name='user', on_delete=models.CASCADE) log = models.JSONField(verbose_name='log', default=list, null=True, blank=True) def __str__(self): return self.user.username the data(log.log) like this: [ {"date": "2021-1-1", "volume": 123}, {"date": "2021-2-1", "volume": 456}, // if post date is 2021-2-1, i want delete this {"date": "2021-3-1", "volume": 789} ] this this delete view: def delete(self, request, *args, **kwargs): date = request.data.get('date', None) if not date: return Response(status=status.HTTP_400_BAD_REQUEST) user = request.user log = Log.objects.filter(user=user).first() if not log: return Response(status=status.HTTP_404_NOT_FOUND) # delete data based on date # data = json.dumps(log.log) ... return Response(status=status.HTTP_200_OK) I'm not good at json, tried a few ways but failed. Very grateful for any answer -
How To Validate Captcha Form In Django
how to validate a captcha form in django? forms.py: from django import forms from captcha import fields class Cap(forms.Form): cap=fields.CaptchaField() template renderer function in views : def cap(request:HttpRequest): return render(request,"cap.html",{"form":Cap}) template : <form action="" method="post"> {% csrf_token %} {{form.cap}} <button type="submit">Submit!</button> </form> where to use form.is_valid() function in views? -
I am working on this Django project But stuck in this error
When running the application I get this error message. I have uploaded the code and error message screenshot below. [error message][1] -
Hiring Django expert with good frontend skills for an MVP App
We are looking for an experienced Full Stack Developer to help us build our MVP application from scratch. We are expecting this MVP not only to align with the requirements but also to be built cleanly and properly documented so it can be handed over to our future in-house developers. You will be working with the in-house Technical Lead, who will guide and support you in understanding our user needs and the application goals. Who are you? You are an experienced Full Stack developer, with solid experience in Django and you have a solid grip on Front End development (mix of static sites with dynamic functionalities). Required experience: Experience implementing a mix of relational and non-relational data models in PostgreSQL Python development and Django UI, UX, interactivity design experience a huge plus Experience in making architectural recommendations Ability to communicate clearly Dedication to meet project deadlines in a timely manner Willingness to sign an NDA What do we want to build: Our MVP is a Django application interacting with a PostgreSQL database as well as a simple Django-Admin interface. We are aiming at it to be simple but have the potential to grow. We have some simple sketches on how … -
Django Filtering A For Loop with 2 Parameters
I've built a notification system that allows a user to sign up for custom notifications (Notification) that fire based on their chosen parameter and threshold value from another model (Report). My models.py looks like this: class Report(models.Model): field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() ... class Notification(models.Model): threshold_field = models.CharField() # would store field1, field2, field3, etc from Report threshold_value = models.FloatField() # the value corresponding to threshold_field that would trigger the notification I'm trying to write a database query that would get all Notification that meet the criteria for triggering a notification given a Report or Report queryset. However, I can't figure out how to pair all possible threshold_field and threshold_value within the query. The ugliest possible solution that would work would be something like this: report = Report.objects.first() # get the report to query all_fields = Report._meta.get_fields() # all field choices from Report all_querysets = [] for field in all_fields: # loop through all fields, i.e. field1, field2, field3 qs = Notification.objects.filter( threshold_field=field, threshold_value__gte=getattr(report, field) # get the value stored in the field ) all_querysets.append(qs) This is ugly, but this isn't a horrible solution given that there are only ~20 fields in my production Report. However, … -
django one to one cannot get related name
I cannot fetch the record from one to one related object. class Question(models.Model): author = models.ForeignKey(User, related_name='questions', default=deletedUserId, on_delete=models.SET_DEFAULT) createTime = models.DateTimeField(default=now, editable=False) title = models.CharField(max_length=100) content = models.TextField(default='') class Edit(models.Model): to = models.OneToOneField(Question, blank=1, null=1, on_delete=models.SET_NULL, related_name='edit') author = models.ForeignKey(User, related_name='questionRawEdits', on_delete=models.CASCADE) createTime = models.DateTimeField(default=now, editable=False) title = models.CharField(max_length=100) content = models.TextField() from questions.models import Question question = Question.objects.all()[0] print(question.edit) # questions.models.RelatedObjectDoesNotExist: Question has no edit. I expect it to returns None instead of rasing an error, just like other fields such as ManyToMany, ForeignKey, etc, I wonder why only OneToOne would raise an error. thanks for your help. -
"details": "not found" in django rest json response
I'm a newbie in Django Rest Framework. I am building an E-commerce API using postgresql as database for science fair project. I am getting "detail": "not found" as json response whenever I want to check the list of orders for a particular user. I have given the blocks of code below: In views.py class OrderListAPIView(generics.RetrieveUpdateDestroyAPIView): serializer_class = OrderListSerializer permission_classes = [IsAuthenticated] lookup_fields = ['customer'] lookup_url_kwarg = 'customer' def get_queryset(self): a = Orders.objects.filter(customer=self.kwargs['customer']) return a In serializers.py class OrderListSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = Orders fields = "__all__" In urls.py from django.urls import path from .views import OrderListAPIView urlpatterns = [ path('orders/list/<customer>/', OrderListAPIView.as_view(), name='order-list') ] Response getting from the above code { "detail": "not found" } Expected Response [ { "ord_id": "ffa19b9b-650b-4c49-89bd-eb72f7b3c3b4", "product": "57cbd4a2-1c79-47a6-bf95-74ee3402e703", "ord_quantity": 10, "ord_price": 118.0, "ord_date": "2022-03-13T13:40:22.212586Z", "ord_status": "Pending", "customer": "08eba6ca-3f7c-4054-8184-d8ac341579e9" } ] Is there anything which is wrong in these lines of code or anything which I forgot to implement or missed something? Thanks for the help in advance! -
get subclasses of Django non-Model based class
I have following abstract model in Django project, which I don`t want to have as db tables: class Base(object): class Meta: abstract = True and one subclass: class Sub(Base): I trying to get Sub from Base by answeer from this question: How to find all the subclasses of a class given its name? Base.__subclasses__() But, I get only empty list. Why? -
How to get the name of IntegerChoices
I have these models.InterChoices class LogType(models.IntegerChoices): SYSTEM_OK = 1 SYSTEM_REPLY = 2 SYSTEM_ERROR = 5 I can get choices for select box such as LogType.choices() Now, I want to get the name For example, I want to do this LogType.get_by_id(1) return SYSTEM_OK or System Ok is it possible?? -
HTML: File extension "sr" is not allowed
I am using Django version 4. (I don't think the problem is in django). I am using HTML with bootstrap library. I am working on Image Processing Tool, in which I have a FORM through which user can upload an image file. I am getting this output in my Chrome Browser when I choose a .sr file. The text in RED is: File extension “sr” is not allowed. Allowed extensions are: bmp, dib, gif, tif, tiff, jfif, jpe, jpg, jpeg, pbm, pgm, ppm, pnm, png, apng, blp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, ftc, ftu, gbr, grib, h5, hdf, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, psd, bw, rgb, rgba, sgi, ras, tga, icb, vda, vst, webp, wmf, emf, xbm, xpm. My HTML is this... <form method="POST" onsubmit="return validate()" enctype="multipart/form-data"> <legend><u>{{ src|upper }} to {{ dst|upper }}</u></legend> <div class="mb-3">{% csrf_token %} {{ form|crispy }}</div> <button class="btn btn-sm p-2 btn-dark btn-outline-light border border-1 border-dark" type="SUBMIT">Convert Now</button> </form> The method used in form submit event is returning TRUE always. No validation for now. But I have one more javascript code snippet as below. window.onload = () … -
OperationalError at /admin/accounts/user/ | Django error 500
Whenever I click in admin panel user url /admin/accounts/user/ it shows OperationalError and it shows error in templates/admin/base.html, error at line 44. Error line is: <a href="{{ site_url }}">{% translate 'View site' %}</a> {{ site_url }} is red marked. But rest of the parts of admin panel is running fine. -
Publishing Two Sites with Django/Docker/Nginx Reverse Proxy?
How can I publish two different Django projects with two domains to one host using Docker in my DigitalOcean Droplet? Should I set Nginx in the docker-compose.yml file, or should I set it on the host system (etc/nginx/…)? Or should I run nginx in a separate container? When I search on the internet, people who publish django projects with docker usually write their nginx settings in the docker-compase.yml file, but I couldn't understand how to set the reverse proxy in this way to publish two different sites. Nginx settings - Dockerfile, docker-compose.yml would be very appreciated if you give information about settings. Thanks in advance. I'm sorry for my bad English :( :( docker-compose.yml version: '3' services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media networks: - nginx_network - database1_network depends_on: - database1 nginx: image: nginx ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media depends_on: - djangoapp networks: - nginx_network database1: image: postgres env_file: - config/db/database1_env networks: - database1_network volumes: - database1_volume:/var/lib/postgresql/data networks: nginx_network: driver: bridge database1_network: driver: bridge volumes: database1_volume: static_volume: media_volume: Nginx - local.conf upstream hello_server { server djangoapp:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://hello_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
When queryset returned more than one, how choice specific object?
I try get attribute value item from specific object with queryset below: x_img = ProductImages.objects.get(product_id=x_id), with that, return more than one, if i use filter, x_img = ProductImages.objects.filter(product_id=x_id), the attribute i need(image_file_w200_png) is unvailable. The context: I want to create a dynamic values in my head, to do that my choice is custom context_processors, so: head_meta_processors.py import os from .models import Product, ProductImages def meta(request): path_id = os.path.basename(os.path.normpath(request.path)) x_id = path_id x_obj = Product.objects.get(pk=x_id) #... # here is the problem x_img = ProductImages.objects.get(product_id=x_id) x_meta_itemprop_image = x_img.image_file_w200_png.url return { #... 'meta_itemprop_image': x_meta_itemprop_image, #...} models.py class Product(models.Model): #... some fields class ProductImages(models.Model): #... Fk to model above product = models.ForeignKey(Product, on_delete=models.CASCADE) product_id = ... image_type = models.CharField(max_length=33,default='normal') image_file_w200_png = models.ImageField( upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='default_image_thumbnail.png' ) Each Product model, can have many ProductImages related by product_id field. So, my queryset, ProductImages.objects.get(product_id=x_id), return 3 objects related with that product_id, how can access each one and how choice a specifc, like a index, e.g.:x_img[0]? -
request <WSGIRequest: GET '/create'>
Я пытаюсь сделать страницу для создания таска, но я не могу запустить страницу (ошибка: form = TaskForm()) from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.order_by('-id') return render(request, 'main/index.html', {'title': 'Главная страница сайта', 'tasks': tasks}) def about(request): return render(request, 'main/about.html') def create(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid: form.save() return redirect('home') form = TaskForm() context = { 'form': form } return render(request, 'main/create.html', context) Я могу получить эту форму, но когда я публикую, я получаю: request <WSGIRequest: GET '/create'> -
Remove AUTH user from right sidebar in DJANGO JAZZMIN admin panel
enter image description here Hello there! I want to remove Auth user from left side bar as show in picture above. Is it possible? -
I am new in django having problem to migrate my database
My Error: Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Python39\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "telusko" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Md. Tarek Aziz\Desktop\django\telusko\manage.py", line 21, in <module> main() File "C:\Users\Md. Tarek Aziz\Desktop\django\telusko\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python39\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 29, in execute return super().execute(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 37, in handle loader = MigrationLoader(connection, replace_migrations=False) File "C:\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Python39\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, … -
401 Error in React and django-rest-framework app
First of all I got this useState which takes data from input: const Checkout = ({cart, totalPrice, code}) => { const [values, setValues] = useState({ email: '', city:'', adress:'', postalCode:'', phone:'', firstName:'', lastName:'', message:'', price: totalPrice, code: code, shipmentFee:0, shipmentMethod:'', lockerId:'', cart:cart, }); Then I submit it with generateOrder(values) function: export const generateOrder = (order) => { return fetch(`${url}/orders/generate-bank-transfer-order/`,{ method:"POST", body:order }) .then((response) => { return response.json(); }) .catch((error) => console.log(error)) }; It points to this url in urls.py: path('generate-bank-transfer-order/',generate_bank_transfer_order, name="generate-bank-transfer") And this is a view I use, for now I just want it to return submited data so I can test if it works: @csrf_exempt def generate_bank_transfer_order(request): if request.method == "POST": body = request.body return JsonResponse({"test":body}) All I get is 401 Unauthorized and I have no idea how to fix it. Any ideas? -
Counting sum of values, based on unique values
I am not sure if the title is clear enough, so I'll do my best to explain what I want and what the problem is. What I have I have a graph that get's filled with data from a query. Every day of the month has a value that is grouped by day, for example: day 1 = 5, day 2 = 6, day 3 = 8 etc. This works with the following code, for 1 subscription: data_usage = DataUsage.objects \ .filter(subscription_id=subscription_id) \ .filter(created_at__month=today.month) \ .annotate( created_date=TruncDay('created_at') ).values('created_date') \ .annotate( subscription_id=Max('subscription_id'), data_usage=Max('data_usage'), created_at=Max('created_at') ).values( 'subscription_id', 'data_usage', 'created_at' ) The image below is a correctly filled graph with the code above: What I need I need this same graph but this time with the values from every subscription. So basically the code has to give me the same output, but with the sum of 'data_usage' of all subscriptions for that day. Only the highest and thus latest value for every subscription should be used. I have tried 10's of solutions that did not work for me, the current code does not work: data_usage = DataUsage.objects \ .filter(created_at__month=today.month) \ .annotate( created_date=TruncDay('created_at') ).values('created_date') \ .annotate( subscription_id=Max('subscription_id'), data_usage=Sum('data_usage'), created_at=Max('created_at') ).values( 'data_usage', 'created_at' ) What's …