Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update post with multiple images in django templates
i have two models 1-post 2-postimage so the post can have multiple images so I'm having a trouble to update the post and its images in my templates i did like upload multiple images when i create a post put i dont know how to do it with the update post so can any one show me how to do it or give me a tutorial link Because I searched alot and couldn't find any tutorials this is my models class Post(models.Model, HitCountMixin): ch = [ ('pvp','pvp'), ('Default','Default'), ('bedrock','bedrock') ] xch = [ ('x1','x1'), ('x4','x4'), ('x8','x8'), ('x16','x16'), ('x32','x32'), ('x64','x64'), ('x128','x128'), ('x256','x256'), ('x512','x512'), ] vch = [ ('1.7','1.7'), ('1.8','1.8'), ('1.9','1.9'), ('1.10','1.10'), ('1.11','1.11'), ('1.12','1.12'), ('1.13','1.13'), ('1.14','1.14'), ('1.15','1.15'), ('1.16','1.16'), ('1.17','1.17'), ] author = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() mainimage = models.ImageField(null=True ,upload_to=thumbnail_upload_to) rpfile = models.FileField(null=True, upload_to=file_upload_to) version = models.CharField(max_length=50, null=True) xnumber = models.CharField(max_length=50, choices=xch, null=True) category = models.CharField(max_length=50, choices=ch, null=True) discord_id = models.CharField(max_length=150) date_added = models.DateTimeField(auto_now_add=True) hit_count_generic = GenericRelation( HitCount, object_id_field='pk', related_query_name='hit_count_generic_relation') likes = models.ManyToManyField(User, related_name='blog_posts') private = models.BooleanField(default=False) proved = models.BooleanField(default=False) def total_likes(self): return self.likes.count() def __str__(self): return str(self.title)[:30] def save(self, *args, **kwargs): if self.pk is None: saved_image = self.mainimage self.mainimage = None rpfile = self.rpfile self.rpfile = None super().save(*args, … -
how to sort results by 2 columns, limit prefetch result to one record and sort by prefetch column
I have multiple issues that I couldn't solve by my own. in CaseManager.get_queryset() : I'm trying to add a where clause that the case__id is equal to movement__case__id as: queryset=Movement.objects.filter(case__id=models.F('case__id')).order_by('-date'), but the query becomes as ... WHERE ("cm_movement"."case_id" = ("cm_movement"."case_id") AND ... Full query: SELECT "cm_movement"."id", "cm_movement"."case_id", "cm_movement"."direction", "cm_movement"."date", "cm_movement"."reason_id", "cm_movement"."details", "cm_movement"."created_at", "cm_movement"."updated_at", "cm_case"."id", "cm_case"."police_station_id", "cm_case"."number", "cm_case"."year", "cm_case"."kind", "cm_case"."registered_at", "cm_case"."created_at", "cm_case"."updated_at", "cm_movement_reason"."id", "cm_movement_reason"."direction", "cm_movement_reason"."reason", "cm_movement_reason"."created_at", "cm_movement_reason"."updated_at" FROM "cm_movement" INNER JOIN "cm_case" ON ("cm_movement"."case_id" = "cm_case"."id") INNER JOIN "cm_movement_reason" ON ("cm_movement"."reason_id" = "cm_movement_reason"."id") WHERE ("cm_movement"."case_id" = ("cm_movement"."case_id") AND "cm_movement"."case_id" IN ('41', '35', '29', '26', '44', '40', '34', '39', '32', '38', '31', '33', '30', '28', '27', '25', '43', '37', '36', '42')) ORDER BY "cm_movement"."date" DESC how can I get only the earliest or latest (only one movement) which is in prefetch_related in CaseManager.get_queryset() how can I sort the result by latest_movement that is being generated by CaseManager.get_queryset() and used in: CaseAdmin.latest_movement() in CaseAdmin.ordering should sort the results by year in DESC order, and if there is more than one record with the same year they should be sorted by their number in DESC order that's why I used CaseAdmin.ordering = ['-year', '-number'] but what happened is they got sorted by year only. … -
multiple order instances created when the page is refreshing
I'm getting the billing address and display it in the payments page but the problem is that when i refresh the page it's create an other instance in the admin panel I tried the get_or_create but it still the same def placeorder(request, total=0, quantity=0): current_user = request.user cart_itemes = CartItem.objects.filter(user=current_user) cart_count = cart_itemes.count() if cart_count <= 0: return redirect('store') # order_data=request.session.get('context') # if order_data: # return render(request,'orders/payments.html') for cart_item in cart_itemes: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity totale = total finaltotal = totale+50 if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.email = form.cleaned_data['email'] data.phone_number = form.cleaned_data['phone_number'] data.address_line1 = form.cleaned_data['address_line1'] data.address_line2 = form.cleaned_data['address_line2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] # data = Order(first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, # address_line1=address_line1, address_line2=address_line2, country=country, state=state, city=city) data.order_total = totale data.ip = request.META.get('REMOTE_ADDR') data.save() yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime('%Y%m%d') order_number = current_date + str(data.id) data.order_number = order_number data.save() order = get_object_or_404(Order, user=current_user, is_ordered=False, order_number=order_number) context = { "order": order, "cart_itemes": cart_itemes, "total": totale, "finaltotal": finaltotal } # request.session['context']=context return render(request, 'orders/payments.html', context) else: pass else: return redirect('checkout') … -
Django/HTMX - How to stop resetting selected option when search form is submitted?
I want to implement a search form that has a Product ID field and a and Product locations select field in which the list of locations should be populated based on the Product ID entered. For the Product ID, I'm using HTMX, to get the list of available locations dynamically. Which means, whenever I type any Product ID, I want to get all the available Locations for that ID without having to click on a button. And when the Location is selected and the Search button is clicked the search result should be displayed in the page. BUT the problem is, whenever I click select an option and click on the Search button, It reloads the page and resets the selected option! and this is not what I want, I want to keep the location as selected when the search result is displayed. How can I stop resetting the select input after selecting when the Search button is clicked and the page is reloaded? Template: <form method="get" action="{% url 'shop:product_list' %}"> {% csrf_token %} <div class="d-flex"> <div class="me-2">{{filter_form.name}}</div> <div class="me-2">{{filter_form.category}}</div> <div> <button name="product_search_btn" type="submit" class="btn btn-primary"> Search </button> </div> </div> </form> Form: class ProductSearchForm(forms.Form): id=forms.IntegerField(widget=forms.NumberInput(attrs={"hx-get":reverse_lazy("shop:product_locations"), "hx-trigger":"load, change", "hx-target":"#locations_select", "class":"form-control"})) locations=forms.ChoiceField(widget=forms.Select(attrs={"id":"locations_select", … -
How to update a post in Django using the same manual-written form for creating it?
I have a form in which I can create a new post, which works perfectly. Now I want the same form to be filled when clicking on a link in order to update the post. I've found lots of tutorials, but all of them were using the form in 'form.py'. I don't have a form base on my model, I've created the form myself and now I want it to go to the same form-page and fill up the data, so it can edit the post. When this link is clicked, which each post has one, I want it to go to the form-page and fill the form, so I can edit it. This link is in home.html <a href=""><img width="48" height="48" src="https://img.icons8.com/fluency/48/pogchamp.png" alt="pogchamp"/></a> This is my form. I use it for creating a new post, but I also want to use it for editing. It's add_edit.html <form class="form text-center" action="{% url 'addEdit' %}" method="POST"> {% csrf_token %} {% if messages %} {% for message in messages %} <p class="text-danger text-center fs-3 vov fade-in-up">{{ message }}</p> {% endfor %} {% endif %} <div class="mb-3 col-11 col-md-4 col-lg-3 mx-auto"> <label for="title" class="form-label float-start" id="title_lable">TITLE</label> <input type="text" class="form-control" name="title" id="title" placeholder="U_U" required> … -
DJango: Textarea/Form get, process and show
Good evening, i'm currently working on a small DJango project, and am currently facing an issue: The whole of the project is to provide a textarea to the user: 1- let the user write down the text that will be worked with. 2- store the data to process/work on it using python. 3- store the processed data on another variable. 4- show the text on a second textarea provided on screen. Currently, I've tried using a simple to get the information and store it, but the site keeps spinning and there's no progress Base .html section with the textareas: <section id="det"> <div class="theText"> <textarea id="text" placeholder="Type/Paste to Summarize"></textarea> <br> <button type="submit">Start</button> <br><br> <button type="submit">Clean</button> <br><br> </div> <div class="theText"> <textarea id="text" placeholder="Your summarized text"></textarea> <br> <button type="submit">Export</button> <br><br> <button type="submit">Copy</button> <br><br> </div> </section> Alternative tried: <form method="POST"> {% csrf_token %} <label for='TPre'>PreSummarizarion</label><br> <input id="TPre" name="TPre" type="text"><br> <button>Submit</button> </form> Current views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, "first/home.html",{ "text":text, }) def taking(request,tex,tex_slug): tex= textPre.objects.get(slug = tex_slug) return render(request, "first/home.html", { "tex":tex }) Current models on the django project: from django.db import models class textPre(models.Model): preText = models.TextField() #preText2 = models.CharField(max_length=1500) class … -
What am I missing to have 'move_up_down_links' display on 'ListAdmin' page using django-ordered-model?
I use django-ordered-model==3.7.4 in my project to create an ordered model. I want to have a way to reorder list items via Django Admin. I tried to use example code from django-ordered-model's docs, but unfortunatelly it doesn't work as expected. Here's my code: # models.py class ListItem(OrderedModel): """ Represents an item of the user-created book list. """ list = models.ForeignKey( verbose_name=_("список"), to=List, on_delete=models.CASCADE, related_name="items", ) book = models.ForeignKey( verbose_name=_("книга"), to=Book, on_delete=models.CASCADE, related_name="list_items", ) description = models.TextField( verbose_name=_("описание"), blank=True, null=True, default=None, ) created = models.DateTimeField(verbose_name=_("создана"), auto_now_add=True) updated = models.DateTimeField(verbose_name=_("изменена"), auto_now=True) class Meta: ordering = ["order"] verbose_name = _("элемент списка") verbose_name_plural = _("элементы списков") # admin.py class ListItemInline(OrderedTabularInline): model = ListItem fields = [ "book", "description", "order", "move_up_down_links", ] readonly_fields = [ "order", "move_up_down_links", ] ordering = [ "order", ] extra = 0 @admin.register(List) class ListAdmin(OrderedInlineModelAdminMixin, admin.ModelAdmin): """ Configures admin views for List. """ model = List list_display = [ "title", "user", "is_public", "created", ] inlines = [ListItemInline] readonly_fields = [ "created", "updated", ] @admin.register(ListItem) class ListItemAdmin(OrderedModelAdmin): """ Configures admin views for ListItem. """ model = ListItem list_display = [ "book", "list", "order", "move_up_down_links", "created", ] readonly_fields = [ "created", "updated", ] As a result, I can see move_up_down_links on ListItemAdmin page: … -
Is there a way to define the creation log recrods in database process in MIDDLEWARE?(Django)
I am working on a Django project, in which has a customized logging class. I need to save all the logs on my database. I have a separate app for my customized log class. In settings.py: INSTALLED_APPS = [ ... 'CustomDBLogger', ... ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'db_log': { 'level': 'DEBUG', 'class': 'CustomDBLogger.db_log_handler.DatabaseLogHandler' }, }, 'loggers': { 'db': { 'handlers': ['db_log'], 'level': 'INFO' # we want to see info logges and beyond } } } In CustomDBLogger/models.py: import logging from django.db import models from six import python_2_unicode_compatible from django.utils.translation import gettext_lazy as _ LOG_LEVELS = ( (logging.NOTSET, _('NotSet')), (logging.INFO, _('Info')), (logging.WARNING, _('Warning')), (logging.DEBUG, _('Debug')), (logging.ERROR, _('Error')), (logging.FATAL, _('Fatal')), ) @python_2_unicode_compatible class StatusLog(models.Model): logger_name = models.CharField(max_length=100) level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True) msg = models.TextField() trace = models.TextField(blank=True, null=True) create_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Created at') # new fields username = models.CharField(max_length=128, null=False, blank=False) user_ip = models.CharField(max_length=128, null=True, blank=True) page_url = models.TextField(max_length=200) page_name = models.TextField(max_length=200, null=True, blank=True) json_data = models.JSONField(default=dict, null=True, blank=True) segment0 = models.TextField(max_length=128, null=True, blank=True) segment1 = models.TextField(max_length=128, null=True, blank=True) segment2 = models.TextField(max_length=128, null=True, blank=True) segment3 = … -
Django channels consumer how to disconnect at server side
I'm trying to write a log file viewer with django, channels, but only the first connection works well, while I refresh the frontend, websocket will connect fail. After some search, I found the loop is still running in my code(the first websocket connection not cleaned up rightly). I was thinking that disconnect would be called when I close the websocket client, but it's not. My consumer code: import time from channels.exceptions import StopConsumer from channels.generic.websocket import WebsocketConsumer class LogConsumer(WebsocketConsumer): end = False def connect(self): self.accept() filename = self.scope['url_route']['kwargs']['filepath'] file_fullname = "/tmp/" + filename print('file name: %s' % file_fullname) with open(file_fullname, 'r') as f: while True: time.sleep(1) if self.end: break new_line = f.readline() print('Loop is still running ....') if new_line: print('sending data: %s' % new_line) self.send(text_data=new_line) def disconnect(self, event): print('websocket disconnected...', event) self.end = True raise StopConsumer() daphne output: 192.168.1.2:63267 - - [03/Jun/2023:16:25:09] "WSCONNECTING /ws/message/" - - 192.168.1.2:63267 - - [03/Jun/2023:16:25:09] "WSCONNECT /ws/message/" - - file name: /tmp/message Loop is still running .... sending data: Loop is still running .... sending data: 1 Loop is still running .... sending data: 2 Loop is still running .... sending data: 3 192.168.1.2:63267 - - [03/Jun/2023:16:25:14] "WSDISCONNECT /ws/message/" - - 192.168.1.2:63273 - - [03/Jun/2023:16:25:14] … -
DRF ORM: Aggregate, annotate and remove duplicates all in the same query
Knowing that I have the following models: class Merchant(BaseModel): business_name = CharField() user = ForeignKey( User, related_name='merchant' # ... ) # other fields... class Sale(BaseModel): merchant = ForeignKey( Merchant, related_name='sale_merchant' # ... ) statue = CustomCharField( max_length=20, choices=[(DRAFT, DRAFT)), (COMPLETED, COMPLETED), (FAILD, FAILD)], # ... ) # other fields like total, discount, data... class SaleItem(BaseModel): quantity = PositiveIntegerField() product = ForeignKey( Product, # ... ) sale = ForeignKey( Sale, related_name='sold_item' # ... ) # other fields... As well as a Product model, and a User model (alongside other information, the User model stores the user's city as a reference to the City model). As you can see, a Sale, may have multiple SaleItems, a SaleItem refers to a single Product and the Sale itself, and has a quantity. Finally, a Sale represents a set of products that were sold by us to a specific merchant . I want to get the number of items of each product that were sold to each merchant. An example of the output I'm trying to achieve (id replesents the id of the first SaleItem that links product X to merchant Y): +--------------------------------------------------------------------+ | id | Merchant Name | Denomination | Quantity | Merchant City … -
django full text search taggit
My application - the basics I have a simple django application which allows for storing information about certain items and I'm trying to implement a search view/functionality. I'm using django-taggit to tag the items by their functionality/features. What I want to implement I want to implement a full text search which allows to search across all the fields of the items, including their tags. The problem(s) On the results view, the tagged items are showing up multiple times (one occurence per tag) The ranking is correct when I specify * only a single* tag in the search field, but when I specify multiple tag names, I will get unexpected ranking results. I suspect the SearchVector() does not resolve the tags relation as I expected it to do. The tags should be treated just like a list of words in this case. Example Code models.py from django.db import models from taggit.managers import TaggableManager class Item(models.Model): identifier = models.SlugField('ID', unique=True, editable=False) short_text = models.CharField('Short Text', max_length=100, blank=True) serial_number = models.CharField('Serial Number', max_length=30, blank=True) revision = models.CharField('Revision/Version', max_length=30, blank=True) part_number = models.CharField('Part Number', max_length=30, blank=True) manufacturer = models.CharField('Manufacturer', max_length=30, blank=True) description = models.TextField('Description', blank=True) tags = TaggableManager('Tags', blank=True) is_active = models.BooleanField('Active', default=True) forms.py … -
"detail": "Authentication credentials were not provided." Django DRF
Im trying to create an api for my django project to get some data from database and show it as restframework Response everytime I try to get the data it shows me this error this is my views.py code for getting the data class QuestionListView(APIView): permission_classes = [IsAuthenticated] def get(self: Self, request: HttpRequest) -> Response: questions_list: Question = Question.objects.filter(status=True) if (len(questions_list) == 0): return Response('هنوز سوالی طرح نشده', status=status.HTTP_204_NO_CONTENT) else: serializer = QuestionsSerializer(instance=questions_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) this is my question model models.py file class Question(models.Model): CHOISES: list = [ ('option1', 'گزینه اول'), ('option2', 'گزینه دوم'), ('option3', 'گزینه سوم'), ('option4', 'گزینه چهارم'), ] SCALES: list = [ (1, 'آسان'), (2, 'متوسط'), (3, 'سخت'), ] question = models.CharField(max_length=200, unique=True, verbose_name='سوال') option1 = models.CharField(max_length=50, verbose_name='گزینه اول') option2 = models.CharField(max_length=50, verbose_name='گزینه دوم') option3 = models.CharField(max_length=50, verbose_name='گزینه سوم') option4 = models.CharField(max_length=50, verbose_name='گزینه چهارم') answer = models.CharField(max_length=10, choices=CHOISES, verbose_name='پاسخ', help_text='گزینه درست را انتخاب کنید') scale = models.IntegerField(choices=SCALES ,null=True, verbose_name='سطح سختی سوال') status = models.BooleanField(default=False, help_text='وضعیت انتشار سوال', verbose_name='وضعیت') def __str__(self): super(Question, self).__str__() return self.question class Meta: verbose_name = 'سوال' verbose_name_plural = 'سوالات' and this is the serializer.py file class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question exclude = ('status',) read_only_fields = ('id',) and this is my … -
Issue with dictionary values not appending in Django session
I'm encountering an issue with updating dictionary values in Django session. Initially, I was using a list to store data in the session, and it worked perfectly fine. However, when I switched to using a dictionary to store the data, I noticed that the values were not getting appended as expected. Instead, the new data was replacing the old data in the dictionary. views.py: def pushups(request): if "record" not in request.session or not isinstance(request.session["record"], dict): request.session["record"] = {} return render(request, ("App_4/record.html"), { "record" : request.session["record"] }) def add(request): if request.method == 'POST': form = Add_record_form(request.POST) if form.is_valid(): a = form.cleaned_data["add_form"] b = request.session["record"] b[f"{date.year}-{date.month}-{date.day} {date.hour}:{date.minute}:{date.second}"] = a request.session["record"] = b return HttpResponseRedirect(reverse("App_4:view_record")) else: return render(request, "App_4/add_record.html", { "add_form" : form }) return render(request, ("App_4/add_record.html"), { "add_form" : Add_record_form() }) record.html {% for key,value in record.items %} <tr> <td>{{key}}</td> <td>{{value}}</td> </tr> {% empty %} <tr> <td>no tasks</td> </tr> {% endfor %} The strange thing is that the dictionary values only get updated correctly if I make changes in the views.py file or just simply click CTRL+S before adding new data. Otherwise, the previous data just gets replaced. This issue wasn't present when I was using a list instead of a dictionary. … -
Nested for loop - model.id in parent for loop does not match model.id in nested for loop (django)
I am trying to access data from a parent to a child via a foreign key. WHAT WORKS - the views The data in the child is not "ready to be used" and need to be processed, to be represented in a progress bar in %. The data processing is handled in the views. When I print it on the console, it seems to work and stored into a variable reward_positions. Reward positions = [(<Venue: Venue_name>, reward_points, reward_position_on_bar)] So this part works. The plan is therefore to access reward_position_on_bar by calling {{reward_positions.2}} WHAT DOESNT WORK - the template But something is not working to plan in the template. The template renders the last child_model (thats rewardprogram) objects of the last parent_id (thats venue) irrespective of the actual parent_id processed in the for loop. TEST RESULT & WHERE I THINK THE PROBLEM IS I think my problem lies in my nested forloop. The parent_id in the parent forloop does not match the '{{reward_position.0}}' in the nested forloop. Doing a verification test, {{key}} should be equal to {{reward_position.0}} as they both go through the same parent forloop. However, if {{key}} does change based on venue.id (parent forloop id), {{reward_position.0}} is stuck to … -
Django orm filter many to many fields
The question is this. There are Project and User models. In the Project model, there are 2 ManyToMany links to the users model. class Project(models.Model): name = models.CharField(max_length=100) content = models.TextField() creaters = models.ManyToManyField('User', related_name='creater_projects') workers = models.ManyToManyField('User', related_name='worker_projects') class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) I need to filter the projects depending on the transferred user.id You can filter as follows from django.db.models import Q user_id = 1 Project.objects.filter(Q(creaters__id=user_id) | Q(workers__id=user_id)) What other ways are there to do similar filtering? -
Applying sync_to_async for django query results in the same error nonetheless
I have the following code import asyncio from asgiref.sync import sync_to_async from user.models import Users @sync_to_async def get_users(input): return Users.objects.values_list("name", flat = True).filter( name__icontains=input) async def user_autocompletion(current: str): print(list(await get_users(current))) asyncio.run(user_autocompletion("b")) I am getting this error even though I used sync_to_async as advised django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I fix it? -
Troubleshooting: Cannot post images to S3 Bucket from Django during deployment on Vercel
So, I have been trying to use django admin panel to add some contents along with title and image into a database which I have been using in my react project. When I try to upload static file like image from django backend It is properly posted in s3 bucket. But in deployment its not working Also, the static files are properly retrieved as well in deployment as I can see css in django admin panel as well. Error message I am getting in deployment -
Django does not serve static files for ckeditor in docker container
I am deploying an django project with docker-compose and nginx. I can serve the ckeditor with its toolbar showing with python manage.py runserver. However when I try to serve it docker-compose and nginx I cant. These are the output in the console: Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor-init.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor.js:1 docker-compose.yml version: '3.8' services: db: image: postgres:13 environment: - POSTGRES_DB=db - POSTGRES_USER=user - POSTGRES_PASSWORD=password volumes: - db_data:/var/lib/postgresql/data networks: - app_network web: build: . command: gunicorn okuyorum.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/app/staticfiles - media_volume:/app/media expose: - 8000 depends_on: - db networks: - app_network nginx: image: nginx:1.19 volumes: - static_volume:/usr/share/nginx/html/static - media_volume:/usr/share/nginx/html/media - ./nginx.conf:/etc/nginx/nginx.conf ports: - 80:80 depends_on: - web networks: - app_network volumes: db_data: static_volume: media_volume: networks: app_network: Dockerfile # Use an official Python base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Create and set the working directory RUN mkdir /app WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ libpq-dev \ gcc \ gettext \ && rm -rf /var/lib/apt/lists/* # Install project dependencies COPY requirements.txt /app/ … -
Is there is a way to convert django project to app(iso/apk)
can I convert a django project into a iso/apk app, I have seen cordva that fixs this problem, but im not sure if it works with django since it use templates/assest/static folders, and cordva dosnt have this files system.., so is there is a way to config cordva to work with djanog or is there is another way? note: i do not prefer to rebuild the UI, I prefer to keep it as it is. a way to run the django project as an application. -
I get 301 Moved Permanently Error when react app calls a channel route of django app
I use django-eventstream and django channel packages for have a realtime channels and when channel route is called by Browser i would get Sent messages in my channel(i can see messages in browser tab), but react-app gets 301 Moved Permanently Error when calls my channel with this form new EventSource('http://source-ip:source-port/post-list', { withCredentials: true }); my setting for django-app : 1)installing django--eventstream 2)installing django channel 3)Adding them in 'INSTALLED_APPS' part of settings.py 4)Adding the GripMiddleware: in MIDDLEWARE part of settings.py 5)creating an asgi.py : import django from django.core.asgi import get_asgi_application from django.urls import path, re_path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myserver.settings') os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" application = ProtocolTypeRouter({ 'http': URLRouter([ path('events/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), path('post-list/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns)), { 'channels': ['post'] }, ), re_path(r'', get_asgi_application()),]), }) 6)using send_event for sending message to channel: send_event('post', 'message', {'text': 'hello world' }) -
Queryset to update set of values for a field
What queryset can I use to translate the values of a field from one set of values to another set? For example, lets say I have a User model with a CharField containing the name of a country and I wish to update the name of some of the countries for all users using the following dict: new_country_names = {"Micronesia": "States of Micronesia", "Macedonia": "North Macedonia"} I obviously want to avoid doing this by looping over each user and checking the value of their country. -
I get 301 Moved Permanently Error when react app calls my channel route of django app
I get 301 Moved Permanently Error when react app calls my channel route of django app. I use django-eventstream and django chnnel packages for have a realtime channels and when channel route is called by Browser ,i would get Sent messages in my channel(can see messages in browser tab), but react-app gets 301 Moved Permanently Error when calls my channel with this form enter image description here my setting for django-app : 1)installing django-eventstream and django channel packages 2)Adding them in INSTALLED_APPS section and Adding the GripMiddleware to MIDDLEWARE part in settings.py file 3)creating an asgi.py enter image description here 4)using send_event for sending message to channel enter image description here 5)django-cors-headers package is also used -
Images and static files not showing up on Django app with Docker Compose and Nginx
When I run Django application in docker compose containers and deploy to the server I have no images displayed on the page and no statics for the admin panel. docker-compose.yml version: '3.3' services: db: image: postgres:13.0-alpine volumes: - db_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: login/foodgram:latest restart: always volumes: - static_value:/app/static/ - media_value:/app/media/ depends_on: - db env_file: - ./.env frontend: image: login/foodgram_frontend:latest volumes: - ../frontend/:/app/result_build/ depends_on: - web nginx: image: nginx:1.21.3-alpine restart: always ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - ../frontend/build:/usr/share/nginx/html/ - ../docs/:/usr/share/nginx/html/api/docs/ - static_value:/var/html/static/ - media_value:/var/html/media/ depends_on: - web volumes: static_value: media_value: db_data: nginx.conf server { server_tokens off; listen 80; server_name my ip; client_max_body_size 20M; location /api/docs/ { root /usr/share/nginx/html; try_files $uri $uri/redoc.html; } location /media/ { root /var/html/; } location /static/admin/ { root /var/html/; } location /static/rest_framework/ { root /var/html/; } location /admin/ { proxy_pass http://web:8000/admin/; } location /api/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://web:8000; } location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri /index.html; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /var/html/frontend/; } } Please help, third day i can't … -
Django - problem re-adding goods to the basket
I am creating an online store on Djnago. The project has a basket in which you can place goods, as well as remove them. Goods are placed and removed without problems. But, after the product has been placed, after deletion - when re-adding this product (which was deleted) to the basket (the user is always the same) - the product does not appear, what is the problem? Below is the code of all application files: models.py: from django.db import models from users.models import User class ProductCategory(models.Model): name = models.CharField(max_length=128, unique=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=256) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveSmallIntegerField(default=0) image = models.ImageField(upload_to='products_images') category = models.ForeignKey(to=ProductCategory, on_delete=models.CASCADE) def __str__(self): return f'Product: {self.name} | Category: {self.category.name}' class Basket(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=0) created_timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Корзина для {self.user.username} | Продукт: {self.product.name}' views.py: from django.shortcuts import render, HttpResponseRedirect from products.models import ProductCategory, Product, Basket from users.models import User def index(request): context = { 'title': 'Store', 'is_prom': True, } return render(request, 'products/index.html', context) def products(request): context = { 'title': 'Store - Каталог', 'products': Product.objects.all(), 'categories': ProductCategory.objects.all(), } return render(request, "products/products.html", … -
Django sessions idle on localhost, pending forever after login callback
Django project cannot set sessions only on localhost, and the web keeps pending forever after login callback. Here is the log: "GET / HTTP/1.1" 302 0 "GET /kc/callback?state=95ad23ff24f648dd9a28b845dab57623&session_state=feac8cb3-a655-4608-82b5-2a309e97db72&code=771863de-fa31-4aa7-a936-c26c082995e1.feac8cb3-a655-4608-82b5-2a309e97db72.d52c4c80-ab1f-4a3c-9909-f1d43de72c5c HTTP/1.1" 302 0 "GET /kc/callback?state=3c3f804074094bccb802dfb65b8eb34f&session_state=feac8cb3-a655-4608-82b5-2a309e97db72&code=d1ae63ae-9c6e-4fb3-b2b6-75ac7f339a0d.feac8cb3-a655-4608-82b5-2a309e97db72.d52c4c80-ab1f-4a3c-9909-f1d43de72c5c HTTP/1.1" 302 0 setting user session Internal Server Error: / Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 233, in _get_session return self._session_cache AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\...backend\venv\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\...backend\venv\lib\site-packages\django\utils\asyncio.py", line 33, in inner return func(*args, **kwargs) File "C:\Users\...backend\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\...backend\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: sorry, too many clients already The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\...backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\...backend\ilumens_backend_sf\middleware\auth.py", line 164, in __call__ if "user" not in request.session: File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 55, in __contains__ return key in self._session File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 238, in _get_session self._session_cache = self.load() File "C:\Users\...backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load s …