Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
ideas on how to build a function in python django for cellulating hours interval
I am Total beginner starting a project in Django a payroll calculator app, in it my user has a workhours with dates form. the function required should calculate(dates, in hour, out hour) and output the value to another(total hours) field. the restrictions are: value must be an integer value can be crossday meaning: giving a worker crossday shift 07.01.2021,08.01.2021/dates, 22:00:00pm/hour in, 06:00:00am/hour out function must work with Django .models / .datetime as far as i got 'def HoursTotalConf(in_time, out_time): start_dt = dt.datetime.strptime(in_time, "%H:%M:%S") end_dt = dt.datetime.strptime(out_time, "%H:%M:%S") return relativedelta(end_dt, start_dt) ' -
./manage.py runserver in MACBOOK M1 throws 'illegal hardware instruction ./manage.py runserver'
runnung server: ./manage.py runserver /Users/ashwin/dmango_entrayn/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) /Users/ashwin/dmango_entrayn/lib/python3.6/site-packages/psycopg2/init.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi. """) Performing system checks... System check identified no issues (0 silenced). zsh: illegal hardware instruction ./manage.py runserver requirements.txt: aenum==1.4.5 alabaster==0.7.10 amqp==2.3.2 # via kombu appnope==0.1.0 asn1crypto==0.24.0 # via cryptography authy==2.2.0 babel==2.5.0 backports-abc==0.5 bcrypt==3.1.6 # via paramiko beautifulsoup4==4.6.3 billiard==3.5.0.4 # via celery bleach==2.0.0 boto3==1.6.3 botocore==1.9.3 bs4==0.0.1 cachecontrol==0.12.5 # via firebase-admin cached-property==1.4.0 cachetools==2.1.0 # via google-auth celery==4.1.1 certifi==2018.1.18 cffi==1.12.3 # via bcrypt, cryptography, pynacl chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 coverage==4.5.1 # cryptography==2.6.1 # via paramiko decorator==4.1.2 django-cors-headers==2.2.0 django-extensions==2.0.0 django-filter==2.0.0 django-health-check==3.10.1 django-polymorphic==2.0.2 django-rest-polymorphic==0.1.8 django-rest-swagger==2.1.2 django-s3-storage==0.12.4 django-storages==1.6.6 django-treebeard==4.3 django-url-filter==0.3.5 django==2.0.2 djangorestframework-bulk==0.2.1 djangorestframework-simplejwt==3.2.3 djangorestframework==3.7.7 docutils==0.14 drf-dynamic-fields==0.3.1 dry-rest-permissions==0.1.10 entrypoints==0.2.3 enum-compat==0.0.2 fabric3==1.14.post1 factory-boy==2.11.1 faker==0.9.0 # via factory-boy firebase-admin==2.11.0 flake8==3.5.0 geoip2==2.9.0 google-api-core[grpc]==1.2.1 # via google-cloud-core, google-cloud-firestore, google-cloud-storage google-api-python-client==1.7.4 google-auth-httplib2==0.0.3 # via google-api-python-client google-auth-oauthlib==0.2.0 google-auth==1.5.1 # via firebase-admin, google-api-core, google-api-python-client, google-auth-httplib2, google-auth-oauthlib google-cloud-core==0.28.1 # via google-cloud-firestore, google-cloud-storage google-cloud-firestore==0.29.0 # via firebase-admin google-cloud-storage==1.10.0 # via firebase-admin google-resumable-media==0.3.1 # via … -
Place a text on top of an image
I want to place an image in the center of my white page and add a title over it (the title would be larger than the image || also the title center must be the image center). The problem is that the title won't go on top of the image. I use Django and bootstrap ^^ Here is the code : HTML : <div class="col-md-7 white nopadding text-center"> <div class="brand"> Brand </div> <div class="heading"> <img src="{% static '/eyemeet/hero.jpg' %}" class="hero"> <div class="title ctr">Title</div> </div> CSS: .hero { width: 65%; height: auto; } .title { position: absolute; background-color: cadetblue; top: 50%; left: 50%; } .ctr { position: absolute; transform: translate(-50%, -50%); } What happens currently : -
Django making 2 request instead of 1
Initial I thought 2 django process was started. So i have added a print statement in the settings.py. But it was printing only one time. My problem is, whenever I am making a request, I can see two entries in the django console. Entires in Database is added twice. (Often getting UNIQUE constrain error in db because of double request). I have added print('hi'). It is printing only one time. Also i tried --noreload. No luck. -
Django Can i fill automatically list_display
I'm trying fill automatically my list_display on my admin Django, apparently the code works correctly, but it doesn't show nothing. This is my code Model class Pacient(models.Model): name = models.CharField( max_length=50 ) last_name = models.CharField( max_length=50 ) id_identification = models.IntegerField() age= models.PositiveSmallIntegerField() gender = models.ForeignKey( Gender, on_delete=models.CASCADE ) blood_type = models.ForeignKey( BloodType, on_delete=models.CASCADE ) def __str__(self): return self.name Admin.py from django.contrib import admin from .models import Pacient class PacientAdmin(admin.ModelAdmin): list_display=() x = Pacient.objects.values() def some(self): for k in self.x: k = k.keys() self.list_display=(tuple(k)) print (self.list_display) return self.list_display admin.site.register(Pacient,PacientAdmin) -
how to send "order is confirmed emails to customer" in django
I am trying to make an e-commerce website in Django and react. but I am not able to find a way for this scenario. whenever a user purchases something a confirmation email should go to the user and one to the admin that a user buy something. can we do this just by code or we have to use something like Mailchimp?i want to do it by writing code. -
Django dev server view handler very slow, but only when logged in
My django dev server view handler takes over 1 minute. I've narrowed it down to when the request.user is logged in. E.g. the below handler is <1 second when logged out, but >1 second when logged in (i.e. request.user.is_authenticated() == True). def test_handler(request): return HttpResponse("OK") Similarly, this handler is very fast def test_handler(request): logout(request) return HttpResponse("OK") -
Reason for receiving swapStyle is not defined
I am new to Javascript, I am currently learning to debug errors that I am receiving in the Console. In my project I am adding a theme choosing option for each user logging into the website. I have created an app in my Django Project and everything is as covered in the tutorial I am following except that in the console I am receving errors: Uncaught ReferenceError: swapStyle is not defined at HTMLButtonElement.onclick (VM58:202) swapStyle('css/app-light.css') To start here is the base.html <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyle('css/app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyle('css/app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); var cssFile = "{% static 'css' %}" function swapStyles(sheet){ document.getElementById('mystylesheet').href = cssFile + … -
why am i getting Incorrect type. Expected pk value, received str (many to many field)
models.py import uuid import os from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from django.conf import settings def recipe_image_file_path(instance, filename): """Generate file path for new recipe image""" ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/recipe/', filename) class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that suppors using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' class Tag(models.Model): """Tag to be used for a recipe""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.name class Ingredient(models.Model): """Ingredient to be used in a recipe""" name = models.CharField(max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.name class Recipe(models.Model): """Recipe object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) title = models.CharField(max_length=255) time_minutes = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) link = models.CharField(max_length=255, blank=True) ingredients = models.ManyToManyField('Ingredient') tags = models.ManyToManyField('Tag') … -
Multiple types of the same type of relationship in django
I have a requirement for models with a pk relationship where one of the models can be multiple types of a similar object. for instance I have three different ways in which a requisition can be made and these three ways have distinct attributes which are different from each other. How can I make the model so as to connect the three different requisition types with a single order model? Any help is much appreciated. Thank you very much. -
How to use Spyne+Django with parameters on url?
on django urls.py url(r'soap/<str:user_id>/', DjangoView.as_view(application=provider)), on views.py @ rpc(_returns=AnyDict) def super_test_dict(self, one, two): user_id = 1 #here need to receive the user_id res = {"user_id":user_id} return res on tests.py self.soap_client = DjangoTestClient( f'/soap/{org.str:user_id}/', provider) res = self.soap_client.service.super_test_dict() The problem is when i send parameter str:user_id dont work, but if not sent anything work fine, im need to send same parameters as request but also need to send str:user_id on url.