Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Backend is not taking styles, images, etc
I make a project, backend is make in python/django and frontend is make in React. I already finish and I make a npm run build:prod to make a umd.js and umd.js.map. I upload that files to my backend folder /static/js, but there is not styles or images when I deploy my backend server. -
how to use CASE when then in sql?
i have an sql query that crash the program i want to check if the field contain 0 or 1 so i used : query = cursor.execute('select ID, CASE WHEN status = 1 THEN "GOOD" WHEN status = 0 THEN "BAD" END AS status FROM Person') the error is below : invalid column name "GOOD" invalid column name "BAD" -
Heroku Deployment: Scaling dynos... ! ▸ Couldn't find that process type (web) error - Django Application
I keep getting the following errors when trying to deploy my django application to Heroku. Scaling dynos... ! ▸ Couldn't find that process type (web) error heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=abc123.herokuapp.com dyno= connect= service= status=503 bytes= protocol=https heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=abc123.herokuapp.com dyno= connect= service= status=503 bytes= protocol=https -
Django- Why I am getting this Programming Error
Django- Why I am getting this Programming Error When I have not declared shop_product variable anywhere . Please help Click here to view error Image please refer to this image of error -
Local variable unreferenced in decorator definition
My code is behaving weird, and I can't get why. Here is the code: # 1) The decorator urlpatterns = [] def route(url, name=""): def dec(f): print("NAME:", name) urlpatterns.append( path(url, f, name=name) ) return f return dec # 2) The decorator call @route("/my_function") def my_function(): print("Hello world") I get an UnboundLocalError on name File "urls.py", line 10, in dec if name == "": UnboundLocalError: local variable 'name' referenced before assignment name should be set to "" by default, I don't understand where the problem is. The weird thing is if I run the same code and change the decorator to this: urlpatterns = [] def route(url, name=""): def dec(f): if name == "": print("I work!") urlpatterns.append( path(url, f, name=name) ) return f return dec It works perfectly and output: I work ! while the problem was supposed to come from the line if name == "" PS: I'm programming on django, this line is in the urls.py file. -
Django models timestamp in MYSQL Db
I want to store time as unix timestamp in my MYSQL database, I have django project with model: date = models.DateField() But I didn't find any models.Timestamp() or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now. -
How to combine AJAX + view function (API call) + url mapping the smart way?
I have a Javascript/AJAX function that assigns the team_id of a soccer team to a variable on 'click' of the teams name in the sidebar (see below for a screenshot). This variable shall then be used to make the according API call to get fresh data to update the dashboard as requested. The web application/dashboard is Django based. The Javascript itself assigns the variable smoothly and the views function itself fetches data from the API as well (when using a fix API URL without the assigned variable). To make this thread a future guidance for similar issues, i divided the content in different questions and tried to present it as neat as possibe. 1.) Now when I want to combine these steps i always end up with a TypeError (because the API call doesn't return any data) since the views function seems not to use the assigned variable 'team_id' within the API url (the team_id is emtpy when debugging = no API data in return). Why is that? 2.) I also tried to change the logic of the url mapping that way (which I would prefer) that there is only one url e.g. www.dasocc.com to display the dashboard and the … -
Using django url tag inside jquery ajax
I am building a page which holds some categories and when user clicks on a link, then I go ahead and fetch the details for that specific category (products of that category). The way to do this, I thought, was to use jQuery Ajax. Anyway, the part where i append my data is like this: ... $.ajax({ ... success: function(results) { $("#cards").empty(); for (let iterator = results.length -1; iterator>=0; iterator--) { $("#cards").append( '<a href="{% url "product" '+results[iterator].id+' %}">' +'<div>' + '<div class="card mb-5 shadow-sm">' + '<img class="card-img-top"' + 'src="'+results[iterator].image+'" />' + '<div class="card-body">' + '<h5 class="card-title">'+results[iterator].name+'</h5>' + '<p class="card-text">'+results[iterator].price+'</p>' + '</div>' + '</div>' +'</div>' +'</a>' ); } }, ... }); ... Based on this block of code, i get this error: Reverse for 'product' with arguments '('+results[iterator].id+',)' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$'] Since i get the results in form of json i don't have a problem with using it the way i did, but the problem rises when adding the a tag around my container div. I don't understand what course of action I should take since i'm not really experience with neither Django nor jQuery. -
Django + nginx + gunicorn not serving static files
Sorry for kind of repeating question, I know that similar questions has been asked before, but none of them helped to find solution. I am very new to whole web development thing and been struggling with this problem for couple of days now. My website do not show static files then I turn off debug mode. To my understanding that's why i should use nginx. I configured everything according to this guide. Following guide I put my static files into /opt/myenv/static/ directory. Done collectstatic command, created symbolic link (to my understanding), restarted nginx but still if I turn off debugging I see no static files served. My nginx config: server { server_name stvskaiciuokles.eu; access_log off; location /static { alias /opt/myenv/static/; } location /media { alias /opt/myenv/STV_skaiciuokle/skaiciuokle_web/media/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded_Host $server_name; proxy_set_header X-Real_IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } My settings.py relevant part: STATIC_URL = '/static/' STATIC_ROOT = '/opt/myenv/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Please help me determine what is wrong, since I cannot find any suitable solution despite reading multiple similar questions online? Guide I used is from 2013 maybe syntax changed a … -
django uwsgi - "No module named 'project'"
I'm trying to set up a Dockerised django/uwsgi stack. When I start the containers, uWSGI logs a "ModuleNotFoundError: No module named 'project'". I'm obviously doing something dumb, but I can't see what. Following the guide here, my dir tree looks like: mysite docker-compose.yml manage.py project __init__.py urls.py wsgi.py settings __init__.py base.py local.py The django docker container mounts the entire mysite dir as /mysite. My uwsgi INI file contains: chdir = /mysite/project module = project.wsgi:application env = DJANGO_SETTINGS_MODULE=project.settings.local (I've also tried with chdir = /mysite) What simple and obvious mistake am I making here? -
Foreign key issue in UserProfile django
I want to retrieve User profile data of User who is logged in. e.g. Based on logged in user I want to retrieve the country of the user from userprofile. Seems straightforward but I am missing some fine print. Tried a lot but no success. Need help. I tried and referred django document but I am a newbie I am having following model. class User(AbstractUser): username = models.CharField(max_length=100,blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) title = models.CharField(max_length=5) dob = models.DateField() address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) photo = models.ImageField(upload_to='uploads', blank=True) -
django - upload file to folder and show the current logged in username in the uploadform
I have a userprofile that captures the username and the group the user is assigned to. I want the uploaded files to be saved under the group name folder. The folders already exit at the media root, the files shoud be routed to these folder I solved the problem by the solution given. Now the username is shown as a dropdown list on the upload page. I want only the logged it username to be shown or exclude even showing it models.py class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username') tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") # validators=[FileExtensionValidator(allowed_extensions=['tar', 'zip'])] def __str__(self): return self.request.user.username class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username view.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') forms.py class uploadmetaform(forms.ModelForm): count = Metadataform.objects.all().latest('id').id #To know the id of latest object data = Metadataform.objects.all().filter(id=count) #return the queryset with only latest object path = forms.ModelChoiceField(queryset=data) def __init__(self, *args, **kwargs): super(uploadmetaform, self).__init__(*args, **kwargs) count = Metadataform.objects.all().latest('id').id data = Metadataform.objects.all().filter(id=count) self.fields['path'] = forms.ModelChoiceField(queryset=data) class Meta: model = uploadmeta … -
Making a Page in Django to render data from API?
I Have a problem statement where i have a RShiny Code and i have converted it into an API using Plumber . I want to create page in django which should take input from user and then hit that pi hosted and display the rendered JSON output from that api. Can anybody guide me what should i go forward to do this ? -
How to find area of Polygon intersection to annotate GeoDjango query?
In my model, I have a Polygon Field. In my query, I would like to compute the area of the intersection between this field, and a predetermined circle, in order to find the proportion of the circle's area that is recovered by my Polygon model field. Here is my model definition: class WDPA(models.Model): site_code = models.CharField(max_length=200, primary_key=True) site_name = models.CharField(max_length=300) iucn = models.IntegerField(default=0) geom = models.MultiPolygonField() Here is my query: tile = Tiles.objects.filter(start_long__gte=float(form.cleaned_data.get("latitude")), end_long__lte=float(form.cleaned_data.get("latitude")), start_lat__lte=float(form.cleaned_data.get("longitude")), end_lat__gte=float(form.cleaned_data.get("longitude")) )[0] tiles = [tile.tile_id, tile.near_0, tile.near_1, tile.near_2, tile.near_3, tile.near_4, tile.near_5, tile.near_6, tile.near_7] center = Point(float(form.cleaned_data.get("longitude")), float(form.cleaned_data.get("latitude")), srid=4326) circle = center.buffer(0.01802) zones = WDPA.objects.filter(tiles__in=tiles).annotate( distance=Distance('geom', center) ).order_by('distance').filter(distance__lte=2000).annotate( intersection=ExpressionWrapper(F('geom'), output_field=PolygonField()).intersection(circle).area ) But I can't call .intersection() method, it causes this error: AttributeError: 'ExpressionWrapper' object has no attribute 'intersection' I also tried to use an Intersection object, but I can't call the area either in my annotate. Does someomne as a solution please ? Thanks in advance -
Django-money. When display in template it's showing wrong format of currenncy
I have a problem with displaying currency by django-money module. In template I used 2 options: {{ object.balance }} and {% money_localize object.balance %}. I expected to see on website $100.00, but I got US$100.00. Any ideas, why it's display this way? My model class has field: balance = MoneyField(_('Balance'), max_digits=25, decimal_places=2, default=Money(0, "USD")) -
Django annotate first occurrence of x in sorted queryset
I have a queryset where the owner's objects are displayed first then objects not owned by them are followed. MyModel.objects.annotate( sort=Case( When(owner=self.request.user, then=0), default=1, output_field=IntegerField() ) ).order_by('sort', 'name') Now if that produced the following, how can I annotate the first occurrence that the owner is not the request user so that obj_list[2]['first_occurrence'] = True? obj_list = [ {'owner': 1, 'name': 'B', 'sort': 0}, {'owner': 1, 'name': 'D', 'sort': 0}, {'owner': 6, 'name': 'A', 'sort': 1}, ... ] Alternatively is there a way to get the first occurrence (without regrouping) where request.user != obj.owner so that I can insert an extra table row? {% for obj in obj_list %} {% if obj.first_occurrence %} ... {% endif %} ... {% endfor %} -
Unabe to make migrations to herokuapp: No module named 'django-heroku'
After finally deploying my app to heroku I wanted to make migrations to my postgres database. I ran into a curious error: (movie_app) ejan@linux-nr9m:~/github/Moviebase-web-app> heroku run python manage.p makemigrations Running python manage.py makemigrations on ⬢ rate-star-movies... up, run.2515 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 15, in check_all_models models = apps.get_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 178, in get_models self.check_models_ready() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all for alias in self: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in … -
Django Elasticsearch results highlighting problem
I'm making a site, almost finished and I have implemented the basic search into my site using Elasticsearch (5.6) and Haystack. I followed the tutorial, built the indexes connected everything and the search is working. Now I would like to highlight the search results with the query word. ( so if the word is Batman, I would like all instances of the word Batman to be highlighted on the page ). I read through elasticsearch documentation ( https://www.elastic.co/guide/en/elasticsearch/reference/6.4/search-request-highlighting.html ), and there I found examples like: GET /_search { "query" : { "match": { "content": "kimchy" } }, "highlight" : { "fields" : { "content" : {} } } } I'm still not sure how is this supposed to work, I have been searching since yesterday. I downloaded postman and tried getting this to work using that, but honestly I got no idea what I'm doing. Anyone kind enough to point me to some docs or help me out with that one, I really can't seem to work out how is that supposed to work :( Next, after failing with that, I tried this : https://django-haystack.readthedocs.io/en/v2.4.1/highlighting.html The problem here is that I get an <form class="search" method="get"> <i class="fa fa-search search-icon"></i> … -
Unable to run Python Django Oscar sandbox website on Windows
I wanted to learn how to use Django and Oscar to create an e-commerce website. I was initially trying to follow some tutorials but almost all of them use some old version. Finally, I tried to follow the official documentation. The only problem is that the instructions on the website seem to be for Linux. (https://django-oscar.readthedocs.io/en/2.0.2/internals/sandbox.html). Here are my commands I wrote in the terminal: git clone https://github.com/django-oscar/django-oscar.git cd django-oscar virtualenv oscar oscar\Scripts\Activate These commands seem to have created all the folders. However, make sandbox sandbox/manage.py runserver throws an error about the make not being recognized. I installed MinGW on my Windows but this did not seem to make any difference. If I try to run the manage.py runserver command directly. cd sandbox manage.py runserver I get the following error: ModuleNotFoundError: No module named 'django' How can I get the sample Django Oscar project to run? Thanks. -
Strange Bug : List.append in Python erasing precedent input and cloning the new one instead each
Ok I have been working many times with list in python and it s the first time I encounter this problem : Near the strange place I've got this ( simplified ) list = [] dict = {} things = {'1':'Am', '2':'I', '3':'Dumb?'} [...] for key,value in things.items(): if value: dict[key]=value print(dict) list.append(dict) print(list) And get the this result : {'1':'Am'} [{'1':'Am'}] {'2':'I'} [{'2':'I'},{'2':'I'}] {'3':'Dumb?'} [{'3':'Dumb?'},{'3':'Dumb?'},{'3':'Dumb?'}] hinhin, someone have ever get this ? I, m stuck, thank iou :) -
Saleor comes with react by default. Can we have a 'basic' Saleor without frontend frameworks?
I wanted to use Saleor for a "single-type-product" e-commerce website. I installed Saleor yesterday but it has a huge requirements file, including react.js and many other frontend stuff. I don't want them. Is it possible to install Saleor without anything else? Or at least, with the least other requirements? -
Creating own ordering class
I need to order all stories by popularity(rating field), lass added(created_at field) and by genres(genre field(Foreign key)). Now it only works for last added, how can I add two more order in my CustomOrdering class? class CustomOrdering(OrderingFilter): allowed_filters = ['top', 'new', 'genres'] def get_ordering(self, request, queryset, view): params = request.query_params.get(self.ordering_param) if params: fields = [params.strip() for param in params.split(',')] ordering = [f for f in fields if f in self.allowed_filters] if ordering: return ordering return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: ordering = ['-created_at'] if ordering: return queryset.order_by(*ordering) return queryset class StoryView(viewsets.ModelViewSet): queryset = Story.objects.all() serializer_class = StorySerializer filter_backends = (CustomOrdering, ) -
django template issue with django admin
from .models import Info from django.forms import ModelForm class NewInfo(ModelForm): class Meta: model = Info #fields = ('first_name', 'last_name', 'address') exclude = () -
Django HTML form input to db.sqlite3
I'm making a simple web server to take html input data and insert it to data base table . I've tried with POST request got into more CSRF troubles , Turned to GET request to go over CSRF (not necessary in my case ) , still not able to make it . myapp/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=300, unique=True) content = models.TextField() myapp/templates/createpost.html <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action="" method="GET"> {%csrf_token%} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> myapp/views.py from django.shortcuts import render from .models import Post def createpost(request): if request.method == 'GET': if request.GET.get('title', None) and request.GET.get('content', None): post = Post() post.title = request.GET.get('title', None) post.content = request.GET.get('content', None) post.save() return render(request, 'createpost.html') else: return render(request, 'createpost.html') am using Django 2.2.6 with PyCharm community 2019.2.3 I've been searching for almost 2 days , checked django doc , and stackoverflow answers , none was helpful , I had to ask to make sure its not a version related issue and forgive me if i miss understand a simple point am just a beginner. -
How to validate username in django forms?
Here I am trying to validate username and email in my forms but validating username is not working. But validating email is working fine. How can I validate username here? forms.py class RegisterUserForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email__iexact=email).exists(): raise ValidationError('Sorry this email address already exists.') return email def check_username(self): username = self.cleaned_data['username'] if len(username) < 6: raise ValidationError('Username must be 6 characters long.') return username class Meta: model = User fields = ['username', 'password1', 'password2','email']