Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Email sending SMTP Error, cant send a mail
I am trying to send email within my Django project: # settings.py EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True def notify_user(email_address, subject='Subject', message='Some message!') -> None: send_mail( subject, message, settings.EMAIL_HOST_USER, [email_address], fail_silently=False ) As I know I need to disable this option (Gmail Security), but Gmail don't let me do it. As a result I got this error: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a056512360e00b00492bbf7db8asm320697lfs.85 - gsmtp') What can I do? How to disable that option? -
Python function to get sytem mac address
I am developing an API using Django rest framework. I need a user's mac address to be in the list of an organization's mac addresses before he is authorized to access the organization's data. But the challenge is that this code returns different mac addresses when the code is hosted and when I am running it on my local machine. I don't know what I am getting wrong. and I really don't know much about networks too. Below is the code class MacAddressPermission: @staticmethod def authenticated(): mac_address = gma() mac_address = mac_address.upper() print("MAC ADDRESS: ", mac_address) return mac_address``` -
Django assigning model FloatField coordinate points to marker coordinates using Mapbox
For my project I have a model that had two FloatFields called lat and lng for coordinate value which I would like to display on an interactive map. Just starting with Django and API's so still very new to a lot of this. animal = models.CharField(max_length=32, choices=ANIMALS, default=BISON) image = models.ImageField(upload_to='images', null=True, blank=True) description = models.TextField(null=True, blank=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) def __str__(self): return self.animal I am not sure how to access these values from my views page so that I am able to use them as {{ Django variables }} within my html template. My views: def homePage(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = PostForm() context = {'form': form} return render(request, 'home.html', context) I want to use a {% for n in posts %} {% endfor %} loop to loop through all the posts in my database add new markers the the map via: var marker = new mapboxgl.Marker() .setLngLat([-110.5885, 44.4280]) .addTo(map); However, these .setLngLat([-110.5885, 44.4280]) values need to be the ones specified from the posts. -
Django isn't authenticating user already logged in through web app frontend using keycloak
I am building an application that uses django as a backend for data processing and management calls served to a Vue3 SPA. I am using Keycloak for authentication and using keycloak-js and mozilla-django-oidc to handle authentication for each. Each work separately fine, I can navigate to the django app, login and see the data behind protected views (and get redirected properly if I a not logged in). Likewise I can login to the frontend and get a token and associated data. I can even login to the django app, then navigate to the frontend and calls are made with the correct session information and it all works fine. The challenge is when I just login to the frontend and make a call to the django app it doesn't recognize it as being an authenticated user request - I am guessing it has something to do with not creating a django session, but am honestly a bit lost at this point. Is there a way to ingest the token information and have django authenticate the user and start a session when the call is made from the frontend? -
How to use react-image-crop with python-django backend cropping?
I am trying to use Python Pillow to crop the images with react-image-crop and it seems to be working fine, but I can not figure out how to set the scale (zooming) to be working with the backend. Any help would be greatly appreciated! Frontend- (React) const scaleX = imgRef.current.naturalWidth / imgRef.current.width const scaleY = imgRef.current.naturalHeight / imgRef.current.height const pixelRatio = 1 const cropX = crop.x * scaleX const cropY = crop.y * scaleY const width = Math.floor(crop.width * scaleX * pixelRatio) const height = Math.floor(crop.height * scaleY * pixelRatio) const formData = new FormData() formData.append('crop_x', cropX) formData.append('crop_y', cropY) formData.append('crop_height', height) formData.append('crop_width', width) formData.append("image", localImage) const response = await axios.post('/image/upload/', formData) Backend - (Django) from PIL import Image temp_image = Image.open(form.image) left_x = float(form.get('crop_x')) top_y = float(form.get('crop_y')) right_x = left_x + float(form.get('crop_width')) bottom_y = top_y + float(form.get('crop_height')) thumbnail_image = temp_image.crop((left_x, top_y, right_x, bottom_y)) -
Query parameter doesn't match any record returns "Select a valid choice. That choice is not one of the available choices." instead of empty array
I'm using DjangoFilterBackend to handle query parameters on a ModelViewSet. My expectation would be that if nothing in the table matches one of the query params, that it would just return an empty array. Instead it returns: { "document_guid": [ "Select a valid choice. That choice is not one of the available choices." ] } Which just seems like an odd response to me so I'm wondering: how can I change this behavior? Would much rather just have the following indicating nothing matched: [] I'm aware of this similar question, but I'm already doing what they suggested: https://stackoverflow.com/a/62219220/3123109 Here's the URI where there are no records that match document_guid (but there are some that match user_guid): localhost/api/d2u/?user_guid=55d57235-79b0-ec11-9840-000d3a5a343c&document_guid=df4c9c11-49dd-ec11-a7b6-000d3a3667a1 Here's the related code: # views.py class Document2UserSyncViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filter_fields = [ 'id', 'document_guid', 'user_guid' ] permission_classes = [PowerAutomatePermissions] queryset = Document2User.objects.all().order_by('id') serializer_class = Document2UserSerializer # serializer.py class Document2UserSerializer(serializers.ModelSerializer): """Serializer for the d2u model. Returns all fields. """ class Meta: model = Document2User fields = '__all__' # models.py class Document2User(models.Model): document_guid = models.ForeignKey( Documents, to_field='guid', on_delete=models.CASCADE, db_column='document_guid' ) user_guid = models.ForeignKey( CRMFields, to_field='guid', on_delete=models.CASCADE, db_column='user_guid' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'document_to_user' unique_together = [['user_guid', 'document_guid']] -
Load data from model in view.py Django
I just started with Django and Python and I still don't understand it very well. Would it be possible to access all the information stored in Persons, showing also orderstext and archivename, I can't manage to do it :( my idea is to get all the information and save it as JSON, but I'm not getting the info from orderstext and archivename, it would be great if someone could show me the right way. models.py from django.db import models class Order(models.Model): order_id = models.PositiveIntegerField(blank=True, null=True) orderstext = models.CharField(max_length=250, blank=True, null=True, ) order_start = models.DateTimeField(blank=True, null=True) order_end = models.DateTimeField(blank=True, null=True) @property def default(self): return self.orderstext class Meta: managed = False db_table = 'order' class Archives(models.Model): archive_id = models.AutoField(primary_key=True, null=False) archivename = models.CharField(max_length=50, unique=True, blank=True, null=True) deleted = models.IntegerField(blank=True, null=True) def __str__(self): return self.archivename @property def default(self): return self.archivename class Meta: managed = False db_table = 'archives' class Clients(models.Model): name = models.CharField(max_length=20, verbose_name="Name") lastname = models.CharField(max_length=50, blank=True, null=True, verbose_name="Lastname") archives = models.ForeignKey('Archives', db_column='archive_id', on_delete=models.CASCADE, null=True, verbose_name="Archives") order = models.ForeignKey('Order', db_column='order_id', on_delete=models.CASCADE, null=True, verbose_name="Order") coments = models.CharField(max_length=250, blank=True, null=True, verbose_name="Coments") class Meta: managed = False db_table = 'clients' views.py from django.http import JsonResponse from .models import Clients def data_json: info = list(Clients.objects.all().values()) response … -
Can't find the Django Docs that list DetailView attributes
Working through the Django tutorial and on the Detail and List class-based views portion. When I go to the docs for the DetailView, it doesn't really list any of the attributes I can use or the tutorial uses. Any chance someone has a link to the page where I can read up on attributes like: -Model -Context_object_name -template_name -etc... I just like to understand what Im doing a bit more than the tutorial explains, just cant seem to find the proper docs when googling :( -
Running aggregate function on Django queryset union with renamed fields raises django.db.utils.DatabaseError
I am using Django 3.2 I am trying to create a query that queries two different models and does the following: renames the returned columns (so the queries can be 'union'ed together 'unions' the two querysets (after column rename using annotate) tries to run an aggregate function Sum on the union (this is where it barfs). This is a simplified version of my codebase: Models class EventCategory(models.Model): name = models.CharField(max_length=16) class Event(models.Model): name = models.CharField(max_length=32) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) class Tournament(models.Model): name = models.CharField(max_length=32) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) prize_money = models.IntegerField() class TournamentAward(models.Model): awardee = models.ForeignKey(setting.AUTH_USER_MODEL, on_delete=models.CASCADE) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Game(models.Model): player = models.ForeignKey(setting.AUTH_USER_MODEL, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) payment = models.SmallPositiveInteger() created_at = models.DateTimeField(auto_now_add=True) Queries payment_earned_today = Game.objects.filter( player=user, created_at__year=year, created_at__month=month, created_at__day=day ).annotate(category=models.F('event__category'))\ .only('category','payment') tournament_prize_today = TournamentAward.objects.filter( awardee=user, created_at__year=year, created_at__month=month, created_at__day=day ).select_related('tournament__category')\ .annotate(category=models.F('tournament__category'))\ .annotate(payment=models.F('tournament__prize_money'))\ .only('category','payment') # Union the two querysets ... union_queryset = payment_earned_today.union( tournament_prize_today ) results = union_queryset.aggregate(total=models.Sum('payment')) On the line when I try to calculate the total, I get the following error: django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements How can I union two models and calculate an aggregate function on the union? -
Django Signals Python
In this piece of code i want to get text from reacently created data in model models.py: from django.db import models class Tokenize(models.Model): text = models.TextField() class Pos(models.Model): POS_TAGS = [ ('NOUN', 'NOUN'), ('ADJ', 'ADJ'), ('NUM', 'NUM'), ('PRON', 'PRON'), ('ADV', 'ADV'), ('VERB', 'VERB'), ('CNJ', 'CNJ'), ('ADP', 'ADP'), ('PRT', 'PRT'), ('INTJ', 'INTJ'), ('MOD', 'MOD'), ('IMIT', 'IMIT'), ('AUX', 'AUX'), ('PPN', 'PPN'), ('PUNC', 'PUNC'), ('SYM', 'SYM') ] token = models.CharField(max_length=150) pos = models.CharField(max_length=150, choices=POS_TAGS, null=True, default='NOUN') signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from .models import Tokenize, Pos from uztagger import Tagger Uztagger tags each word in text example: input: "White board" output: [('White', 'ADJ'), ('board', 'NOUN')] but it's for Uzbek language @receiver(post_save, sender=Tokenize) def create_profile(sender, instance, created, **kwargs): tagger = Tagger() if created: text = instance.text # there i should get text of receantly created data tokens = tagger.pos_tag(text) for token in tokens: a = Pos(token=token[0], pos=token[1]) # and there i should create tagged data a.save() I should get data from instace and post in other model -
How to pass a variable into a django admin page?
I have an app in my django project, and I need to display a list in one of its model's templates. How to pass the variable of this list to this model's template? ! I know that there are some almost simular questions but I didn't really understand the answers so they didn't help me. If you have read to this line, thank you a lot for your attention. -
Django file based email backend
It's probably something very obvious, but I can't seem to figure it out. This snippet is from Django's file based email backend (django.core.mail.backends.filebased.py) def write_message(self, message): self.stream.write(message.message().as_bytes() + b"\n") My question is. How can I find out what class is message an object of? Context for why: My code sends emails along various execution paths. I want to leverage Django's filebased backend, instead of firing live emails during debugging and unit testing (or creating my own file based system). The relevant code has a MIMEMultipart object currently (with utf-8 coded text) that works fine for production. I need to be able to convert that into an object that can be printed legibly by the above snippet. PS: I come from a C++ background where this would've been an easy question to answer. -
Getting error 'context must be a dict rather than set.' when trying to retrieve single object where id=id in django Model
I can't make work my detail function to simply retrieve all fields of only one Model element. my code is : views.py def band_detail(request, id): band = Band.objects.get(id=id) return render(request, 'bands/band_detail.html', {'band', band }) in urls.py I wrote: path('bands/<int:id>/', views.band_detail) So, when I am going to /bands/{id} it should show me my band_details.html page : {% extends 'listings/base.html' %} {% block content %} <h1> {{ band.name }} </h1> {% if band.active %} <h2> Active : <i class="fa-solid fa-check"></i> </h2> {% else %} <h2> Active : <i class="fa-solid fa-xmark"></i> </h2> {% endif %} {% endblock %} but instead I get a typeError telling me : 'context must be a dict rather than set.' error page I guess this is due to the way I retrieve my Band object from id. But I can't wrap my mind around. That is why I am coming for a lil help. Thanks in advance -
django loading seeds not working - loaddata
I have created the following seed to load into my database [ { "model": "authentication.role", "fields": { "description":"admin", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } }, { "model": "authentication.role", "fields": { "description":"leader", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } }, { "model": "authentication.role", "fields": { "description":"user", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } } ] when I run the command to load the seeds python3 manage.py loaddata core/seeds/role.json I receive the message that they have been inserted correctly. but only the last record of the object appears in my database why if django tells me that 3 records were inserted only one appears? this is my model class Role(models.Model): id = models.CharField(default=str(uuid.uuid4()), max_length=255, unique=True, primary_key=True, editable=False) description = models.TextField(blank=True) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, default=None) -
Django/Wagtail Snippet Serializer in API
I have added wagtail CMS's blog author in my 'models.py' also exposed it in API, but it's showing like this in API "blog_authors": [ { "id": 1, "meta": { "type": "blog.BlogAuthorsOrderable" } } ], Here's the models.py code class BlogAuthorsOrderable(Orderable): """This allows us to select one or more blog authors from Snippets.""" page = ParentalKey("blog.AddStory", related_name="blog_authors") author = models.ForeignKey( "blog.BlogAuthor", on_delete=models.CASCADE, ) panels = [ # Use a SnippetChooserPanel because blog.BlogAuthor is registered as a snippet SnippetChooserPanel("author"), ] @register_snippet class BlogAuthor(models.Model): """Blog author for snippets.""" name = models.CharField(max_length=100) website = models.URLField(blank=True, null=True) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.SET_NULL, null=True, blank=False, related_name="+", ) panels = [ MultiFieldPanel( [ FieldPanel("name"), # Use an ImageChooserPanel because wagtailimages.Image (image property) # is a ForeignKey to an Image ImageChooserPanel("image"), ], heading="Name and Image", ), MultiFieldPanel( [ FieldPanel("website"), ], heading="Links" ) ] def _str_(self): """String repr of this class.""" return self.name class Meta: # noqa verbose_name = "Blog Author" verbose_name_plural = "Blog Authors" How do I serialize like this show author name, website, image and id? I tried to Serialize the BlogAuthor class AuthorSerializer(serializers.ModelSerializer): class Meta: model = BlogAuthor fields = ( "id", "name", "website", "image", ) And here is the API field APIField("blog_authors", serializer=AuthorSerializer(many=True)), When I … -
pass a variable between multiple custom permission classes in drf
I have a base permission class that two ViewSets are sharing and one other permission class each that is custom to each of the ViewSets, so 3 permissions all together, is there a way to pass a specific variable down from the base permission class to the other permission classes? My setup looks like this: class BasePerm(permissions.BasePermission): def has_permission(self, request, view): some_var = # call an API using request variable class Perm1(permissions.BasePermission): def has_permission(self, request, view): # get the value of some_var from BasePerm class Perm2(permissions.BasePermission): def has_permission(self, request, view): # get the value of some_var from BasePerm class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [BasePerm, Perm1] class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [BasePerm, Perm2] -
How can I get cleaned_data from html form?
I have django app with class based view and form written in html: <form method="post" action="{% url 'personal-account' %}"> {% csrf_token %} <div class="page slide-page"> <div class="field"> <input type="text" placeholder="First name" class="input_1" name="first_name" size="1" value="{{ data.first_name }}"> <input type="text" placeholder="Last Name" class="input_2" name="last_name" size="1" value="{{ data.last_name }}"> </div> <div class="middle"> <input type="text" placeholder="Username" class="input_3" name="username" size="1" value="{{ data.username }}"> <input type="text" placeholder="Email" class="input_6" name="email" size="1" value="{{ data.email }}"> </div> <div class="last"> <input type="password" placeholder="Password" class="input_4" name="password" size="1" value="{{ data.password }}"> <input type="password" placeholder="Confirm" class="input_5" name="confirm_password" size="1" value="{{ data.confirm_password }}"> </div> <div class="field"> <button type="submit" class="submit-btn">Submit</button> </div> </div> </form> View class PersonalSignup(View): def post(self, request): return render(request, 'authentication/personal_signup.html') def get(self, request): return render(request, 'authentication/personal_signup.html') Now I want to get all values from inputs(first_name, last_name...) with cleaned_data. -
As a Benevole, how i can create a view for participate in a given mission [closed]
models.py class ProfileBenevole(models.Model): ville = [ ('--Aucun--', '--Aucun--'), ('Agadir', 'Agadir'), ('Casablanca', 'Casablanca'), ('Essaouira', 'Essaouira'), ('Fes', 'Fes'), ('Marrakech', 'Marrakech'), ('Meknes', 'Meknes'), ('Oujda', 'Oujda'), ('Rabat', 'Rabat'), ('Tanger', 'Tanger'), ('Tetouan', 'Tetouan'), ] activiter_prefere = ( ('Cadre', 'Cadre'), ('Salarié', 'Salarié'), ('Sans emploi', 'Sans emploi'), ('Commercent', 'Commercent'), ('Etudiant', 'Etudiant'), ('Autre', 'Autre'), ) user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) telephone = models.CharField(max_length=20,null=True) adresse = models.CharField(max_length=100,null=True) date_naissance = models.DateTimeField(auto_now_add=True, null=True) cin = models.CharField(max_length=12, null=True) domaine_experience = models.TextField(null=True) biographie = models.TextField(null=True, blank=False) activiter_prefere = models.CharField(max_length=100, choices=activiter_prefere) ville =models.CharField(max_length=100,choices=ville) def __str__(self): return self.user.username class Mission(models.Model): domaine_prefere = ( ('Sport', 'Sport'), ('Santer', 'Santer'), ('Soutien Scolaire', 'Soutien Scolaire'), ('Aides Sociales', 'Aides Sociales'), ('Entreprenariat', 'Entreprenariat'), ('Informatique', 'Informatique'), ('Animation', 'Animation'), ) nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() date_modification=models.DateTimeField(auto_now=True) domaine=models.CharField(max_length=20, choices=domaine_prefere) lieu=models.CharField(max_length=50,null=False,blank=False) nombre_participant=models.CharField(max_length=50,null=False,blank=False) photo_mission = models.ImageField( upload_to='uploads/images',null=True,blank=True) slug=models.SlugField(null=True,blank=True) participe=models.ManyToManyField(ProfileBenevole,related_name='participer') class Meta: ordering = ('-date_publier',) def save(self,*args, **kwargs): if not self.slug: self.slug=slugify(self.nom) super(Mission,self).save(*args, **kwargs) def __str__(self): return self.nom -
how to access foreign table field in django view
I have two models, the plans model & plans features ( foreign relation with plans table), given below: Following is the view which returns an object of features for each plan: Now I want to access, the "price" field of the plans table (model). How this is possible? my Django template is the following which doesn't work: I belive there is solution to this, I would love hear from you . thank you -
how to run function encryption in django
so i have function for encryption in views.py. the file is saved at models. i want to run the function to know if the function is work. but i don't know how to run the function or code in urls.py here's my views.py : key_bytes = 16 testaudio = Audio_store.objects.all().values_list('audio').last() key = 'testing' # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testaudio): assert len(key) == key_bytes print(testaudio) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key, AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testaudio) print(iv) print(ciphertext) return (iv, ciphertext) testaudio got by user add it from html. -
Django Numpy ImportError with Apache but not on runserver
so i've tried every other thread and their suggested solutions but without success so far. I have a Django app with a virtualenv and Apache 2.4 and mod_wsgi, which i developed on other server. Now, I'm migrating (rebuilding from scratch) everything on another server. While everything else works, when i tried to install pandas, the app served through Apache throws me an ImportError for Numpy. Original error was: /optilab/env/lib64/python3.6/site-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object Thing is, this doesn't happen while using runserver with manage.py . Everything is the same: Python Version (3.6.8), Python Executable (/optilab/env/bin/python) except the Python Path order. For the testing runserver, this is the Python Path list: ['/optilab', '/optilab/env/lib64/python3.6/site-packages', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/home/appuser/.local/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/env/lib64/python3.6/site-packages'] But, for the app served through Apache, the Python Path is: ['/optilab', '/optilab/core', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages'] I suspect that the list order is the culprit for this problem, but it seems i'm not able to change it. My file structure is the following: /optilab /core <-- startproject directory /env <-- virtualenv files /static /media ... other apps This is the first part of my apache config (BTW, I tried … -
Docker domain name not redirecting to HTTP or HTTPS
I have deployed a Django project using Docker and Nginx. All the process has gone well, but I am having a little issue. I am using certbot for HTTPS, and the redirection from HTTP to HTTPS works fine, but the problem is when I just type the domain name, without HTTP or HTTPS. If I type just the domain name in the URL (example.com) page doesn't load. And if y type http://example.com or https://example.com, everything works perfect. What could be the problem? How can I do to redirect the domain name to HTTPS? My Nginx configuration is the next one: server { listen 80; server_name ${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www/; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam /vol/proxy/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } -
Error while installing psycopg2 using pip
I am trying to run docker in django using this command docker build -t myimage . Now the docker file tries to run the RUN pip install -r /app/requirements.txt --no-cache-dir but when ot gets to the Downloading psycopg2-2.9.3.tar.gz (380 kB) section, it throws the error. NOTE: i do not have psycopg2 in my requirements.txt file only the psycopg2-binary. requirements.txt file ... dj-database-url==0.5.0 Django==3.2.7 django-filter==21.1 django-formset-js-improved==0.5.0.2 django-heroku==0.3.1 psycopg2-binary python-decouple==3.5 ... Downloading pytz-2022.2.1-py2.py3-none-any.whl (500 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 500.6/500.6 kB 2.6 MB/s eta 0:00:00 Collecting psycopg2 Downloading psycopg2-2.9.3.tar.gz (380 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 380.6/380.6 kB 2.7 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info writing /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI … -
Django : Transfer data to another view by a button
I have a table of clients where each line has a button to redirect to another page with the id of the client. I do not want that it is on the URL, so I want to avoid a GET method, it is why I thought to us a POST method with the buttons. I did something but it is not working, I have an error message "Method Not Allowed (POST)" with the specific URL. html <table id="customers" class="table table-sortable"> <tr> <th>Référence Client</th> <th>Client</th> <th>Edit</th> </tr> {% for client in query_list_client %} <tr> <td>{{ client.id }}</td> <td>{{ client }}</td> <td> <a href="{% url 'modifyclient' uuid_contrat uuid_group % }" class="btn btn-primary" >Modify</a> <form action="{% url 'selectsaletype' uuid_contrat uuid_group %}" method="POST"> {% csrf_token %} <button name = 'client' type ='submit' value="{{ client.id }}" class='btn btn-secondary' > Select </button> </form> <!-- <a href="{% url 'selectsaletype' uuid_contrat uuid_group client.id % }" class="btn btn-secondary" >Selectionner</a> --> </td> </tr> {% endfor %} </table> urls urlpatterns = [ path('<str:uuid_contrat>/<str:uuid_group>/sales/selectclient/', ListSelectClient.as_view(), name="selectclient"), path('<str:uuid_contrat>/<str:uuid_group>/sales/selectsaletype/', SelectSaletType.as_view(), name="selectsaletype"), ] views class SelectSaletType(ListView): model = ListSaleType paginate_by =10 template_name = 'sales/selectsaletype.html' context_object_name = 'query_sale_type' def get_context_data(self, *args, **kwargs) : context = super(SelectSaletType, self).get_context_data(*args, **kwargs) context['uuid_contrat'] = self.kwargs['uuid_contrat'] context['uuid_group'] = self.kwargs['uuid_group'] print(self.request.POST) return … -
Test form_valid() in Createview
I am trying to test one of my CreateViews. The whole view looks like this: class BookCreate(CreateView): model = Book form_class = BookForm template_name = 'base/components/form.html' def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse( status=204, headers={ 'HX-Trigger': json.dumps({ "bookListChanged": None, }) }) The part of the view that needs testing according to coverage.py is this part: form.instance.user = self.request.user form.save() return HttpResponse( My test right now looks like this: class TestBookViews(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(email='test@gmail.com', password='teSTpassword123') self.client.login(email='test@gmail.com', password='teSTpassword123') return super().setUp() def test_book_create(self): response = self.client.post(reverse('base:book-create'), { 'name': 'TestBook', 'user': self.user, 'publishing_date': '2022-08-17', }) self.assertEqual(response.status_code, 204) But this test does not make it covered. What I am missing?