Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why sites served with nginx have no styling applied
I try to put build of react app on localhost/ using nginx. As far as i understand this, i need to build app with "npm run build" and then serve build dir with static content. After many hours i managed to get it into work with docker and my django service as a api under localhost/api/. But what is not working is css and js on this sites. On any page neither is it react or django endpoints there is only raw html with attached css but not working. After many attempts with changing configs etc. I ended with same raw html. Why on nginx there is no styling on sites even if with inspecting these pages there is linked css to them. This is my nginx.conf http { server { listen 80; listen [::]:80; root /var/www/html; server_name localhost; index index.html index.htm; location /api/ { proxy_pass "http://web:8000/"; } location / { include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { root /var/www/html; expires 1M; access_log off; add_header Cache-Control "public"; } } } This is part of docker-compose nginx: image: nginx:latest ports: - 80:80 - 443:443 volumes: - ./nginx_conf/:/etc/nginx/ - ./frontend/build/:/var/www/html/ depends_on: - web When i run this app … -
How to create a user voter to vote for one single choice in a poll in Django
class Poll(models.Model): question = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) expire_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(max_length=100) def _get_unique_slug(self): slug = slugify(self.question) unique_slug = slug num = 1 while Poll.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self._get_unique_slug() super().save(*args, **kwargs) def __str__(self): return self.question class Meta: ordering = ('-pub_date',) class Choices(models.Model): poll = models.OneToOneField(Poll, related_name='choices') choice_text = models.CharField(max_length=200) voter = models.OneToOneField(User, on_delete=models.CASCADE, related_name='voters', blank=True, null=True) vote_count = models.PositiveIntegerField(default=0) def __str__(self): return self.choice_text def save(self, *args, **kwargs): self.vote_count += 1 super().save(*args, **kwargs) class Meta: pass # order_with_respect_to = 'poll' It doesn't allow user to vote more than one poll. and if I change it to voter = models.Foriegnkey(User, on_delete=models.CASCADE, related_name='voters', blank=True, null=True) It allows users to vote more than a single option in a poll which is not the intended behaviour. I will appreciate if I can't get help to fix this. Thank you. -
Page not found (404) after running the url of API
I have an django app,But i want to make its API so just i created it after runing the server Page not found (404) But my django app is running,After the running the url of API i got the error of Page not found views.py from django.http import Http404 from django.shortcuts import render from django.views.generic import ListView,DetailView from .models import List from django.http import HttpResponse,JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from List.serializers import ListSerializers class MainListView(ListView): queryset = List.objects.all() # temp = List.objects.all() template_name = "main_list.html" def get_context_data(self, *args, **kwargs): context = super(MainListView, self).get_context_data(*args, **kwargs) context['temp'] = List.objects.all() return context class MainListView(ListView): queryset = List.objects.all() # temp = List.objects.all() template_name = "List/list.html" def get_context_data(self, *args, **kwargs): context = super(MainListView, self).get_context_data(*args, **kwargs) context['temp'] = List.objects.all() return context class MainDetailSlugView(DetailView): queryset = List.objects.all() template_name = "news/detail.html" @csrf_exempt def list_list(request): if request.method == 'GET': queryset = List.objects.all() serializer = ListSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ListSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def list_detail(request, pk): try: list = List.objects.get(pk=pk) except List.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ListSerializer(list) return JsonResponse(serializer.data) elif request.method … -
Error on dynamic link libraries (dll) when using GDAL of OSGeo4W in Django
I'm trying to install GeoDjango in my Django project and got weird errors with GDAL. Following Django documentation, I installed GDAL, GEOS, PROJ using OSGeo4W64, for specific, these are packages I selected to install on OSGeo4W64 setup: gdal v2.3.2-2 geos v3.7.0-1 proj v5.2.0-1 I also set my environment variables as documented. When I started my Django project (using runserver), python tried to look for gdal202.dll and raised error Entry Point Not Found: The procedure entry point sqlite3_column_origin_name could not be located in the dynamic link library ...\osgeo4w64\bin\gdal202.dll And one more error with libcurl.dll (installed by OSGeo4W as dependencies): The ordinal 361 could not be located in the dynamic link library ..\osgeo4w64\bin\libcurl.dll I fixed the first error by download latest curl Windows binary version and replaced the existed on in OSGeo4W but still can not figure out how to solve the first error. As the error said, it seemed that there were some code require for sqlite3_column_origin_name function in gdal202.dll. In addition, OSGeo4W also install sqlite3 as dependencies in its bin directory, and I also checked the dll too, it did contain an entry point for function sqlite3_column_origin_name. So it seemd that the entry point sqlite3_column_origin_name was required directly from gdal202.dll, … -
DRF post request multiple inner serializers
i have three models named Smoker,Switch,Survey i have smoker as foreign key in Switch model and switch as foreign key in Survey model class Smoker(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) mobile = models.IntegerField(null=True, blank=True) gender = models.BooleanField(blank=True, null=True) age = models.ForeignKey(Age,models.DO_NOTHING,blank=True, null=True) occupation = models.ForeignKey(Occupation, models.DO_NOTHING, blank=True, null=True) class Switch(models.Model): time = models.TimeField(blank=True, null=True) count_outers = models.IntegerField(blank=True, null=True) count_packs = models.IntegerField(blank=True, null=True) smoker = models.ForeignKey(Smoker, models.DO_NOTHING, blank=True, null=True) new_brand = models.ForeignKey(NewBrand, models.DO_NOTHING, blank=True, null=True) new_sku = models.ForeignKey(NewSku, models.DO_NOTHING, blank=True, null=True) # def __str__(self): # return self.time.strftime("%H:%M") class Survey(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True) date = models.DateField(null=True, blank=True) bool_switch = models.BooleanField(null=True, blank=True) reason = models.ForeignKey(Reason, models.DO_NOTHING, null=True, blank=True) shift = models.ForeignKey(ShiftingTime, models.DO_NOTHING, null=True, blank=True) current_brand = models.ForeignKey(CurrentBrand, models.DO_NOTHING, null=True, blank=True) current_sku = models.ForeignKey(CurrentSku, models.DO_NOTHING, null=True, blank=True) pos = models.ForeignKey(Pos, models.DO_NOTHING, null=True, blank=True) switch = models.ForeignKey(Switch, models.DO_NOTHING, null=True, blank=True) and here i have my serializers: class SmokerSerializer(serializers.ModelSerializer): class Meta: model = Smoker fields = '__all__' class SwitchSerializer(serializers.ModelSerializer): smoker = SmokerSerializer() class Meta: model = Switch fields = '__all__' def create(self, validated_data): smoker_data = validated_data.pop('smoker', None) if smoker_data: smoker = Smoker.objects.create(**smoker_data) validated_data['smoker'] = smoker class SurveySerializer(serializers.ModelSerializer): switch = SwitchSerializer() class Meta: model = Survey fields = '__all__' … -
Slow down the rate of requests in Vue.js updated method in Django web application
I have a Vue.js view in a Django template. Vue pulls the data to display in the view from a Django Rest Framework endpoint. My code follows: const app = new Vue({ el: '#app', delimiters: ["[%", "%]"], data: { dedicated_server: [], }, created() { fetch('/api/dedicated-server/{{ object.id }}/') .then(response => response.json()) .then(json => { this.dedicated_server = json; }) }, updated() { /* TODO: Try and limit the number of requests to the API */ fetch('/api/dedicated-server/{{ object.id }}/') .then(response => response.json()) .then(json => { this.dedicated_server = json }) }, }); As you can see I have an updated method which polls the Restful endpoint to update the page if the data changes. This all works fine but it seems to poll the Restful API endpoint about 3 to 5 times a second. This is fine in development but if I have 100 people visiting this page then it is going to kill my server with requests. Is there a way to limit the number of times Vue.js checks to see if the data has been updated? It would be great if you could say check once every 5 seconds. -
How to restrict edit link being shown in template, based on whether the current user is the owner of a blogpost?
I am new to Django and attempting to create a a test blog. Everything is working except I cannot restrict the editing of a blog post to the blog post's owner. My first attempt was successful, but all I did was "Raised 404" in the view function after comparing whether, or not, the current user was the same as the blog post's owner. My second attempt involved adding a comparison in the template. But, all that did was remove the edit link for all users, even the owner. The template code is below. {% extends "blogs/base.html" %} {% block content %} <h3>My Posts</h3> <p> <a href="{% url 'blogs:new_blogpost' %}">Add a new blog post:</a> </p> <ul> {% for blogpost in blogposts %} <li><strong>{{ user.username }} : {{ blogpost.owner }}</strong> <br> <strong>{{ blogpost.title }}</strong> - {{ blogpost.date_added }} <br> {{ blogpost.text }} <br> <p> {% if user.username == blogpost.owner %} <a href="{% url 'blogs:edit_blogpost' blogpost.id %}">edit blog post</a> {% endif %} </p> </li> {% empty %} <li>No posts have been added yet.</li> {% endfor %} </ul> <a href="{% url 'blogs:new_blogpost' %}">Add a new blog post:</a> {% endblock content %} Note, I am using Django 1.8. And, for testing purposes, I included both … -
Django: how to log every app to a separate file
i've my log definition as below: LOG_DIR = '/var/log/myapp/' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.NullHandler', }, 'logfile': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/application.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': False, }, '': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } Now, i have several applications in this project, and i have to organize the logging of them in a simple way, creating a separate log from each other, i mean: Project general logs My_App1 logs My_App2 logs My_App3 logs Is this possible in a easy way with Django? -
Django ForeignKey Constraint Failed error
I am creating a simple blog site with multi-user facility using django framework. In my project, If the admin deletes any user, all of that user's blogs should not be deleted, I've tried using models.ForeignKey(django.contrib.auth.models.User,on_delete=models.CASCADE) but it obviously deletes all the blogs if the admin deletes the user. Can anyone help me please? Thank in advance... -
Django csrfmiddlewaretoken shown as hidden input tag in browser
I have {% csrf_token %} in my html file form. It renders nicely. But when I click on view source in a browser it shows as <input type="hidden" name="csrfmiddlewaretoken" value="SkXIYIpbfiaGWZImnFHoiausd3Q0NK098qw1MgrJ54f55nmG7VXrnHqSpsw9yU8C"> Is this safe for anyone to be able to access csrfmiddlewaretoken value? I am currently on development server provided by Django. Thanks -
ValueError: Cannot use object with type datetime for a spatial lookup parameter
During makemigrations it's okay but when i'm gonna migrate here title exception raised. models.py from django.contrib.gis.db import models class Restaurant(models.Model): restaurant = models.CharField(max_length=254) rating = models.FloatField() type = models.CharField(max_length=254) cuisines = models.CharField(max_length=254) cost = models.CharField(max_length=254) address = models.CharField(max_length=254) features = models.CharField(max_length=254) latitude = models.FloatField() longitude = models.FloatField() point = models.PointField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.restaurant Not only Pointfield. That exception raised in case too MultiPolygonField, MultiPointField and such like this field. -
How to get the currently logged in user (from auth) and display his name on the post
How can I get the Username and save it to auhtor model in discussion and then display it in template. i tried a few things but it doesn't work. Any help is appreciated. thanks models class Discussion(models.Model): author=models.CharField(max_length=15,null=True) title=models.CharField(max_length=50) argument=models.CharField(max_length=350) slug=models.SlugField(max_length=31,unique=True) created_on=models.DateField(auto_now=True) def get_absolute_url(self): return reverse('discussion_detail',kwargs={'slug':self.slug}) def __str__(self): return self.title Form class DiscussionForm(forms.ModelForm): class Meta: model=Discussion fields=['title','argument','slug'] Views: class NewDiscussionView(LoginRequiredMixin,View): template_name='Discussion/new_discussion.html' form_class= DiscussionForm def get(self,request): return render(request,self.template_name,{'form': self.form_class()}) def post(self,request): bound_form = self.form_class(request.POST,instance=request.user) if bound_form.is_valid(): new_discussion=bound_form.save() return render(request,'Discussion/discussion.html',{'discussion':Discussion.objects.all()}) else: return render(request,self.template_name,{'form': bound_form}) -
How to look up with foreing keys?
I'm starting with Django and I want to get the movies that have a better rating score and I don't know how to find a way using my model state. Now there are my classes: class Movie(models.Model): movieId = models.IntegerField(unique=True) title = models.TextField(max_length=100) anno = models.IntegerField() imdbId = models.IntegerField(unique=True) tmdbId = models.IntegerField(unique=True) def __str__(self): return self.title class Rating(models.Model): rating = models.IntegerField() timestamp = models.IntegerField() user = models.ForeignKey(User, on_delete = models.CASCADE) movie = models.ForeignKey(Movie, on_delete = models.CASCADE) def __str__(self): return str(self.user)+"--"+str(self.rating) -
Building my django project with Centos7 + virtualenv + apache2
It goes nothing wrong when I run ./manage.py runserver 0.0.0.0:8000. But I came across weird errors when launching them with virtualenv and apache2. And there seems to be nothing wrong in the error_log. enter image description here It has confused me for a long time. I would be highly appreciated if I can get your help! -
I have an "empty path didn't match any of these" error after apllying the django toturial, is the problem in my computer siitting
I have an "empty path didn't match any of these" error after apllying the django toturial , is the problem in my computer siitting ? page not found mysit urls polls urls views sitting -
How to write view to update model image in django?
Now I extends the django User model with profile model. I want add update user's profile function. Because I make the num field as the unique field, So in my update view function, the update form's is_valid was always False, and I also cannot update the photo png? Those are my codes. What should I do to solve this problem? Models: class Profile(models.model): user = models.OneToOneField(User,on_delete=models.CASCADE) num =models.CharField('identity',max_length=254,unique=True) photo = models.ImageField('image',upload_to = 'images/licences') forms: class ProfileForm(forms.ModelForm): class Meta: model= Profile fields = ['num','photo'] views: def modify_view(request): user = request.user if request.method=="POST": form = ProfileForm(request.POST,request.files) if form.is_valid() user_profile = Profile.objects.get(user=user) user_profile.image = form.clean_data['image'] user_profile.save() else: form = ProfileForm() return render(request,"profile.html",{form:form}) -
Emulate file upload from a form from code
This is probably trivial but I am unable to find a solution. Here are my models.py and forms.py models.py class FileModel(models.Model): file = models.FileField(blank=False, upload_to='/xyz/') forms.py class FileModelForm(forms.ModelForm): class Meta: model = FileModel Now I want to create an instance of this model (using the form) from the shell. Assume my file is currently located in media/test_files/x.txt These are the things that I have already tried : ins = FileModelForm(data={'file':'/test_files/x.txt'}) ins = FileModelForm(data={'file':'/media/test_files/x.txt'} ins = FileModelForm(data={'file':os.path.join(settigs.MEDIA_ROOT,'test_files/x.txt') f = open(os.path.join(settings.MEDIA_ROOT, 'test_files','x.txt') ins = FileModelForm(data={'file':f} In all these above cases, ins.is_valid() returns False How do I do this? -
How to add if function in django html template
I want to add one if function in html template of my django project. If the variables datas is null, it will show the text "The results is null", if the variables datas is not empty, it will show the table for the data in datas. Here's what I write, but it keeps show that "Invalid block tag on line 13: 'if(isEmpty($('#datas')))', expected 'endblock'. Did you forget to register or load this tag?" How could I deal with it? {% if(isEmpty($('#datas'))) %} <h3>The results is null.</h3> {% else %} <table style="table-layout:fixed;"> <tr>...</tr> <tr> {% for i in datas %} <td>{{ i.1 }}</td> </tr> {% endfor %} </table> {% endif %} -
Django: When to use UUID?
I know this question is the one someone already asked but I really don't understand when I should use UUID. I just started to try to bulid REST API in Django. And I've read we should use UUID but I don't understand how to use it. For example, I currently use id to refer to a specific object in api views as I write in usual views.py. Is it what I should not do? If so, how users can refer to a object using UUID? When is it used? @api_view(['GET', 'PUT', 'DELETE']) def specific_entry(request, pk, format=None): entry = get_object_or_404(Entry, id=pk) ... -
restframework-jwt not working with manual model class
I have only beginner level idea about django restframework-jwt. When i try to authenticate with my custom model class it showing "non_field_errors": [ "Unable to log in with provided credentials." ] But I can generate token with "auth_user" table data model.py contain users class & user_manager settings.py INSTALLED_APPS = [ 'rest_framework', 'rest_framework_jwt', 'rest_framework.authtoken', ] AUTH_USER_MODEL = '**app_name**.Users' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } JWT_AUTH = { 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', } -
Can't connect to localhost using mysql
I am new to Django and mysql and I am trying to configure my django application's backend to mysql. I am using XAMPP for my local mysql database and anaconda as my pkg manager. Also using a conda virtualenv. When I go to run python3 manage.py migrate, I get this error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' (61)") My database is setup as the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'exampleproject', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '', } } I changed 'HOST' to 'localhost' but then get this error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") Any help is appreciated! -
Why doesn't jinja re-render my template after a successful Ajax POST operation
I am told that the success of AJAX function is responsible for doing everything after sending the data, including updating the page to show any data sent by the backend in response to the post. When I printed the success: function(res){ console.log(res) } I am able to see my newly generated HTML in the console log where the HTML DIV is populated where I had the Jinja FOR loop. <div id="RIGHTCONTAINER" class="list-group" style="height:625px; overflow-y: scroll"> {% for model in model_list %} <a href="#" data-set="{{ model_list|length }}" class="list-group-item py-0 list-group-item-action">{{ model }}</a> {% endfor %} </div> I am surprised that console.log is able to see the returned data, render generated html, but it is now up to me somehow to display that in the browser if when I am using ajax. I was however able to print my content using ajax BELOW METHOD but this is NOT not ideal for me, (because I have additional functions I need to call for operations upon list-group-items inside my RIGHTCONTAINER, which will become multiple nested ajax requests inside my ajax success function, and I found myself worked into a corner). $.ajax({ type:'POST', url:"home/view_results/onclick/", data:{ selected_item:item_index, // Sending users selection csrfmiddlewaretoken:"{{ csrf_token }}" }, dataType:"text … -
Java ZonedDateTime.toInstance() behavior
I'm seeing a discrepancy whereby this: ZonedDateTime.now(ZoneId.of("America/New_York")).minusDays(30) returns (correctly): 2018-11-07T22:44:11.242576-05:00[America/New_York] whereas conversion to an instant: ZonedDateTime.now(ZoneId.of("America/New_York")).minusDays(30).toInstant() seems to mess up the result by adding an extra day to it: 2018-11-08T03:58:01.724728Z I need an instant conversion to use the result in the following code as Date: Date.from(t.toInstant()) An equivalent Python code (Django) works correctly: datetime.datetime.now(TZ)+datetime.timedelta(days=-num_days) evaluating to: datetime: 2018-11-07 20:13:55.063888-05:00 -
Django: Video can play in Chrome, but not Safari
I have an issue about Video in Django. This is my URL: https://api.feedtrue.com/vd/39/21_39_37957721_276811923114866_7425040007062093824_n.mp4 When I open this URL by Google Chrome browser, it works normally, but when I use Safari browse, this video doesn't load and I don't know the reason. This is the screen of Safari browser, which doesn't load this video. I read about byte-range and apply this package: Django Ranged Response but it doesn't work too. Please give me advice about this issue. Thanks in advance! -
Django: Check if a foreign key field has been loaded
I have two django models class ValidName: name = models.TextField() class MetaSyntacticName(ValidNames): name = models.ForeignKey(ValidName) usages = models.IntegerField() If I have an instance of MetaSyntacticName, can I find out if the ValidName instance it's name references has been loaded from the database without a database query?