Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static loaded but not used
Nginx web server serves static. Browser downloads static files but they don’t work. Why would that be? Loaded static files docker-compose volumes: django_static: services: nginx: build: context: . dockerfile: ./_nginx/Dockerfile container_name: webserver restart: unless-stopped volumes: - django_static:/app/staticfiles ports: - "80:80" - "443:443" depends_on: - backend backend: build: context: . depends_on: - postgres command: /gunicorn.sh entrypoint: /entrypoint.sh restart: always env_file: .env volumes: - django_static:/app/staticfiles ports: - "${CUSTOM_PORT}:8000" staticfiles config STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] -
How to allow .svg formated file in Wagtail images
I want to upload svg files in Wagtail images. Is it posible to do so. I used "wagtailsvg" but it generate extra table in database not the same image table. So simply I need to allow .svg formated file in images. Any siggestions? -
Problems with Django URL routing
I'm building a website, to be used in dental practices, however I'm having trouble with the URL routing. I'm wanting af URL pattern like: Denthelp/kartotek/#nameofclinic#/opretpatient. My suggestion looks like this: urls.py: path('kartotek/<str:kl_id>/', views.kartotek, name="kartotek"), path('kartotek/<str:kl_id>/opretpatient/', views.opretpatient, name="opret_patient"), Views. py: def kartotek(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) E_patient = kliniknavn.patient_set.all() context = { 'kliniknavn':kliniknavn, 'E_patient':E_patient} return render(request,'DentHelp/kartotek.html', context ) def opretpatient(request, kl_id): kliniknavn = Klinik.objects.get(navn=kl_id) form = PatientForm() if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): form.save() return redirect('kartotek/<str:kl_id>/') context = {'form':form, 'kliniknavn':kliniknavn} return render(request,'DentHelp/kartotek/<str:kl_id>/opretpatient.html', context) When running code I get an OSError for the last line of code shown here. Have you guys have any advise for this to work? -
POST HTML FORM verificaton doesn't work with Django
I am currently learning Django,I connected my register FORM with my views.py, and wrote a little backend code, the problem, is that it links successfully with my .html file, and the POST elements are registering, but as I try to make a verification, (if POST_element < 10), it does nothing. Here is a part of my HTML Register FORM: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form action="{% url 'register' %}" method="POST" class="login100-form validate-form"> {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username"> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> Here is a part of my views.py that manages register: def register(request): if request.method=="POST": username = request.POST["username"] password = request.POST["pass"] password_confirm = request.POST["pass-confirm"] email = request.POST["mail"] if len(username) < 7: messages.error(request,"Username must be more than 10 char.") #Don't get any error else: messages.success(request,"Success") return render(request, 'users/register.html') Here is my urls.py: urlpatterns = [ path('', views.register, name='register'), path('login/', views.login, name='login') ] Thanks for your help! -
How to get data from Django Rest Framework to GoogleMaps in JS
I am trying to build web app which should get data from Django Rest Framework (using Serializer) and pass it to JavaScript and generate markers of GoogleMaps. When I fetched the data from Django API then JS return me 'Promise'. To create markers on GoogleMaps I need GeoJson object. Please for advice where is my mistake. Django serializer: class LocationList(generics.ListAPIView): model = Homes queryset = Homes.objects.all() serializer_class = LocationSerializer API url: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "type": "FeatureCollection", "features": [ { "id": 7, "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 19.2800748, 50.2004355 ] }, "properties": { "property_type": 1, "name": "Zagłoby", "surface": 140.0, "price": 5600000.0, "home_number": "11", "street": "Zagłoby", "post_code": "43-600", "city": "Jaworzno", "country": "Polska", "lat_maps": 50.2004355, "lng_maps": 19.2800748, "add_date": "2022-04-17T15:05:18.274352Z", "active": 2 } }, My JS code: var endpoint = 'api/location' async function getLocalization() { try { const response = await fetch(endpoint); return await response.json(); } catch (error) { console.log(error); } } async function renderLocalization() { let address = await getLocalization(); return address }; function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), … -
Getting a Bad Request when making a POST request in djangorestframework
I'm getting the following error when I try to make a POST request to the server; "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" The request is successful when I POST null content or input in a dictionary, i.e {"content": "Hello world"}. Any kind of help in trying to debug this issue will be greatly appreciated My views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def tweet_create_view(request, *args, **kwargs): serializer = TweetCreateSerializer(content=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) My serializers.py class TweetCreateSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Tweet fields = ['id', 'content', 'likes',] def get_likes(self, obj): return obj.likes.count() def validate_content(self, value): if len(value) > MAX_TWEET_LENGTH: raise serializers.ValidationError("This tweet is too long") return value -
Django query annotate after filter doesn't work correctly
I have two models that are related using a m2m relationship through an intermediate model. The relation field is called participants. When I do this: chats = Chat.objects.annotate(Count("participants")).filter(participants=user) chats.get(pk=11).participants__count It will return 2; which is correct. But when I do this: chats = Chat.objects.filter(participants=user).annotate(Count("participants")) chats.get(pk=11).participants__count It will return 1. And not only for this object for all of the objects in the queryset. What's wrong? what am I doing wrong? I need to annotate a filtered queryset. -
How does "alternates" in the Django site framework work?
I am struggling to get the "alternates" attribute to work in the Django sitemap framework. class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'daily' i18n = True alternates = True def items(self): return ['index', 'about'] def location(self, item): return reverse(item) The documentation appears to suggest the above i.e. setting i18n and alternates to True. But when I do that, my sitemap is literally a plain test string like this: http://127.0.0.1:8000/en/daily0.5http://127.0.0.1:8000/en/about/daily0.5http://127.0.0.1:8000/es/daily0.5http://127.0.0.1:8000/es/about/daily0.5 Whereas it should look like so: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>http://127.0.0.1:8000/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/about/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> </urlset> There are two issues: It doesn't have the correct formatting. What am I doing wrong here? I don't want the 'en' language prefix for the default language. How do I remove this? -
Submit form post from another view with input field
I am relatively new to Django and I'm making a small "social" project. It basically consists of user profiles, and on those profiles you can post "comments". I have a view that displays the comments each user has, and a separate view that allows you to post comments. This works as expected. The problem I am facing right now is the following. - I have an < input type=text > field in the view to view comments, and I want to be able to post a comment from there and have it saved in the database. I have tried grabbing the post kwargs in the form, but I couldn't get it to work correctly nonetheless have it save automatically. How can I get this done? Here is the code that I have so far. Comments view: class CommentsView(auth_mixins.LoginRequiredMixin, views.ListView): model = ProfileComments template_name = 'comments/comments_view.html' paginate_by = 5 def get_queryset(self): receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk']) if receiver: return self.model.objects.filter(receiver=receiver) return None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) receiver = PROFILE_MODEL.objects.get(pk=self.kwargs['pk']) if receiver: context.update({ 'receiver': receiver }) return context View to post comments: class CreateCommentView(auth_mixins.LoginRequiredMixin, views.CreateView): form_class = CommentsForm template_name = 'comments/post_comment.html' @staticmethod def get_profile_model_by_pk(pk): return PROFILE_MODEL.objects.get(pk=pk) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['author'] … -
how to display notification before two days from start date and display notfication on end date using django?
from django.shortcuts import render from app.models import maintenance def notification(request): time_obj = maintenance.time_obj before_two_days = time_obj - datetime.timedelta(days=2) today = datetime.date.today() print('before_two_days',before_two_days) print('today',today) if before_two_days > today: msg = maintenance(start_date=maintenance.start_date,msg = f"Your site will be under construction on {before_two_days}",is_seen=False) msg.save() else: msg = maintenance(end_date=maintenance.end_date,msg = f"Your site will be reopen on {maintenance.end_date}",is_seen=False) msg.save() return render(request,'site.html') -
Can any one help me with import-export-django problem in django
Model.py class Order(models.Model): customerID = models.CharField(max_length=300, blank=True, null=True) osm_bol = models.CharField(max_length=300, blank=True, null=True) ..... ..... def __str__(self): return self.customerID Resouces.py class NewOrders(resources.ModelResource): osm_bol = Field(attribute='osm_bol', column_name='Client Track ID') class Meta: model = Order fields = ('osm_bol') Exel Sheet Column This is the Column that i want to import in my model Problem the problem is i have the column name "Client Track ID" but in my model the name of attribute is "osm_bol" for the same field. when i import the file it shows nothing in "osm_bol" field. i mean its shows empty field. how can i fix it? -
Django template language how to fix
Hi I'm trying to build a simple django app but I can't get index.html file to recognise the variables created in views.py. Nothing I do seems to work. Does it have to be configured somehow in settings.py perhaps? index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Hello world {{ name }}</p> </body> </html> views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = {'name' : 'Peter'} return render(request, 'index.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] Whatever I try, the browser just doesn't recognise anything in the {{}}. It just leaves it blank. I seem to have tried everything. Please help, I'm tearing my hair out. Thanks -
How to get notification when new Article is added to Website?
I have multiple blogging websites made in WordPress. I want to make a website, by which when I add some article on any of these websites, I have to get a notification on website that a new article is added to a particular website. How can I make such a website in Django? -
Can I write posts for a personal Django blog website in static html files?
I'm pretty new to Django and have been experimenting making my own personal blog. General question I get that I can specify my blog post structure in models.py and use the admin site to write my blogs. However, what if I want to write my blogs in raw HTML files stored in, e.g. my-website/blog/posts/<list-of-html-blogs> and then have those files uploaded into the data base and shown on the website. Is there are a standard way of doing this? My initial approach is to create a Python function that reads in the HTML files as strings and uploads those files into the database manually, i.e. using something like blog.models.Post(title=my_title, content=html_as_string). Whenever I'd write a new blog, I'd then call this function to upload a specific html file. However, I have found very little online about whether this is the correct approach. Django blog overview If helpful, I'm showing below what my blog's models.py and views.py currently looks like. models.py from django.db import models STATUS = ( (0, "draft"), (1, "published") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=True) date = models.DateTimeField() content = models.TextField(blank=True) status = models.IntegerField(choices=STATUS, default=0) class Meta(object): ordering = ["-date"] def __str__(self): return self.title … -
About cleaning memory used in GPU with Tensorflow operation
Here is my installed environment, Cuda 10.0 Nvcc Ubuntu 20.04 Python 3.7 Tensorflow 2.0 GPU When I simply run a style transfer code like the code provided here https://www.tensorflow.org/tutorials/generative/style_transfer It runs well if the process is done, but when I try to use Django-q to run it. The GPU memory will be kept even after my style transfer task is done. I have tried the following methods to test if the GPU memory can be released but keep my Django-q working. I manually used the command 'kill -9 ' and restart the Django-q with the command, it worked I ran the commands in Method 1 programmatically, it released the GPU memory but the future style transfer job could no longer reach the GPU. I restarted the server, and used a script to init my Django-q again, it worked but it took time. I used the session cleared method of Tensorflow, but it did not allow my later style transfer job to utilize the GPU. I have the following questions, which will be greatly appreciated if they can also be answered, Why I ran the command programmatically, it cannot utilize GPU for my later style transfer jobs How I can release … -
Should not include "Sunday" in Dates column
views def pendingc(request,userid): userid=userid today = date.today() d=today.strftime("%A") dd = today - timedelta(days = 2) ddd=dd.strftime("%A") r=User.objects.filter(id=userid) engagement=list(r[0].engagement.all().values_list('id',flat=True) ) l=Client.objects.filter(status="Active",Parent__in=engagement) emp=list(Task.objects.filter(project__in=l).values_list('employee_id',flat=True)) u=list(User.objects.filter(id__in=emp).exclude(is_superuser=True).values_list("id",flat=True)) k = list(Task.objects.filter(date__lte=today,date__gte= dd,project__in=l).values_list("employee",flat=True)) res = list(set(u)^set(k)) datas_list = User.objects.filter(id__in=res) page = request.GET.get('page', 1) paginator = Paginator(datas_list, 50) try: datas = paginator.page(page) except PageNotAnInteger: datas = paginator.page(1) except EmptyPage: datas = paginator.page(paginator.num_pages) if request.method=='POST': s=request.POST.get('search') datas_list=User.objects.filter(first_name__contains=s) page = request.GET.get('page', 1) paginator = Paginator(datas_list, 20) try: datas = paginator.page(page) except PageNotAnInteger: datas = paginator.page(1) except EmptyPage: datas = paginator.page(paginator.num_pages) return render(request,"pending_taskc.html",{'userid':userid,'datas':datas,'k':k,'datas_list':datas_list,'s':s,'today':today,'dd':dd,'ddd':ddd,'d':d}) return render(request,'pending_taskc.html',{'userid':userid,'datas':datas,'k':k,'datas_list':datas_list,'today':today,'dd':dd,'ddd':ddd,'d':d}) html <div class="table-responsive"> <table class="table table-stripped table-hover"> <thead> <tr> <th>Name</th> <th>Dates</th> <th>Contact Number</th> </tr> </thead> <tbody> {% for i in datas_list %} <tr> <td>{{i.first_name}}</td> <td>{{dd.day}}&nbsp;{{ddd}} &nbsp;&nbsp;,&nbsp;&nbsp;{{dddd.day}}&nbsp;{{ddddd}},&nbsp;&nbsp;{{today.day}}&nbsp;{{d}}</td> <td>{{i.phone}}</td> </tr> {% endfor %} </tbody> </table> The table is showing all the days but I don't need the sunday in the table.Since sunday is weekend instead I need saturday as the last day.I have the codes for views and html. Someone could help me to correct the error . The output is like Name Dates Contact Number None 24 Sunday , 25 Monday, 26 Tuesday 123 None 24 Sunday , 25 Monday, 26 Tuesday 9744588885 Anushma S 24 Sunday , 25 Monday, 26 Tuesday 6238009232 Akhil Johnson 24 Sunday … -
Serialize a queryset including the ForeignKey values
models.py: class Project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) description = models.CharField(max_length=1000, null=True, blank=True) class ProjectManager(models.Model): name = models.CharField(max_length=250, null=False, blank=False) project_id = models.ForeignKey( Project, on_delete=models.CASCADE ) views.py: def ajax_search(request): if request.method == 'GET': category = request.GET['category'] if category == 'Project': result = Project.objects.all() data = serialize("json", result, cls=DatetimeJSONEncoder) return HttpResponse(data, content_type="application/json") else: result = ProjectManager.objects.select_related('project_id').all() data = serialize("json", result, cls=DatetimeJSONEncoder) return HttpResponse(data, content_type="application/json") return HttpResponse('') return HttpResponse('') I would like to return a json response with the content of ProjectManager + the content of the Project associated to that ProjectManager (ForeignKey). According to what I have read in the Django documentation, to do a left join, the best thing to do would be to use select_related. In fact, it works, but when I serialize ProjectManager, the Project values are not included in the JSON string. How could I put all into the JSON? -
TypeError: get() missing 1 required positional argument: 'path'
I'm trying to write a view test for my index() function, I used TestCase and RequestFactory to perform this test, my test module look like this: from attr import Factory from django.test import TestCase, RequestFactory from solos.views import index class IndexViewTestCase(TestCase): def setUp(self): self.factory = RequestFactory def test_index_view_basic(self): """ Test that index view returns a 200 response and uses the correct template """ request = self.factory.get('/') response = index(request) self.assertEqual(response.status_code, 200) when I tried to run my test I got this error: (JMAD_Project) omer358@OMO:~/PycharmProjects/JMAD_Project/jmad$ python manage.py test Found 2 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .E ====================================================================== ERROR: test_index_view_basic (solos.tests.test_views.IndexViewTestCase) Test that index view returns a 200 response and uses ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/omer358/PycharmProjects/JMAD_Project/jmad/solos/tests/test_views.py", line 15, in test_index_view_basic request = self.factory.get('/') TypeError: get() missing 1 required positional argument: 'path' ---------------------------------------------------------------------- Ran 2 tests in 0.004s FAILED (errors=1) Destroying test database for alias 'default'... -
How can I use an OR-clause with haystack along with a distance filter?
I've been using a distance filter using regular django query filters within an OR-clause: self.filter(Q(location__distance_lt=(geometry, LOCATION_WITHIN_D)) | ~Q(type=Event.IN_PERSON)) I want to do a similar filtering as part of a haystack query, using SQ (queryset = queryset.filter(SQ(location__distance_lt=(geometry, LOCATION_WITHIN_D)) | ~SQ(type=Event.IN_PERSON))) but instead I get back the error: not all arguments converted during string formatting - and that only happens with the distance_lt query part, not the ~SQ(type..) I'm able to do this distance filtering with my search query by using queryset = queryset.dwithin('location', geometry, LOCATION_WITHIN_D) but I want to be able to have that 'or' condition in this sub-clause. Is this even possible without resorting to raw querying? -
AttributeError: module 'collections' has no attribute 'Iterator'
I'm diving into a Django docs and I'm using the latest Django (4.0.4) and Python 3.10.0 Whenever I try the command django-admin startproject mysite it gives the error "AttributeError: module 'collections' has no attribute 'Iterator'" I am using a virtual environment as well which has the Django installed on it. I tried uninstalling the django and reinstalling but no changed in the program.. Please guide me into the right direction. Thank you! -
Django GenericSitemap: Problem with the model
I'm trying to create a Django sitemap with the GenericSitemap function. my urls.py file looks like this: from django.urls import path from . import views from django.views.generic.base import TemplateView from re_analytics.models_new import AnalyticsData from django.contrib.sitemaps import GenericSitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'analytics': GenericSitemap({ 'queryset': AnalyticsData.objects.all(), 'date_field': 'timestamp', }, priority=0.9) } urlpatterns = [ ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] My models_new.py file looks like this: from django.db import models class AnalyticsData(models.Model): index = models.TextField(blank=True, null=False) post_code = models.FloatField(blank=True, null=True) ... Running the app works. I just have trouble accessing the sitemap view. I get the following error message: OperationalError at /sitemap.xml no such column: analytics_data.id Request Method: GET Request URL: http://127.0.0.1:8000/sitemap.xml Django Version: 3.2.5 Exception Type: OperationalError Exception Value: no such column: analytics_data.id Exception Location: /Users/finnj/coding/App1/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/finnj/coding/App1/env/bin/python Python Version: 3.9.6 Python Path: ['/Users/finnj/coding/re_crawler_homepage/re_homepage', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/finnj/coding/App1/env/lib/python3.9/site-packages'] This messages indicates that the column id is not existing in the model. And yes it is not existing there. The 'local var' in the error message indicate the the app is trying to extract this column : sql ('SELECT "analytics_data"."id", "analytics_data"."index", ' '"analytics_data"."post_code",... How does it happen that the id column suddenly … -
Python regex for this type of number (xx-x-xxxx-x), for ex. 21-1-9999-4
Hello devs I want to validate this type of number 21-1-9999-4 using python regex format of regex like(xx-x-xxxx-x) Thanks for advanced -
version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined
import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/init.py", line 24, in version_info, _mysql.version_info, _mysql.file NameError: name '_mysql' is not defined -
AWS ElasticBeanstalk Stripe
I dont have a domain and i didnt configured my SSH(which i don't know what it's) I deployed Utilizing Elastic Beanstalk on local its working just fine, but deployed i cant load the stripe. Im utilizing live keys error: Uncaught IntegrationError: Live Stripe.js integrations must use HTTPS. For more information: https://stripe.com/docs/security/guide#tls at e.value ((index):1:312510) at new e ((index):1:281123) at No ((index):1:314058) at create:303:20 what can i do to correct this? -
How to put a constraint using foreign key fields in Django?
Consider following models: class Model1: x = an integer y = an integer class Model2: f1 = models.ForeignKey(Model1) f2 = models.ForeignKey(Model1) Now, I want to put a constraint on model 2 such that no duplicate pairs of f1.x and f2.x get inserted in model 2. How should I achieve it? I will be populating model 2 using bulk_create so maybe customising clean() or save() won't work. I'm new to Django and not able to figure it out. Any help will be appreciated.