Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does Fargate send both uWSGI and Django logs from the container to Cloudwatch
I have Django running behind uWSGI in a docker container in AWS Fargate. The container logs are sent to Cloudwatch. In my setup, I would be okay if both uWSGI and Django log to stdout/stderr and the logs are getting mixed. Pasting my config below. This is my entrypoint.sh: #!/bin/bash python manage.py collectstatic --noinput python /code/manage.py migrate --noinput exec uwsgi --show-config --log-master I can see proper log output from Django for collectstatic and the migrate call. DEBUG 2020-09-06 07:39:38,589 retryhandler 6 139721333720896 No retry needed. These are easy to recognize, because they start with the log level DEBUG. As soon as a the uWSGI process starts, I stop seeing any log events from Django. The only thing I see are uWSGI log events like: [pid: 13|app: 0|req: 2/1] 10.0.2.249 () {30 vars in 352 bytes} [Sun Sep 6 07:39:46 2020] GET / => generated 3877 bytes in 444 msecs (HTTP/1.1 200) 4 headers in 128 bytes (1 switches on core 1) In the Dockerfile I am setting 3 additional uWSGI related environment variables: ENV UWSGI_WSGI_FILE=sanctionsio/wsgi.py ENV UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_HTTP_AUTO_CHUNKED=1 UWSGI_HTTP_KEEPALIVE=1 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy ENV UWSGI_WORKERS=2 UWSGI_THREADS=4 Django logging is set up like this: LOGGING_LEVEL = 'DEBUG' LOGGING = { 'version': 1, … -
how to ajaxify the post uploaded in django
I have already created posts. Users can post their own posts with images and can update and delete them. But now i want to list the already posted posts of the user with ajax . But i don't how to do that with the images. here's the post of user in my template {% for object in object_list %} <div class="post-card" > <p> <img class="rounded-circle profile-image" src="{{ object.author.profile.image.url }}"> <span class="auth-span"><b>{{ object.author }} </b><i class="fa fa-check-circle"></i> </span> <span class="date-span">{{ object.date_created|timesince }} ago</span> </p> <p><a href="{% url 'detail' object.id %}" class="title">{{ object.title }}</a></p> <div> {% if object.Image %} <p><a href="{% url 'detail' object.id %}"><img src="{{ object.Image.url }}" class="img-fluid" alt="Responsive image" ></a></p> {% endif %} </div> <div class="icon-div" > <p class="icon" style="mt"> <i class="fa fa-comments"></i> <i class="fa fa-heart" ></i> <i class="fa fa-share-square"></i> <i class="fa fa-eye"></i> </p> </div> </div> {% empty %} {% if request.GET.q %} <p style="color: var(--text-color);margin-top: 20px;margin-left: 250px;">NO tweets found</p> {% else %} <p>NO tweets yet.</p> {% endif %} {% endfor %}` So how do i show these posts with jquery for ajax? -
Push Notifications with Angular and Django Rest Framework
I want to build a Progressive Web App with Angular in the Frontend and Django/Django Rest Framework in the backend (PostgreSQL as an RDBMS). I want to have Push Notifications in my system, for example, I have a table of 'payments' in my DB, and one day before the 'due_date' of a 'payment' I want to send a push notification to the User. Can you recommend me some libraries, third-party Message Brokers maybe that would go well with Angular and DRF. I am not very familiar with Angular, but I will mostly handle the backend stuff. -
Django3x RuntimeError:
I am learning Django 3x and when I try to add a path in config/urls.html "path( cheeses/', include('everycheese.cheeses.urls', namespace='cheeses'), ),", it throws an runtimeerror, "RuntimeError: Model class everycheese.cheeses.models.Cheese doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." I searched for solutions but found the existing answers cannot fix it. Could anyone help me? Thank you. ./config/urls.html ... urlpatterns = [ path( "", TemplateView.as_view(template_name="pages/home.html"), name="home", ), path( "about/", TemplateView.as_view(template_name="pages/about.html"), name="about", ), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path( "users/", include("everycheese.users.urls", namespace="users"), ), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path( 'cheeses/', include('everycheese.cheeses.urls', namespace='cheeses'), ), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ... ./cheeses/models.py from django.db import models from autoslug import AutoSlugField from model_utils.models import TimeStampedModel class Cheese(TimeStampedModel): class Firmness(models.TextChoices): UNSPECIFIED = "unspecified", "Unspecified" SOFT = "soft", "Soft" SEMI_SOFT = "semi-soft", "Semi-Soft" SEMI_HARD = "semi-hard", "Semi-Hard" HARD = "hard", "Hard" name = models.CharField("Name of Cheese", max_length=255) slug = AutoSlugField("Cheese Address", unique=True, always_update=False, populate_from="name") description = models.TextField("Description", blank=True) firmness = models.CharField("Firmness", max_length=20, choices=Firmness.choices, default=Firmness.UNSPECIFIED) def __str__(self): return self.name -
Get value from intermediate table
I have 2 tables "Sample" and another one "Test", with a pivot table (intermediate) "SampleTest" that has the ForeignKeys plus an extra field "result". I made a view.py where I can get the "Sample" and "Test" data: def imprimir(request, id): sample = Sample.objects.get(pk=id) tests = sample.tests.all() return render(request, 'protocolo.html', { 'sample': sample, 'tests': tests, }) But I would also like to take the value "result" from my intermediate table, and that this value comes in the variable "tests". How can I do this? From already thank you very much -
How to change the select options based on the radio check?
Here I have div column for subject. There is a select option and I want to change this options based on the user check either general or reserve. If general Select Listing option and if reserve lisitng detail options should be displayed. At the first general option will be checked so Select Lisiting option should be displayed by default. If user clicks the reservation then the Listing Detail option should be displayed. How can I do it ? <input type="radio" id="general" value="general" onclick="javascript:chooseTableRows();" name="option" >General</label> <label><input id="reserve" value="reserve" type="radio" name="option" onclick="javascript:chooseTableRows();">Reservation</label> <div class="form-group row" id="sub" style="display:none;"> <label class="col-sm-2 col-form-label">Subject:</label> <div class="col-sm-10"> <select class="js-example-basic-single" name="subject" required="" style="width: 250px;"> <option selected value="">Listing Detail</option>{{event}} {% for listing in listing_details %} <option value="{{listing.listing.nickname}}">{{listing.listing.nickname|truncatechars:20}}</option> {% endfor %} </select> </div> # want to replace this select upon reserve option checked <select class="js-example-basic-single" name="subject" required="" style="width: 250px;"> <option selected value="" id="sub1">Select Listing</option> {% for listing in listings %} <option value="{{listing}}">{{listing}}</option> {% endfor %} </select> script <script type="text/javascript"> function chooseTableRows() { if (document.getElementById('reserve').checked) { document.getElementById('sub1').style.display = 'block'; document.getElementById('sub').style.display = 'none'; } else { document.getElementById('sub').style.display = 'block'; document.getElementById('sub1').style.display = 'none'; } } </script> -
Django custom url using rest framework
I have a model ... class Person(models.Model): first_name = models.CharField(max_length=30), last_name = models.CharField(max_length=30) I'm using React on the frontend and using json to deal with my data. So in my urls.py file I'm using drf-extensions I'm using it because it allows me to do some nested routing but I am having trouble now trying to router correctly if I want all people by name from my database. For instance, I have a viewset class PersonView(viewsets.ModelViewSet): serializer_class = PersonSerialzer queryset = Person.objects.all() And I am getting all the data back from my table but I want to have this and also be able to hit an endpoint where I can get back all rows with the same first name. I'm not sure how to do this. -
Add multiple products to an order - Django
I'm trying to create an inventory management system. I'm having problems figuring out how to add multiple inventory items into my order from a table. I want to achieve this by selecting the item by the checkbox and also adding the quantity. html <form method="POST" action=""> {% csrf_token %} {% for field in form %} <div class="form-group row"> <Label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</Label> <div class="col-10"> {{ field }} </div> </div> {% endfor %} <table class="table table-striped"> <tbody> {% for item in Inventory %} <tr> <td> <input type="checkbox" name="itemCheck" value="{{ item.pk }} "></td> <td> <input name="itemQuantity"> </td> <td> {{ item.name }} </td> <td> {{ item.quantity }} </td> <td> <span class="badge badge-pill badge-success">{{item.status}}</span></td> <td> ${{ item.sale_price }} </td> </td> </tr> {% endfor %} </tbody> </table> views.py def create_order(request): order_form = OrderForm(request.POST) if request.method == 'POST': if formset.is_valid(): total = 0 order = Orders(total=total) order.save() order_form.save() selected_items = request.POST.getlist('itemCheck') print(selected_items) # This returns the primary keys of the selected items context = {"form": order_form, "Inventory": Inventory.objects.all()} return render(request, 'create_order.html', context) models class Inventory(models.Model): name = models.CharField(max_length=128, blank=False) ... def __str__(self): return f"{self.id} - {self.name}" class Orders(models.Model): studio = models.CharField(max_length=64) status = models.CharField(max_length=64, default="warehouse", blank=False) total = models.DecimalField(max_digits=10, decimal_places=2) class OrderEquipment(models.Model): … -
OperationalError at /admin/core/order/ no such column: core_order.shop_name_id
i want to use shop table as foreign key to filter items and order in the adminview but got that error models class Shop(models.Model): shop_name = models.CharField(max_length=100) class Item(models.Model): title = models.CharField(max_length=100) shop_name = models.ForeignKey(Shop, on_delete=models.CASCADE) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) is_active = models.BooleanField(default=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop_name = models.ForeignKey(Shop, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) payment_received = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) in admin i defined the the model shop admin.py admin.site.register(Shop) -
Created A Sitemap But Google Couldn't Fetch Error
In Django, I've created a sitemap for my project. I didn't used built in django sitemap framework. I created a view and template and point it from urls.py. When I open it in explorer sitemap works fine. But when I add my sitemap to my searh console google give me couldn't fetch error. Couldn't figure out what is the problem. Any idea? My View: class SitemapPost(ListView): model = Movies ordering = ['-pk'] template_name = "front/sitemap-post.xml" content_type='application/xml' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.now() context['today'] = datetime.now() return context Urls: path('sitemap-post.xml', SitemapPost.as_view(),name='sitemap-post'), template: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% for object in object_list %} <url> <loc>https://{{request.get_host}}{{ object.get_absolute_url }}</loc> <lastmod>{{today|date:"Y-m-d"}}</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> {% endfor %} </urlset> and here is my sitemap file: link -
FormSet for a child class only
class Parent(Form): field1 = forms.FloatField(.....) field2 = forms.IntegerField(.....) field3 = forms.IntegerField(.....) field4 = forms.CharField(.....) class Child(Parent): field5 = forms.CharField(.....) I'm trying to have a formset to repeat the "Child" class field without repeating the "Parent" class fields I've tried ChildFormSet = formset_factory(Child, extra=10) but this will repeat the parent as well Any ideas? -
Not able to add Emoji's as comment "OperationalError :Incorrect string value: '\\xF0\\x9F\\xA5\\xB0' for column 'content' at row 1"
when I tried to add emoji's i'm getting this error did not workout even CharField getting the same error. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) content = models.TextField(max_length=500, blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.content def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.post.pk}) # returns a string to the post detail that uses the pk of the comment instance. post. pk to link to the correct detail page ie. /post/ def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) n = 4 truncatewords = Truncator(self.content).words(n) notify.send(self.author, recipient=self.post.author, verb='commented "' + truncatewords + '" on your post!', action_object=self.post, description='comment', target=self) -
How to attach an image in mail using django
I tried sending mail using Django. It worked well when I sent simple mail. But how can I add attachments(image) to my mail? -
How do you do nested routes in Django using drf-extension
I have a model with fields and I want to get all data from that table that is populated in my psql database back. However, I also want to have a url that gets back all data that meets a specific criteria. So filtering for the data based on url params. These are for certain fields on my model. How can I do this using something like drf-extensions -
how to call custom data from Django User models
im using the built in User model of django and have added few custom fields one of them being the user type, i want to set up conditional statements according to the e_type this is my code. models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib import auth from django.conf import settings class User(auth.models.User,auth.models.PermissionsMixin,models.Model): EMPLOYEE='em' MANAGER='mn' USER_TYPE=[ (EMPLOYEE,'employee'), (MANAGER,'manager'), ] e_type=models.CharField(max_length=2,choices=USER_TYPE,default=EMPLOYEE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return "@{}".format(self.username) views.py from django.shortcuts import render from django.contrib.auth import views as auth_views from .models import * from django.views.generic import TemplateView def home(request): user=request.user.e_type return render(request,"leaveApp/home.html") -
How do i generate an index number to display in the template
This might be a very simple question but i'm very new to django So i'm working on Django book list app and i need to have an index for each book in order. i was using id that was generated by the database at first but then i realized the number jumps from 3 to 10 cause i was deleting some books earlier. How do i generate an index number for every object in the queryset in order? Here's my views just incase def booklist_view(request): queryset = Book.objects.all() bkff = BookListForm() if request.method == 'POST': bkff = BookListForm(request.POST) if bkff.is_valid(): bkff.save() bkff = BookListForm() context = { 'form': bkff, 'arrayobj': queryset, 'index': 0 } return render(request, 'booklist1st/booklist.html', context) and here's my HTML {% for ins in arrayobj %} <div class="data" id="test"> <div class="num"><p>{{ins.id}}</p></div> <div class="title"><p>{{ins.title}}</p></div> <div class="author"><p>{{ins.author}}</p></div> <div class="ISBN"><p>{{ins.isbn}}</p></div> <div class="edit"><a href="#">Edit</a></div> <div class="delete"><a href="#">Delete</a></div> </div> {% endfor %} -
how to write serializer and models in django for my custom output?
Below the json i want to pass from postman and want to store in django models, Please note province_name,email,country_code,phone_number should be save in respected table and addressline1, addressline2, postcode should be save in respected table, how to achieve this in serializer and django model. { "user_id": 3, "designation_id": 1, "province_name": "xxxxxxxxxxx", "email": "xxxxxxxxxxx@gmail.com", "country_code": "54321", "phone_number": "9876543210", "address_line1": "aaaaaaaaaaaaaaa", "address_line2": "aaaaaaaa", "province_id": 1, "district_id": 1, "city_id": 1, "postcode": "12345" } -
Issue in making changes on the site, hosted on pythonanywhere
I'm hosting my blog site on pythonanywhere. I also have a model field for subscribers in the database. The problem is whenever ever I create a new post locally and pull it in pythonanywhere bash console. The local database replaces the production database. Which results in losing all the data provided by the users. How to stop some fields from changing on every pull request? class Category(models.Model): created_on = models.DateTimeField(auto_now_add=True, verbose_name="Created on") updated_on = models.DateTimeField(auto_now=True, verbose_name="Updated on") title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() image_file = models.ImageField(upload_to='media', null=True, blank=True) image_url = models.URLField(null=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) published_date = models.DateTimeField(blank=True, default=timezone.now ,null=True) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ('-published_date',) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_on',) def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) class Subscribe(models.Model): email = models.EmailField() subscribed_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-subscribed_on',) def __str__(self): return 'Subscribed by {} on {}'.format(self.email, self.subscribed_on) -
How to use User Model defined in models.py for Authetication in Django Rest Framework
What I want to do 1.Introducing authentication in Django Rest Framework 2.Doing authentication using User model I defined in as models.Model, not admin-user provided by django by default. Version django : 3.1 djangorestframework:3.11.1 python : 3.7.6 Situation I am trying to creating an app that each user can exchange their items. I use Django in server side, and React in client side. In order to introduce authentication and registration, I created User model in models.py. However, when I try to introducing these features in Django Rest Framework I notice that I may not be able to do that using User I define, perhaps I have to use admin-user django provides. Question __ First of all, can I introduce authentication and registration features using User model I define myself ?__ I found I can edit admin-user itself so I edited it. It doesn't work. Honestly, I don't understand whether I can introduce these features using User model as well. I would like to teach me how to figure it out. And I would like to those who have combined Django and React to teach me some way to realize authentication and registration. Thank you very much. This is my User model. … -
Integrating Stripe Payment gateway with Django Rest Framework (DRF) and use it with Flutter
I want to use Stripe Payment Gateway for my Django Rest Framework (DRF) API which is going to be consumed by my flutter app. I could have used Strip's plugin in Flutter but I think that is not the actual process. I want to know the actual way of integrating payment gateway with a Django Rest Framework API. -
how do you work together on github project but sync databases in the code? Django
Hi How would you go about using the same database in django when working on a web application together via github? New to web apps and collaborating :) thank you! -
How does Django get id on url?
When i clicked my menu url only gets category name and slug cant reach id how can i solve that ? This is the url i get def category_products (request,id,slug): category=Category.objects.all() products=Product.objects.filter(category_id=id) context={'products':products,'category':category,'slug':slug, } return render(request, 'kiliclar.html', context) urlpatterns = [ path('category/<int:id>/<slug:slug>/', views.category_products,name='category_products'), ] template {% recursetree category %} <li class="dropdown"> <a href="/category/{{ node.slug }}" class="nav-link dropdown-toggle arrow" data-toggle="dropdown">{{ node.title }}</a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> <li><a href="#">{{ children }}</a></li> </ul> {% endif %} -
Order of Values from a Django Foreign Key Reverse Lookup
I have two models, Document and DocumentImage. Document has a primary key called document_id, and a foreign key to DocumentImage. Say I have a list of document_ids and I run this query: images = DocumentImage.objects.filter(document__in=document_ids) as a reverse lookup through the foreign key relationship Is it true that images[0] is derived from document_ids[0], and images[1] is derived from document_ids[1], etc? I need to combine each element in images with each element in document_ids, and I want to make sure that I have the correct document_id for that element from images. In other words, I want to do this: for document_id, image in zip(document_ids, images): # associate the document_id with the image and make sure that each image is associated with the correct document_id. Thanks! Mark -
Allow user to view previously submitted form in Django
I made a a web app where the user can submit a form. I want the user to be able to view his submission but I can't figure out how to access the previously submitted data. I keep getting an error related about failing to reverse match failure. The error says Reverse for 'apply_view' with no arguments not found. 1 pattern(s) tried: ['submission/(?P<apply_id>[0-9]+)/$'] Views.py @login_required def apply(request): """Submit application""" if request.method != 'POST': form = ApplicationForm() else: form = ApplicationForm(data=request.POST) if form.is_valid(): new_application = form.save(commit=False) new_application.owner = request.user new_application.save() return redirect('credit_apply:submitted') context = {'form': form} return render(request, 'credit_apply/apply.html', context) def apply_view(request, apply_id): """View and maybe? edit application""" application = Application.objects.get(id=apply_id) if request.method != 'POST': form = ApplicationForm(instance=application) else: form = ApplicationForm(instance=application, data=request.POST) if form.is_valid(): form.save() return redirect('credit_apply:submitted') context = {'application': application, 'form': form} return render(request, 'credit_apply/submission.html', context models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth import get_user_model as user_model User = user_model() # Create your models here. class Application(models.Model): """App para las aplicacions de credito""" first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) business = models.CharField(max_length=100) m_number = PhoneNumberField(max_length=16) email = models.EmailField(max_length=254, unique=True) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.first_name} {self.last_name} {self.business}" url pattern path('submission/<int:apply_id>/', … -
how can i filter comments by user and by article with get_context_data Django?
i want to filter the comments by user and by post. would you like to tell me how can i filter the comment using get_context_data. i am getting this error with that code 'NewsDetailView' object has no attribute 'get_object_or_404' how can i solve this issue? models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) commentator = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.article.title views.py class NewsDetailView(LoginRequiredMixin, DetailView): model = Article form_class = CommentForm template_name = 'news/news_detail.html' def get(self, request, *args, **kwargs): self.object = self.get_object_or_404(User, username=self.kwargs.get('username')) self.object = self.get_object_or_404(Article, pk=self.kwargs.get('pk')) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = self.object context['form'] = CommentForm() return context def post(self, request, *args, **kwargs): if request.method == 'POST': form = CommentForm(request.POST) form.instance.article = Article.objects.get( pk=self.kwargs.get('pk')) form.instance.commentator = self.request.user form.save() return redirect('news:news-detail', pk=self.kwargs.get('pk')) else: return redirect('news:news-detail', pk=self.kwargs.get('pk'))