Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django working with query parameters in raw Postgres queries
I use the `amount = (request.GET.get('page'))` and then i convert it into a int `amount= (int)amount` but when i tried to run this query: `cursor.execute('SELECT column1, FROM table LIMIT amount')` I get a error: `column "amount" does not exist` So is the any way how i can get the value to the query? -
I can't understand how to use correct static in django
I'm trying to display a picture whose address is saved in the Django models attribute. As I know you need to enter in the fieldurl({% static movie.img %}) but it doesen't works. If only use url({% static 'img/default-movie.png' %}) it works. That is my query sets from django shell: In [21]: Movie.objects.first().img Out[21]: <ImageFieldFile: ../MovieApp/movies/static/img/1202296.jpg> P.S (I should mentioned, that these fields are in for loop {% for movie in movies %} ) -
Can I use an API Key to identify a server that is an API consumer?
I'm facing a straightforward architectural challenge, which is that I have a central API written in Django and DRF. It has in it an API key library, in which there is an API key stored along with some other cryptographic information, and a column called "name". I can imagine with a little bit of customization I could add extra fields to this entity. I have multiple API consumers, which are themselves end-user browsable services, which communicate with this API. I need to be able to send notifications from within the centralized API - this requires access to the user's contact point, which is a URL, sometimes an IP address especially if it's behind a proxy. Since I need this URL, I need to store it somewhere perhaps in the database. There is get_base_uri() in Django, but I don't think it is for this purpose, especially since IP addresses are typically not necessarily connected to the consumer. How should I store, authenticate and authorize an API consumer's request? Should I submit the notification endpoint on every request (quite tedious), use the API key on every request (sent along with the request headers, would also need to implemented, but it would be … -
django filter data and make union of all data points to assignt to a new data
My model is as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) Sample data saved in drawingJSONText field is as below {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) #drawingJSONData2 = json.loads(Drawing.objects.get(id=3).drawingJSONText) #drawingJSONData = dict() #drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] #drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] #drawingJSONData = json.dumps(drawingJSONData) #drawingJSONData = Drawing.objects.get(id=3).drawingJSONText filterdata = Drawing.objects.filter(project=1).count() drawingJSONData = Drawing.objects.get(id=filterdata).drawingJSONText #drawingJSONData = filterdata[1].drawingJSONText #drawingJSONData["points"]=filterdata["points"] #drawingJSONData["lines"] = filterdata["lines"] # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response Any suggestions on to achieve it -
Docker on GCE always restarting
Problems I am having with my Docker instance on a GCE VM: It keeps restarting I cannot access tcp:80 after creating several firewall policies Here are the steps I took in creating the instance with gcloud: Why is Google Compute Engine not running my container? What I have tried: To open the port, I created a new policy and updated tagged the VM, but still running: nmap -Pn 34.XX.XXX.XXX # results in: PORT STATE SERVICE 25/tcp open smtp 110/tcp open pop3 119/tcp open nntp 143/tcp open imap 465/tcp open smtps 563/tcp open snews 587/tcp open submission 993/tcp open imaps 995/tcp open pop3s # 80/tcp is not open Alternatively, I tried opening the port from inside the container after SSH: docker run --rm -d -p 80:80 us-central1-docker.pkg.dev/<project>/<repo>/<image:v2> curl http://127.0.0.1 #which results in: curl: (7) Failed to connect to 127.0.0.1 port 80: Connection refused Also, running docker ps from within the container shows a restarting status. If it helps, I have two docker-compose files, one local and prod. The prod has the following details: version: '3' services: web: restart: on-failure build: context: ./ dockerfile: Dockerfile.prod image: <image-name> volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 env_file: - … -
django.db.utils.OperationalError: Problem installing fixtures: no such table: pages_page__old
i am a begginer in code and when y try to make : python3 manage.py createdb. after to add my password i have an error, after the superuser create succesfully. and the finish of the following error is : django.db.utils.OperationalError: Problem installing fixtures: no such table: pages_page__old all my error : Traceback (most recent call last): File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: pages_page__old The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/martaf/Travail_insPYration/shop/manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/mezzanine/core/management/commands/createdb.py", line 61, in handle func() File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/mezzanine/core/management/commands/createdb.py", line 109, in create_pages call_command("loaddata", "mezzanine_required.json") File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/core/management/commands/loaddata.py", line 115, in loaddata connection.check_constraints(table_names=table_names) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 276, in check_constraints cursor.execute( File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/martaf/Travail_insPYration/shop/env/lib64/python3.9/site-packages/django/db/backends/utils.py", … -
How can I host my Django project on cpanel?
I'm using cpanel on hostinger and I want to host my Django project on cpanel but there's no "set up a python app" on the board. I googled it and saw people say I need to install cloud linux os. but I don't know how please tell me how can I do that or if there is an alternative way to do that. i'm a collage student and I need this for my project. please help! -
DjangoListField analouge for an individual object resolver
I am using Django + GraphQL and it is extremely convenient to use DjangoListField. It allows me to override get_queryset at the ObjectType level and make sure all permissions verified there. In that manner I have a single place to have all my permission checks. However, whenever I need to do something like: contract = graphene.Field(ClientContractType, pk=graphene.ID(required=True)) I have to also duplicate permissions validation in the resolve_contract method. I came up with the following solution to ensure permission and avoid duplication: def resolve_contract(self, info, pk): qs = ClientContract.objects.filter(pk=pk) return ClientContractType.get_queryset(qs, info) It works but I'd love to have some sort of DjangoObjectField which will encapsulate this for me and, potentially, pass arguments to the ClientContractType in some way. Have someone had this problem or knows a better solution? -
makemigrations/migrate error django.db.utils.OperationalError: no such table
I have an application that I have made using PostgreSQL as a database management system, but due to a series of things that have happened, now I want to use SQLite, but when I run makemigrations or migrate, it throws me the error django.db.utils.OperationalError : no such table: blogapp_category. With PosgreSQL it works perfectly, but I can't get it to work with SQLite ... (I have also tried to deploy the application with heroku and got the same error ...) This is the traceback: Traceback These are my models: blogapp\models.py class Category(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(to=User, on_delete=models.CASCADE) # body = models.TextField() body = RichTextField(blank=True, null=True) post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='uncategorized') # category podría ser un ManyToManyField # https://stackoverflow.com/questions/2642613/what-is-related-name-used-for-in-django likes = models.ManyToManyField( to=User, related_name='blog_posts', blank=True) # null has no effect on ManyToManyField snippet = models.CharField(max_length=255) header_image = models.ImageField( blank=True, null=True, upload_to='images/') def get_likes(self): return self.likes.count() def __str__(self): return '{} - {}'.format(self.title, self.author) def get_absolute_url(self): # https://docs.djangoproject.com/en/3.1/ref/urlresolvers/#reverse return reverse('article_detail', args=[str(self.id), ]) # return reverse('home') class Meta: ordering = ['-post_date'] class Profile(models.Model): user = models.OneToOneField(to=User, null=True, on_delete=models.CASCADE) bio … -
Django - Filter by multiple values (Logical AND) on ManyToMany field
I'm trying to build job-candidate match system. I want to filter Candidates by Critical Skills needed for the Job. Every candidate has multiple skills. Every Job has multiple 'required' JobSkill which is a model that also contains importance of the skill. I want to filter my candidates and to get only candidates how have all the critical skills required for a job. A critical skill is defined as a JobSkill with importance = 3. For a given job 'job_1' I want to get the relevant candidates as follows: critical_skills = job_1.required_skills.filter(importance=3) relevant_candidates = Candidate.objects.filter('candidate how has all the critical_skills) models.py: class Skill(models.Model): title = models.CharField(max_length=100, blank=False, unique=True) class JobSkill(models.Model): skill = models.ManyToManyField(Skill) class Importance(models.IntegerChoices): HIGH = 3 MEDIUM = 2 LOW = 1 importance = models.IntegerField(choices=Importance.choices) class Job(models.Model): title = models.CharField(max_length=100, null=False) required_skills = models.ManyToManyField(JobSkill, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Candidate(models.Model): title = models.CharField(max_length=100, blank=False, null=False) full_name = models.CharField(max_length=100, blank=False, null=False) skills = models.ManyToManyField(Skill, blank=True) I would appreciate any help with this!! Thank you -
My HTML page won't print my django variable
First of all sorry for my bad english but i'm french. I am currently working on a django app and i'm trying to make my HTML page work but it won't and i dont know why. I followed the tutoriel but i edited some of the code to fit my purpose. And now my page won't print out my variable. I have python 2.7.5 and Django 1.11.29 My html page Now this is my code for the HTML : {% if True %} <p> Vrai </p> <li>{{ Thriller.title }}</li> {% else %} <p> faux </p> {% endif %} <ul> <p> Paragraphe : </p> <li>{{ Thriller.title }}</li> <li>{{ Thriller.id }}</li> </ul> My code for the Django part : This is in the models.py file : from django.db import models import datetime from django.utils.encoding import python_2_unicode_compatible from django.utils import timezone class Artist(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class Album(models.Model): reference = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) title = models.CharField(max_length=200, unique=True) picture = models.URLField() artists = models.ManyToManyField(Artist, related_name='albums', blank=True) def __str__(self): return self.title This is in the views.py file : from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from .models import Album, Artist, Contact, … -
Integrity Error: NOT NULL constraint failed - Django Rest Framework
models.py from django.db import models class client(models.Model): ROLES = ( ("Player", "player"), ("Umpire", "umpire"), ("Scorer", "scorer"), ("Organization", "organization"), ("Administrative", "administrative") ) client_id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=10) lastName = models.CharField(max_length=10, blank=True) email = models.EmailField() # * in the form.py widget=forms.PasswordInput as param passed into the model.CharField(). password = models.CharField(max_length=15) profileImage = models.ImageField( blank=True, null=True) coverImage = models.ImageField( blank=True, null=True) role = models.CharField(max_length=20, choices=ROLES) def __str__(self): return f"{self.firstName} {self.lastName}" GAMES = ( ("Basketball", "basketball"), ("Football", "football"), ("Cricket", "cricket"), ("Table-tennis", "tennis") ) class tournament(models.Model): tournament_id = models.AutoField(primary_key=True) title = models.CharField(max_length=60) organizer = models.ForeignKey( client, null=False, blank=False, on_delete=models.CASCADE) logo = models.ImageField(null=True, blank=False) game = models.CharField(max_length=20, choices=GAMES) fees = models.IntegerField() def __str__(self): return self.title class team(models.Model): name = models.CharField(max_length=30) logo = models.ImageField(default=None, blank=False, null=True) members = models.ManyToManyField(client) game = models.CharField(max_length=60, choices=GAMES, null=False, blank=False, default=None) def __str__(self): return f"{self.name} - {self.game}" views.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import clientSerializer, tournamentSerializer from .models import client, tournament # Client Views @api_view(['GET']) def index(request): return Response("API") @api_view(['GET']) def clientList(request): clients = client.objects.all() serializer = clientSerializer(clients, many=True) return Response(serializer.data) @api_view(['GET']) def clientDetail(request, clientId): singleClient = client.objects.get(client_id=clientId) serializer = clientSerializer(singleClient, many=False) return Response(serializer.data) @api_view(['POST']) def clientCreate(request): serializer = clientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @api_view(['POST']) … -
how to save JSON data in Django using forms
when I am printing new_data I'm getting JSON data in CMD but I don't know how do I verify and save it in the database? I tried to save but I'm getting AttributeError at /attendance/ so please suggest to me how to solve it . [ { "1220":"present", "1221":""present", "1223": "present", "1223": "present" }}, models.py from django.db import models class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class Meta: ordering = ('name',) verbose_name_plural = 'Student Profile' def __str__(self): return self.name class studentAttendance(models.Model): CHOICES = ( ('present', 'present'), ('absent', 'absent'), ) name = models.ForeignKey(studentProfile, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=10, choices=CHOICES) date = models.DateField(auto_now=True) class Meta: verbose_name_plural = 'Student Attendance' def __str__(self): return self.name.name views.py def studentAttendanceView(request): student_status = studentProfile.objects.all() if request.method == "POST": my_data = ast.literal_eval(request.POST.get('passedJSON')) new_data = json.dumps([my_data]) save_data = studentAttendanceForm(new_data) if save_data.is_valid(): cd = save_data.save() cd.author = request.user cd.save() cd.refresh_from_db() name = save_data.cleaned_data.get('name') messages.success(request, f'Attendance submitted for {name} ') else: messages.error(request, 'Please check An Error occurred') else: save_data = studentAttendanceForm() return render(request, 'attendance.html', {'save_data': save_data, 'student_status': student_status}) -
Django: render template after AJAX POST request in view using context
Simple question but can't find the answer. I submit an AJAX post request from my template template1.html, my view function uses the AJAX POST data to lookup objects/context variables from the database. Then I simply want to render a different template template2.html from this view using those context variables as template tags in this next template (template2.html). I do NOT want to use the AJAX success call-back function to load the next template (because I don't want the context variables displayed in the URL in the GET request). Please help. -
Overwrite django admin delete_queryset's "short_description"
I've been overwriting django's delete_queryset in my app (mainly to provide custom bulk deletion). I can't find the way to overwrite the "short_description" of this method. For custom methods, you can easily use the short_description attribute, for instance : class MyAdminModel(admin.ModelAdmin): def dump_model(self, request, queryset): pass dump_model.short_description = "My description" But this won't work : class MyAdminModel(admin.ModelAdmin): def delete_queryset(self, request, queryset): pass delete_queryset.short_description = "My description" I've tried every method/attribute of the standard delete_queryset (within the __init__ method after a super() call that is) without finding anything useful, though I might have missed something. I've also gave it a try deleting the standard method using delattr (also in __init__), though it seems a bit clumsy. It also fails, throwing an AttributeError : class MyAdminModel(admin.ModelAdmin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) delattr(self, "delete_queryset") -
Django Custom Model, Email Field disable for filling when Create User by Admin
I changed default User Model to my custom usermodel and use email for login. After login to admin and trying to create new user, the email field can not be filled. Like the screenshot below. I deleted db.sqlite3 while solving someother problems. But already re-build later. python manage.py createsuperuser still work. I can create superuser through terminal. Here the code | ./accounts/admin.py | from django.contrib import admin from django.contrib.auth.admin import UserAdmin # Register your models here. from .models import Account class AccountAdmin(UserAdmin): list_display = ('email', 'date_joined', 'last_login', 'is_admin') search_fields = ('email',) readonly_fields = ('email', 'date_joined', 'last_login') ordering = ('email',) # solution for E033 filter_horizontal = () list_filter = () fieldsets = ( (None, {'fields': ('email', 'password')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) admin.site.register(Account, AccountAdmin) | ./accounts/backends.py | from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailAuthBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): UserModel = get_user_model() if email is None: email = kwargs.get(UserModel.USERNAME_FIELD) if email is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(email) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if … -
How should I save to the database?
I have created a Customer model in Django and am not able to save the data to the database table and when I click the signup button it just redirects me back to the home page. I have attached below the customer model and the signup function. ...please help me resolve the issue. customer.py from django.db import models class Customer(models.Model): first_name= models.CharField(max_length=50) last_name= models.CharField(max_length=50) phone=models.CharField(max_length=15) email=models.EmailField() password=models.CharField(max_length=500) def register(self): self.save() views.py def signup(request): if request.method == 'GET': return render(request, 'signup.html') else: postData=request.POST first_name=postData.get('firstname') last_name=postData.get('lastname') phone=postData.get('phone') email=postData.get('email') password=postData.get('password') print(first_name,last_name,phone,email,password) customer=Customer(first_name=first_name,last_name=last_name,phone=phone,email=email,password=password) customer.register() return HttpResponse("Signup success") signup.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="p-4 m-4"> <div class="col-lg-5 mx-auto border rounded pt-4"> <h3 class="alert alert-light border rounded" >Create An Account</h3> <form action="/" method="POST"> {% csrf_token %} <!--firstname--> <div class="form-group"> <label for="">First Name</label> <input type="text" name="firstname" id="" class="form-control form-control-sm" placeholder="Mike"> </div> <!--lastname--> <div class="form-group"> <label for="">Last Name</label> <input type="text" name="lastname" id="" class="form-control form-control-sm" placeholder="Ross"> </div> <!--phone--> <div class="form-group"> <label for="">Phone No</label> <input type="text" name="phone" id="" class="form-control form-control-sm" placeholder="9876543210"> </div> <!--email--> <div class="form-group"> <label for="">Email</label> <input type="email" name="email" id="" class="form-control form-control-sm" placeholder="abc@gmail.com"> </div> <!--password--> <div class="form-group"> <label for="">Password</label> <input type="password" name="password" id="" class="form-control form-control-sm" placeholder="********"> </div> <div class="form-group"> <input class="btn btn-sm … -
Django allall send verification code instead of verification link
I am using Django allauth for rest API. Currently, when I request password reset, then Django sends me email containing a link which you have to go to in order to verify your email. But i want so that Django send an email with a verification code which put another api endpint to verify the account? My code are below: settings.py file ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True REST_USE_JWT = True JWT_SERIALIZER = True and Installed app [ ''' 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration', ''' ] this is my current urls of built in viwes path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"), path('rest-auth/', include('rest_auth.urls')), #for forget password api endpoint path('rest-auth/registration/', include('rest_auth.registration.urls')), # handle the error: https://github.com/iMerica/dj-rest-auth/issues/9 # https://django-allauth.readthedocs.io/en/latest/configuration.html path("account-inactive/", AccountInactiveView.as_view(), name="account_inactive"), re_path(r'^rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), Can anyone help me in this case? how can i send verification code to verify instead of verificatin link? I am using this lib : https://django-rest-auth.readthedocs.io/en/latest/ https://django-allauth.readthedocs.io/en/latest/ -
"curl: (56) Recv failure: Connection reset by peer" after "curl --unix-socket /run/gunicorn.sock localhost"
I'm trying to deploy a django app to DigitalOcean but when I try to activate gunicorn with curl --unix-socket /run/gunicorn.sock localhost it says curl: (56) Recv failure: Connection reset by peer. I'm literally following a tutorial made by digitalocean but it doesn't shows how to solve this error. What do I have to change? my /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=sammy EnviromentFile=/home/sammy/mysite/env WorkingDirectory=/home/sammy/mysite ExecStart=/home/sammy/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ mysite/locallibrary.wsgi:application [Install] WantedBy=multi-user.target my /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target -
using mixin with a def
I m using this Accessmixin on generic.views: class OrganisorAndLoginRequiredMixin(AccessMixin): """Verify that the current user is authenticated and is an organisor.""" def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated or not request.user.is_organisor: return redirect("home") return super().dispatch(request, *args, **kwargs) I want to use it on a def. I tried this but I've error bellow. @OrganisorAndLoginRequiredMixin() def AgentUpdateView(request, pk): obj = Agent.objects.filter(pk=pk).first() if obj is None: return render(request, "404.html", { "Instance": pk }) else: form = AgentModelForm(instance=obj.user) Error: TypeError: 'OrganisorAndLoginRequiredMixin' object is not callable -
Django CSRF cookie not set: using Ajax Cross site
I have two parts of my code first is a frontend running on localhost:3000 via simple python HTTP server and a Django server running on localhost:8080, what's happening in here is the frontend is making a cross-site POST request to Django server but its been getting a Forbidden (CSRF cookie not set.) error. I know this problem has been asked about so many times but I don't seem to find a solution. I don't have any experience requesting a POST call in Django like this, not using DRF but endpoints of our own. The Problem Code: firstly the frontend shall make a get request for a csrf token to /api/csrf/ views.py: def get_csrf(request): # print(get_token(request)) return JsonResponse({ 'detail': 'CSRF cookie set', 'X-CSRFToken': get_token(request) }) After getting the value, the token is assigned to the cookie and a hidden element via main.js: success: function (response, status, xhr) { $('.csrftoken').attr('value', response['X-CSRFToken']); setCookie("csrftoken", response['X-CSRFToken']); } The code above works fine and we get the value, at the start, it was like this but was not working so I changed it like: xhr.getResponseHeader("X-CSRFToken") -> response['X-CSRFToken'] Now whenever the frontend makes a POST call to the back end with header:{ 'X-CSRFToken': token} running on localhost:8080 … -
How to use @font-face in django?
SO I downloaded a font and I have woff2 , woff and ttf files inside a fonts directory inside my static folder. Directory structure : project\project\static\fonts STATIC_URL = '/static/' STATICFILES_DIRS = [(os.path.join( BASE_DIR, "project", "static"))] style.css is located in static folder too @font-face { font-family: kinder_boyregular; src: url("{% static '../fonts/kinder-boy-regular-webfont.woff2' %}") format('woff2'), url("{% static '../fonts/kinder-boy-regular-webfont.woff' %}") format('woff'), url("{% static '../fonts/kinder-boy-regular.ttf' %}") format("truetype"); font-weight: normal; font-style: normal;} .header{ width: 800px; width: 300px; margin: 5px; text-align: center; border: 1px green; } .header h4{ font-family: "kinder_boyregular"; } html <div class="container"> <div class=header> <h4>Sparison</h4> </div> </div> But when I load the page, the h4 font doesn't change. What could be the issue? -
Django - add ModelTranslation to already registered model
I want to add fields in my db to translate. I want to use modeltranslation link here. I added my model to translation.py: from .models import GameTask class GameTaskTranslationOptions(TranslationOptions): fields =('name', 'description', 'button_text') translator.register(GameTask, GameTaskTranslationOptions) Now I want to add admin integration. I already added GameTask to admin: @admin.register(GameTask) class GameTaskAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'category', 'game', 'cycle_type', 'points', 'link_to_validity') search_fields = ('name', 'category') link_to_validity = link_to_validity What is the best way to create this connection? -
How do I extend a Django admin form's clean() function?
I have a Django 3.0 Model and associated Admin Add Form. I would like to validate entered data against other data being entered at the same time, the way you can for normal Forms -- making sure two password fields match, for example, or making sure the email and backup email fields are different. It seems like the best way to do this is to extend the clean() function for the Add page's Form, because that's the function you'd use for a normal Form. The documentation seems to give hints that this might be possible, but it doesn't give enough information to put it all together. Web searches for "Django extend Admin Form" return results only for extending the template. How do I extend a Django Admin Add Form's clean() function? -
Django url with parameters for http GET POST and DELETE request
I want to have url like localhost/path/?page=1&per_page=5. The page and per page are optional parameters. How should the URL look like. In views I want to use these parameter in raw PostgreSQL query.