Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku (python) FileNotFoundError on root directory
I uploaded an application to heroku and the status of the webservice appears to be ok, but I'm having an error when I start the POST method that reads a file in the project's root directory. Locally it works. The error log is: FileNotFoundError: [Errno 2] No such file or directory: '/app/.heroku/python/bin/chave_privada_google.json' My Procfile looks like this: web:gunicorn app:app When I run the ls command on my heroku bash the file list looks like this, with the app.py file being the main one: ls comand on heroku bash This is how I'm referencing the chave_privada_google.json file in the app.py file: file calling I still haven't figured out what's going on. Could anyone help? -
Trouble installing Django for first time
I am trying to use Django on mac to develop a website backend using python. I installed Django 3.1.5 and when I try to upgrade (to 3.1.5) it says 'requirement already satisfied' so I can tell 3.1.5 is installed However when I type python -m django --version into terminal, it returns 1.11.29 How do I fix this? -
How can I show list of names of the foreignkey IDs and update on a intermediary table with Django modelform?
I am trying to make a table view of the intermediary table for many to many relationship(managerproject table). And I want to directly update this table with the Django form. I want to have a form to add a row to the managerproject table which contains pid from project table and manid from manager table. But I would like to have a choicefield for all pid shown as pname from project and another choicefield for all manid shown as mname from manager table. When I submit the form, it just adds a row to managerproject table with chosen pname's pid and mname's manid. mproj.html <tbody> {% for mproj in mprojs %} <tr> <td>{{ mproj.pId.pName}}</td> <td>{{ mproj.manId.mName}}</td> <td> <a href="{% url 'mproj:edit_mproj' mproj.pId %}" class="btn btn-primary btn-sm"> Edit </a> </td> </tr> {% endfor %} </tbody> add_mproj.html {% block content %} <h2>Project Manager</h2> <form class = "upload_form" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Add</button> </form> {% endblock %} models.py STATUS_CHOICES = [('Active', 'Active'), ('Inactive', 'Inactive')] class Manager(models.Model): manId = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') mName = models.CharField(db_column='name', max_length=100) email = models.CharField(db_column='email', max_length=100, blank=True) status = models.CharField(db_column='status', max_length=16, choices=STATUS_CHOICES) class Project(models.Model): pId = models.AutoField(db_column='pId', primary_key=True) pName = models.CharField(db_column='name', max_length=100) … -
Django unable to access the translated fields of a model in the update_or_create function
I have a model such as below: class MyModel(TranslatableModel): date_created = models.DateField( verbose_name=_('Date Created'), default=timezone.now) source = models.CharField(max_length=100, verbose_name=('Type')) translations = TranslatedFields( name=models.CharField(verbose_name=_('Name'), max_length=200) ) I want to use update_or_create function on this model; I want to fetch a record which has the given id and source; If it exists I want to update its name in 3 different languages. Otherwise I want to create a new record. I used the following code. I tried name_en, name__en, translations__name_en; None of them worked. I also tried get_or_create function, None of them worked with that as well. obj, created = MyModel.objects.update_or_create( id= id, source = 'tmp', defaults={ 'name_en': en_name, 'name_fi': fi_name, 'name_sv': sv_name, }) I don't want to use get function and create function separately. I would like to know how to access the django translated fields via update_or_create function or get_or_create function. Can some one help me with this please? -
Django - Cannot link static CSS to applications
So I am working on a django datascience project tutorial from this guy's youtube channel: https://github.com/pyplane/django_with_data_science and I'm stuck at getting my static CSS file to apply to my html view. here is my file structure: So far, I've been able to get static_project/main.js to work fine but I cannot get the style.css file to work. style.css .test_blue_2 { color:blue; } css_test.html {% load static %} <link rel='stylesheet' type='text/css' href={% static 'style.css' %}> <style type = 'text/css'> .test_blue_1 { color:blue; } </style> {% block content %} <div class ='test_blue_1'>Blue text 1</div> <div class ='test_blue_2'>Blue text 2</div> {% endblock %} This outputs Blue text 1 in blue and Blue text 2 remains black Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_project'), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root") http://127.0.0.1:8000/static/style.css yields .test_blue_2 { color:blue; } here is my file structure: -
images do not match pil, django model
I'm trying to create a QR Code in my Django model which creates itself whenever a new record is saved. The problem is that when testing in my dev environment everything is fine but in production I get an error on the specified line below saying: ValueError, images do not match. from django.core.files import File import qrcode from io import BytesIO from PIL import Image from datetime import date def save(self, *args, **kwargs): img = qrcode.make(self.account_id) canvas = Image.new('RGB', (400, 400), 'white') canvas.paste(img) # Error occurs on this line buffer = BytesIO() canvas.save(buffer, 'PNG') canvas.close() fname = f'pdf-qr-code-{self.account_id}.png' self.menu_qr_code.save(fname, File(buffer), save=False) super(PDFMenu, self).save(*args, **kwargs) I don't know if maybe the problem is with my configurations on my ubuntu server since that's the place where the problem takes place but maybe a new way of creating a qr code within this custom save method is necessary. Thanks in advance for the help. -
Customized PasswordResetSerializer and now it's throwing error 500
I am contributing to an open-source org where they are using django-rest-auth for authentication purposes. I have to simply override the email template for a password reset. So I used imported PasswordResetSerializer and then customized it. It worked in the first place but when I restarted the whole environment it stopped working and just showed this in terminal django_1 | [pid: 65|app: 0|req: 1/1] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] OPTIONS /api/auth/password/reset/ => generated 0 bytes in 4 msecs (HTTP/1.1 200) 7 headers in 365 bytes (1 switches on core 0) django_1 | [pid: 67|app: 0|req: 1/2] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] POST /api/auth/password/reset/ => generated 22264 bytes in 796 msecs (HTTP/1.1 500) 5 headers in 177 bytes (1 switches on core 0) It's showing me error 500. I tried to use debugger but here the all environment is setup using docker and I couldn't figure out what's going wrong. Here are the files settings.py """ Django settings for evalai project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ … -
How can I redact a Django object instance based on the user's view permission?
I would like to redact object instances based on the user's view permission. For instance, if I have the following model class Data(models.Model): value = models.FloatField() I would like users that have view permission, i.e. myapp.view_data, to see the full value, and users without view permission to only see a redacted version, say round(value). I could implement this for every view and template, but that doesn't seem very DRY and would have a risk of overlooking some occurrences. Also, I suppose in a template the mechanism might be bypassed through relation queries. How can I implement this redaction mechanism in the model? Would this be good practice? Or is there a better way? Thank you! -
what does forward slash do in this django settings.py python list?
I'm new to python and I don't understand how this forward slash works in the django settings.py STATICFILES_DIRS = [ BASE_DIR / "static", ] It seems like it is concatenating the value of BASE_DIR + "static", but that would actually be str(BASE_DIR) + "static" correct? Is it a special Django delimiter of sometype? This is the correct usage according to the Django documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files STATICFILES_DIRS Is not a parameter list - so this doesn't seem to apply https://docs.python.org/3/faq/programming.html#what-does-the-slash-in-the-parameter-list-of-a-function-mean It's not a binary division operator: https://docs.python.org/3/reference/expressions.html#binary -
Issue comparing datetime objects in django html template
I am passing in class objects and a variable into my html template in Django Using Classbased Views, I have get_context_data(self, **kwargs): ... context['time'] = datetime.now() ... return context I also pass in my objects using model = Object and context_object_name = 'obj' In my html template my comparison looks like this: {% if obj.start_time > time %} <h1 style="color:white">ITS WORKING</h1> {% endif %} Regardless of whether I use >, <, or ==, the h1 template is never displayed. I have used {{obj.start_time}} and {{time}} to ensure that there really are values attached to these variables, and I see both of the times displayed on the page. The values themselves work, but for some reason the comparison isn't working. -
saving a booking form + current user data to customer profile
i am creating a reservation system for booking, i would like the user to view their booking details once they've booked and would like for their details to show on their customer profile, i am struggling to link the form to the user/customer profile #models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Booking(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) confirm_email = models.CharField(max_length=200, null=True) PACKAGES_CHOICES = [('FULL DAY SPA', 'Full Day Spa'), ('HALF DAY SPA', 'Half Day Spa'), ('MOONLIGHT SPA', 'Moonlight Spa')] packages = models.CharField(max_length=100, choices=PACKAGES_CHOICES, default='FULL DAY SPA') PEOPLE_CHOICES = [('ONE', '1'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5'), ('SIX', '6'), ('SEVEN', '7'), ('EIGHT', '8'), ('NINE', '9'), ('TEN', '10'), ] people = models.CharField(max_length=100, choices=PEOPLE_CHOICES, default='ONE') booking_date = models.DateField() created = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __str__(self): return self.name #views.py @allowed_users(allowed_roles=['customer']) @login_required(login_url='login') def booking(request): if request.method == 'POST': print(request.POST) book = BookingForm(request.POST, ) if book.is_valid(): booking = book.save booking.user = request.user book.save() #forms.py class BookingForm(ModelForm): class Meta: model = Booking fields … -
LINK to a view with url parameter not working (Django href)
i have a problem i have a view how got a parmeter on url , so im trying to access to this view from anoter template with , in the the html inspector its show that the url is correct , and when i open it in new tab the link work perfectly, but when i click on it it redirect me to the correct url but without the parameter so it dont work, so their is my code : <a href=" /coach/addsession/{{session.id}} " class="btn btn-outline-info submit"}> Edit </a> URL.py : path('addsession/<str:session_id>',views.addsession, name='addsession'), views.py : def coach_session(request): sessions = session.objects.filter(coach= request.user.id) form = SessionForm() if request.method == 'POST': form = SessionForm(request.POST) print('weeee') if form.is_valid(): print('nooooo') name = request.POST.get('name') detail = request.POST.get('detail') coach_id = request.user.id obj= session.objects.create(name=name,detail=detail,coach_id=coach_id) # user = authenticate(username=username, password=password) #form.save() return redirect('addsession/'+str(obj.id) ) messages.success(request, f'Account created successfully for {username}') return render(request, 'coach/session.html', context={'sessions': sessions, 'form': form}) their is an image of inspector : -
Token Auth and session auth in django-rest-framework
I always choose token authentication, but after thinking about how it works and not recording it in memory, and I cannot guess whether it is expired or not, is it better to use session authentication or I try to renew the token every given time What is the best practice here -
How can I solve my "Not Found: URL" error in my DRF view?
I'm trying to pass an external API through django rest, however I cant get my URL's to work properly and load the data called from the GET view below. core urls urlpatterns = [ ... path('api/', include('bucket_api.urls')), ... ] bucket_api urls urlpatterns = [ ... path('bucket-data/', BucketData.as_view(), name='bucket-data') ] external API path URL view class BucketData(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): external_api_url = "http://localhost:3000/security?select=symbol,company" res = urllib.urlopen(external_api_url).read() data = json.loads(res) return Response(data, status=HTTP_200_OK) My python terminal says: Not Found: /api/bucket-data/ when I load up the the development url http://127.0.0.1:8000/api/bucket-data/ , I get: { "detail": "Not found." } How can I properly configure my set-up? -
Django nginx gunicorn 502 bad geatway
hello guys i was deploying my django project on fedora 33 nginx server . But domain and localhost tell me 502 bad gateway . i made diagnostic and learned that ~ lines 1-17/17 (END)...skipping... ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Fri 2021-01-08 01:34:08 +04; 1min 17s ago Process: 4348 ExecStart=/home/robot/venv/bin/gunicorn --workers 3 --bind unix:/home/robot/plagiat/plagiat.sock plagiat.wsgi:application (code=exited, status=203/EXEC) Main PID: 4348 (code=exited, status=203/EXEC) CPU: 5ms Jan 08 01:34:10 baku systemd[1]: Failed to start gunicorn daemon. Jan 08 01:34:10 baku systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 08 01:34:10 baku systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 08 01:34:10 baku systemd[1]: Failed to start gunicorn daemon. Jan 08 01:34:11 baku systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 08 01:34:11 baku systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 08 01:34:11 baku systemd[1]: Failed to start gunicorn daemon. Jan 08 01:34:11 baku systemd[1]: gunicorn.service: Start request repeated too quickly. Jan 08 01:34:11 baku systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jan 08 01:34:11 baku systemd[1]: Failed to start gunicorn daemon. ~ ~ -
Geometric intersection in Django's GEOS API no longer working
I've been using Django's GEOS API for a while and it's worked great. I upgraded something in my project and some code I had which determines if points are within a polygon no longer works. I've distilled it down to this, which demonstrates the problem. I set up this model: class TestPoint(models.Model): name = models.CharField(max_length=64) pickup_location = models.PointField(srid=4326) Then I run: >>> from django.contrib.gis.geos import Point, Polygon >>> from mytest.models import TestPoint >>> p1 = TestPoint(name="p1", pickup_location=Point(-118.4, 33.9)) >>> p2 = TestPoint(name="p2", pickup_location=Point(-118.45, 34)) >>> p3 = TestPoint(name="p3", pickup_location=Point(-118.3, 34.02)) >>> p4 = TestPoint(name="p4", pickup_location=Point(-118.46, 34.01)) >>> bbox = (-118.5, 34, -118, 34.5) >>> poly = Polygon().from_bbox(bbox) >>> poly.srid = 4326 >>> hits = TestPoints.objects.filter(pickup_location__within=poly) >>> hits <QuerySet []> I'd expect hits to contain 3 points, but as you can see it's empty. I wondered if perhaps they changed the order of coordinates in from_bbox(), but the documentation says it's still (xmin, ymin, xmax, ymax). What's going on? -
Serving static files from local server when internet is down
I am running a Django app on a dedicated server on company LAN. Initially I setup all static files to be served either from CDN or my S3 bucket. What happens if the company's internet goes down? I know that static files are saved in the cookies on users' computers, but let's say they Ctrl-R it or the cookies get lost some other way. If i put both paths in my settings, will the server only serve static files from local drive if the first link isn't working? What is the correct approach to this? <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> -
Django migration failed
$ python manage.py migrate --run-syncdb [DEBUG] (MainThread) Using proactor: IocpProactor Operations to perform: Synchronize unmigrated apps: humanize, messages, registration, staticfiles Apply all migrations: admin, auth, contenttypes, groups, home, institutes, questions, sessions, student, users Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying institutes.0001_initial...Traceback (most recent call last): File "E:\Freelance\gear\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: ERREUR: la relation « coordinator » n'existe pas The above exception was the direct cause of the following exception: -
Aggregate total by user in a list from Many to Many
I wish you a good year :) I got a question. How I can get the total amount (prix + prix + ...) for each user who belongs to friends (Reservation's model). I'm able to do it with request user: context['user_total'] = RerservationOrder.objects.filter(friends=self.request.user).filter(resa_order_reservation=self.object).aggregate(total=models.Sum('prix'))['total'] But assume I got three friends = X Y and Z. How I can list the total of X / Y an Z I'm stuck with this issue. Thanks in advance class Reservation(models.Model): friends = models.ManyToManyField(User,blank=True,related_name='friends_reservation') resa_order = models.ManyToManyField('RerservationOrder',blank=True, related_name='resa_order_reservation') ... class RerservationOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) ... -
Manually laying out fields from an inline formset in Django
I have created an inline formset for the profile information which is added to the user form: UserSettingsFormSet = inlineformset_factory( User, Profile, form=ProfileForm, can_delete=False, fields=( "title", ... ), ) class SettingsView(UpdateView): model = User template_name = "dskrpt/settings.html" form_class = UserForm def get_object(self): return self.request.user def get_context_data(self, **kwargs): context = super(SettingsView, self).get_context_data(**kwargs) context["formset"] = UserSettingsFormSet( instance=self.request.user, prefix="user" ) return context This works and calling {formset} in the template file renders the complete form for both User and Profile. Yet, I would like to lay out the individual inputs myself. This works for fields belonging to User: <input type="text" name="{{form.last_name.html_name}}" id="{{form.last_name.auto_id}}" value="{{form.last_name.value}}"> But doing the same for fields of the formset does not work. Here the attribute formset.form.title.value appears to be empty. All other attributes, e.g. formset.form.title.auto_id exist though. Why does {{formset}} render completely with values but values are missing individually? -
Using the URLconf defined in myproject2.urls, Django tried these URL patterns, in this order:
urls.py: ------- from django.urls import path from . import views [![enter image description here][1]][1] urlpatterns = [ path('hello', views.hello, name='hello'), ] views.py: -------- from django.shortcuts import render from django.http import HttpResponse # create your view here def hello(request): # return HttpResponse('<h1>Hello World</h1>') return render(request,'home.html',{'name':"Page"}) [![enter image description here][1]][1] Error showing: Using the URLconf defined in myproject2.urls, Django tried these URL patterns, in this order: 1.admin/ -
I am getting some front end issues
! these underlines are showing up on every HTML file as this issue is occurring due to some CSS files. please help me to solve this issue -
request.user.is_authenticated returning false even user is logged in. user authenticated is not working
Front end codeThis is my view code I also tried request. user.is_authenticated but it does not work. Always return false even user is login. Any solution, please -
Exporting a data from last year to csv returns an error
I'm trying to get my data from last year. but my django returns an error when I do it. The error is: TypeError at /home/export_by_last_year/ export_by_last_year() takes 0 positional arguments but 1 was given @views.py def export_by_last_year(): response = HttpResponse(content_type='text/csv') last_year = datetime.now().year - 1 writer = csv.writer(response) writer.writerow(['Level', 'Amount', 'Timestamp']) for i in Rainfall.objects.filter(timestamp__year=last_year).values_list('level', 'amount', 'timestamp'): writer.writerow(i) response['Content-Disposition'] = 'attachment; filename="rainfall.csv"' return response -
Django: Search results with django-tables2 and django-filter
I'd like to retrieve a model's objects via a search form but add another column for search score. I'm unsure how to achieve this using django-tables2 and django-filter. In the future, I'd like the user to be able to use django-filter to help filter the search result. I can access the form variables from PeopleSearchListView but perhaps it's a better approach to integrate a django form for form handling? My thought so far is to handle to the get request in get_queryset() and then modify the queryset before it's sent to PeopleTable, but adding another column to the queryset does not seem like a standard approach. tables.py class PeopleTable(tables.Table): score = tables.Column() class Meta: model = People template_name = 'app/bootstrap4.html' exclude = ('id',) sequence = ('score', '...') views.py class PeopleFilter(django_filters.FilterSet): class Meta: model = People exclude = ('id',) class PeopleSearchListView(SingleTableMixin, FilterView): table_class = PeopleTable model = People template_name = 'app/people.html' filterset_class = PeopleFilter def get_queryset(self): p = self.request.GET.get('check_this') #### # Run code to score users against "check_this". #### qs = People.objects.filter('name__exact'=p) #### # Modify queryset using output of scoring code? #### return qs urls.py urlpatterns = [ ... path('search/', PeopleSearchListView.as_view(), name='search_test'), ... ] models.py class People(models.model): first_name = models.CharField(max_length=200) last_name …