Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix VercelEerror python setup.py egg_info did not run successfully
I'm trying to deploy a Django web app on Vercel, but the deployment fails with the following message: Error: enter code hereCommand failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt 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-xergdc3a/psycopg2.egg-info writing /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-xergdc3a/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-xergdc3a/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 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Can someone help me? Thank you. -
How to get a parameter from a form and insert it in the url with django?
I am a beginner with django. I want to get a parameter that the user has to enter from a form. This parameter must be visible in the url except that the django server returns an error because the parameter is empty. Here is what I did: This is my template: <form method="POST" action="{% url 'direct_aeg' id_aeg %}" enctype="multipart/form-data"> {% csrf_token %} {{form}} <div class="input-field button"><input type="submit" name="submit_btn" value="Recherche AEG"></div> </form> this is my forms.py: from django import forms class Form_direct_aeg(forms.Form): id_aeg = forms.IntegerField(label="N° AEG",required=True) this is my views.py def direct_aeg(request,id_aeg): # doing some_stuff def show_aeg_tool(request): if request.method == 'POST': form = Form_direct_aeg(request.POST) if form.is_valid(): id_aeg = form.cleaned_data['id_aeg'] url = str(id_aeg) # return redirect(url) else: form = Form_direct_aeg() . . . . this is my urls.py path('a/b/c/d/direct_aeg/<int:id_aeg>', aeg.direct_aeg, name='direct_aeg'), as soon as I load the page I get the following error: Reverse for 'direct_aeg' with arguments '('',)' not found. 1 pattern(s) tried: ['a/b/c/d/direct_aeg/(?P<id_aeg>[0-9]+)\\Z'] I have this error because the id_aeg parameter must be initialized. How to solve this problem? -
Custom Select2 form not posting selected value on Submit
This is a really complex customization of a django form using an external endpoint to generate the autocomplete so dont blame me for the horrible code... But I would love to know why the request.body dont have the selected value on POST... <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="SySOrQ0mzaXY8yGOHcO8OCktWOFBLSCvYPNQI8sic8gJ8lndaPBh1SBu1qRAaAK6"> <input type="hidden" name="pk" value="4"> <!-- We present Dynamic Question --> <input type="hidden" name="endpoint" value="https://media.seenka.com/api/programs/brand-autocomplete/?q=" id="id_endpoint"> <select name="value" id="id_value" data-autocomplete-light-language="en" data-autocomplete-light-url="/front/generic_autocomplete/" data-autocomplete-light-function="select2" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true" data-select2-id="id_value"> <option value="32377" data-select2-id="14">Evagina</option> </select> <span class="select2 select2-container select2-container--default select2-container--below select2-container--focus" dir="ltr" data-select2-id="2" style="width: 22px;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-disabled="false" aria-labelledby="select2-id_value-container"> <span class="select2-selection__rendered" id="select2-id_value-container" role="textbox" aria-readonly="true" title="Evagina"> <span class="select2-selection__clear" title="Remove all items" data-select2-id="16">×</span> Evagina </span> <span class="select2-selection__arrow" role="presentation"> <b role="presentation"></b> </span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span> <div style="display:none" class="dal-forward-conf" id="dal-forward-conf-for_id_value"> <script type="text/dal-forward-conf">[{"type": "field", "src": "endpoint"}]</script> </div> <input type="submit" value="Submit"> </form> can you find what is wrong with this html form already selected that when I press the submit button the response.body is: {'pk': '4', 'data': {'username': 'mmandrille', 'values': []}}? -
How to display searched item for users, but all items only for admins?
There is a page where the list of elements is displayed. Also, there is a search to display elements that have the requested value. I have an account and access control, some elements of the site are visible to everyone, and some only through the account. The problem is that I need to remove the display of the entire list of elements for the guest, but leave the display of the element based on the search results. Now I have restricted access to the entire list of items, and the user does not see the items in the search results. How to fix it? Home.html {% extends 'base.html' %} {% block content %} <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> {% if user.is_authenticated %} <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> {% endif %} {% endblock %} Urls.py from django.urls import path #from . import views from .views import HomeView, Search urlpatterns = [ path('', HomeView.as_view(), name="home"), path('search/', Search.as_view(), name="search"), Views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' … -
How to have only redoc url in drf-spectacular
I'm using drf-spectacular for my django project: https://github.com/tfranzel/drf-spectacular On urls.py I have this: urlpatterns = [ # YOUR PATTERNS path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), ] I just want to have 'api/schema/redoc/' so I removed the other two URLs. After removing 'api/schema/' I get the following error: Reverse for 'schema' not found. 'schema' is not a valid view function or pattern name. How can I remove that URL but resolve the error -
Docker + Django + Postgres doesn't work. ERROR: Is the server running on that host and accepting TCP/IP connections? [duplicate]
I'm trying to run docker container with django + postgres. When i run two containers (db + web) i see that it's ok on the db side: LOG: starting PostgreSQL 12.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 8.3.0) 8.3.0, 64-bit LOG: listening on IPv4 address "0.0.0.0", port 5432 LOG: listening on IPv6 address "::", port 5432 LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" LOG: database system was shut down at 2023-02-13 14:36:17 UTC LOG: database system is ready to accept connections But on the django side i see the error: django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? DockerFile: FROM python:3.10.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml: version: '3.9' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=my_admin - POSTGRES_PASSWORD=my_api - POSTGRES_DB=my_db volumes: postgres_data: Also, i have this setting in Django: ALLOWED_HOSTS = ['127.0.0.1', 'localhost', '0.0.0.0', '::1'] … -
Django allauth Configuration
I have implemented Django allauth as a method of authenticating users. I am using Django allauth in an attempt to try and handle multi user authentication system. Now when I omit "username" field in my forms.py file, Django complains of the integrity error as below. IntegrityError at /accounts/accounts/student UNIQUE constraint failed: accounts_user.username Request Method: POST Request URL: http://127.0.0.1:8000/accounts/accounts/student Django Version: 4.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.username Exception Location: /home/offensive/Desktop/Target/.venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: accounts.views.StudentSignUpView Python Executable: /home/offensive/Desktop/Target/.venv/bin/python Python Version: 3.8.10 Python Path: ['/home/offensive/Desktop/Target', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/offensive/Desktop/Target/.venv/lib/python3.8/site-packages'] Server time: Mon, 13 Feb 2023 14:14:23 +0000 below is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.contrib.auth import get_user_model from django.db import transaction from .models import Student, User, Writter class StudentSignUpForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = get_user_model() fields = ( "email", # "username", ) @transaction.atomic def save(self): user = super().save(commit=False) user.email = self.cleaned_data.get('email') user.is_student = True user.save() student = Student.objects.create(user=user) return user class WritterSignUpForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) phone = forms.CharField(required=True) address = forms.CharField(required=True) class Meta: model = get_user_model() fields = ( "email", # "username", "phone", "address", ) By default, I think Django allauth … -
How to set ManToManyField to None?
I have a Section model for storing different sections of laws. A law has Part, Book, Chapter, Title, Section, SubSection, ... and Article Instead of making models for each of the above parts, I created a section model to store the sections in the database. The level field in the section model specifies the depth of levels. as you can see in the picture. class Section(Timestamped): parent = models.ManyToManyField( to='self', verbose_name=_("Parent Section"), help_text=_("Specifies the links to another section."), blank=True, symmetrical=False ) level = models.PositiveIntegerField( verbose_name=_("Level of the section"), ) ... My problem is that when I store the first section or level, the parent should be set to null(which means that the first section has no parent). But I get an error when I set the parent to None. I have all the sections in a JSON file: The script for section in sections: section_data = { "text_id": section.get("id"), "level": 1, } section_db, created = Section.objects.get_or_create(**section_data) section_db.parent.add(None) The error django.db.utils.IntegrityError: null value in column "to_section_id" of relation "laws_section_parent" violates not-null constraint DETAIL: Failing row contains (3, 22, null). Is there any solution? Are the models correctly designed? -
Jinja html code gets incorrectly formatted when saved in VS code
I am writting a Django project using VS Code. I find a strange Jinja formatting issue. What I want is {% extends "../base.html" %} {% load static %} {% block title %} {% if category %} {{ category.name }} {% else %} Products {% endif %} {% endblock %} {% block content %} {% endblock content %} But when I save the file or ctrl+s, it gets formatted like {% extends "../base.html" %} {% load static %} {% block title %} {% if category %} {{ category.name }} {% else %} Products {% endif %} {% endblock %} {% block content %} {% endblock content %} and the render gets error due to broken brackets. I am using Jinja2 Snippet Kit and Prettier plugins. Do I need to make some changes in setting? Could someone give me a help? Thank you. -
Django blog post views count adds two instead of one
I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly Models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() from ckeditor_uploader.fields import RichTextUploadingField class Subscribe(models.Model): email = models.EmailField() class Comments(models.Model): name = models.CharField('Name', max_length=120) post_id = models.IntegerField(null=True) email = models.EmailField() website = models.URLField(max_length=200) comment = models.TextField(blank=True) date_created = models.DateTimeField(blank=True,null=True) def publish(self): self.date_created=timezone.localtime(timezone.now()) self.save() class Category(models.Model): name = models.CharField('Name', max_length=120) slug = models.SlugField(default="", null=False) def __str__(self): return self.name class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = RichTextUploadingField() image = models.ImageField(upload_to='images/', null=True) slug = models.SlugField(default="", null=False) views = models.IntegerField(default=0) def __str__(self): return self.user.username def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) class Post(models.Model): title = models.CharField('Post Title', max_length=120) date = models.DateTimeField() status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft') category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,) author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,) details = RichTextUploadingField() slug = models.SlugField(default="", null=False) image = models.ImageField(upload_to='images/', null=True) post_views = models.IntegerField(default=0) … -
Django UniqueConstraint not working as expected
At the moment I am using the following condition to avoid duplicates MyModel.objects.filter(other_model=self, ended__isnull=True, started__isnull=False).exists() which works, however due to unfortunate caching etc. in the past there were duplicate instances of this. I want to move this exact check to the database level with Django. I tried different constraints using a simple unique_together ([['other_model', 'ended']]) constraint and constraints = [ models.UniqueConstraint(fields=['other_model', 'ended'], name='unique_name', condition=models.Q(ended__isnull=True)) ] This is my testcase, which runs without a problem (which it shouldn't) ts = timezone.now() MyModel.objects.create(other_model=same_instance, ended=ts, started=ts) MyModel.objects.create(other_model=same_instance, ended=ts, started=ts) This is the latest migration (I even reset the entire DB and reapplied all migrations): migrations.AlterUniqueTogether( name='mymodel', unique_together={('other_model', 'ended')}, ), -
How to send data to particular users in Web Sockets?
I am implementing web sockets in my Django Project with channels library. When an object is created, name of that object should be sent to a consumer with group name test_consumer_group_1. class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is the code of my consumer: class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") data = json.loads(event["value"]) print(data) obj_name = data["current_team"] response = { "obj_name": obj_name } self.send(text_data=json.dumps(response)) How to send data to a particular employee only inside send_notification function? e.g. If a super admin has created an object of MyClass, data should be sent to only those members who are added in members attribute? -
How can I keep track of user selections on each page of a questionnaire using django-formtools till final submission?
I am new to Django and looking to write a small questionnaire containing about 300 or more questions. I just learnt of django-formtools it it seems like what I needed. I have searched without success as to how to start. Assuming each page contains 10-20 questions, how can I keep track result of each page and then display the final result on the final page (the done method) I believe? As I am new to this, the more specific the better. I have search all over and there's nothing related to my objective. -
Pytest - @pytest.mark.parametrize() how to use when changes in one field in post request
I'm really sorry but i dont know how to describe my problem in one line so please change if its wrong. so the problem is i'm using unit test in my drf test cases and there are two test cases such as def test_with_blank_addressstate(self): # view = order_list, method = POST # user = Normal # Country = IN, state = "" self.client.login( username=self.order.owner.username, password="normal" ) url = reverse("order_list") self.order["addressstate"] = "" response = self.client.post(url, self.order, format="json") self.assertIn( "{'addressstate': [ErrorDetail(string='This field is required.'", response.data["error"]["description"], ) def test_with_incorrect_addressstate(self): # view = order_list, method = POST # user = Normal # Country = IN, state = GJJ(Incorrect) self.client.login( username=self.order.owner.username, password="normal" ) url = reverse("order_list") self.order["addressstate"] = "SRJ" response = self.client.post(url, self.order, format="json") self.assertIn( "{'addressstate': [ErrorDetail(string='This field is required.'", response.data["error"]["description"], ) both test cases i perfectly fine. but my test cases are increasing, i want to test every field for different-different data. for the above test cases if i want to create only one test case and only want to change the field addressstate every time in post request so i can test it different-different data. i never used pytest only know the basic.but i think i can do this using pytest. can … -
Django Unique Constraint Specific Field
I have a A model which uses model B and C as ForeignKeys. In A model, I want to create a constraint that lets saving only if model B and 'xyz' field in C model are unique. When I do it as follows, it did not work. How can I achieve this? class A(models.Model):: B = models.ForeignKey("B", on_delete=models.CASCADE) C = models.ForeignKey("C", on_delete=models.CASCADE) class Meta: unique_together = [ ('B' , 'C.xyz') ] -
An exception is being raised when testing websocket with POSTMAN
I am implementing web sockets in my Django Project with channels library. When an object is created, name of that object should be sent to a consumer with group name test_consumer_group_1. class MyClass(models.Model): name = models.CharField(max_length=128, unique=True) members = models.ManyToManyField("Employee") def save(self, *args, **kwargs): super().save(*args,**kwargs) channel_layer = get_channel_layer() data = {"current_obj":self.name} async_to_sync(channel_layer.group_send)( "test_consumer_group_1",{ 'type':'send_notification', 'value':json.dumps(data) } ) This is the code of my consumer: class TestConsumer(WebsocketConsumer): def connect(self): self.room_name="test_consumer" self.room_group_name = "test_consumer_group_1" async_to_sync(self.channel_layer.group_add)( self.channel_name, self.room_group_name ) self.accept() print('connected..') self.send(text_data=json.dumps({'status':'connected'})) def recieve(self, text_data): print(text_data) def disconnect(self, *args, **kwargs): print('disconnected') def send_notification(self, event): print("send_notification called") print(event) But it gives following error when testing the websocket API with POSTMAN: raise TypeError(self.invalid_name_error.format("Group", name)) TypeError: Group name must be a valid unicode string with length < 100 containing only ASCII alphanumerics, hyphens, underscores, or periods, not specific.be2251de4bb647c1988845bd460d6971!564c92a792634237bcdba63290554557 WebSocket DISCONNECT /ws/test/ [127.0.0.1:35480] How to fix it? -
How to pass request field into Django test?
I have a function: def test_function(request): return request.device.id which connected to endpoint /test_end/ I need to write a unittest but not working -> request.device is None Test looks like this: from django.test import TestCase from django.test.client import Client class Device: def __int__(self, _id): self.id = _id class MyTest(TestCase): def test_device(self): client = Client() response = client.get("/test_end", device=Device(42)) How to fix it? I need to pass device to function into request -
django Sitemap class alternates not rendering sitemap.xml
I have a problem with adding alternates attribute to my sitemaps.py sitemaps.py class StaticViewSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'weekly' protocol = 'https' i18n = True alternates = True def alternate_hreflangs(self, obj): return [('en-us', obj.alternative_object_url), ] def items(self): return ['index','about', 'contact', 'why', 'product', 'tender-management', 'e-sourcing', 'network', 'faq'] def location(self, item): return reverse(item) when I set the alternates = True my sitemap.xml file broke and show a string file https://example.com/en/weekly0.5https://example.com/en/about/weekly0.5https://example.com/en/contact/weekly0.5 Instead of <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.com/en/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://example.com/en/about/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://example.com/en/contact/</loc> <changefreq>weekly</changefreq> <priority>0.5</priority> </url> I get this problem only when adding the alternates = True my sitemap.xml -
How to check Django Form Submission Against Value in Database Table
I am trying to create a function in my views.py that checks a users date submission against values already submitted to the database: def make_booking(request): if request.method == 'POST': form = BookingForm(request.POST) if form.is_valid(): new_date = form.cleaned_data.get("date_of_booking") existing_booking = Booking.objects.get('date_of_booking').items() for booking in existing_booking: if booking == new_date: messages.success(request, "THIS DATE IS ALREADY TAKEN") else: form.save() print('form saved') if request.user.is_authenticated: return redirect(get_bookings) if not request.user.is_authenticated: return redirect(get_bookings_guest) If the date already exists in the database then I want it to show a message saying the date already exists. I have written the above which seems correct to me but I get this error: "Exception Value: too many values to unpack (expected 2)". Please could someone help me? -
Filter a Django table with multiple entries for each user and get the latest one
I have this model: class UserStatus(models.Model): """ This model builds the user status model. """ user = models.ForeignKey(MyUser, on_delete=SET_NULL, null=True) rest_mode = models.BooleanField(default=False) tags = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) How can get the latest entry for each user, then get only the ones with rest_mode == True? -
Access Model attribute depending on URL parameter in Django
Is it possible to dinamically change a variable name in template? In the view below I am sending to the template an url parameter called sl. is it possible to pass that sl to the {{ devize.sl{{sl}} }} so that it changes dinamicaly ? thank you @login_required def slList(request,centrudecost,SL): queryset = Deviz.objects.filter(centrudecost_id=centrudecost) sl = SL print(centrudecost) return render(request, "proiecte/sl_list.html", {"queryset": queryset,"sl":sl}) {% for devize in queryset %} <td>{{ devize.sl{{sl}} }}</td> {% endfor %} -
Building own SIEM system on django
I am currently working on own siem system, where windows logs(in csv format) automatically collecting every hour and displaying in a Highcharts. The backend is Django. But ran into problems: There's too many data that GPU of browser is load. I set auto parsing to per 1 hour but site not displaying. Other parts of code are working Is it ok if I write logs in database? Can anyone give me advices how to do it right? Here is my Javascript code in template/dashboard _categories = {{categories|safe}}; _values = {{values|safe}}; _data = {{data|safe}}; Highcharts.chart('pie', { colors: ['#558dfa', '#a1c1fe', '#4c72bc', '#3a61ad'], title: { text: '' }, chart: { type: 'pie' }, tooltip: { valueSuffix: '%' }, plotOptions: { pie: { allowPointSelect: false, cursor: 'pointer', dataLabels: { enabled: false }, showInLegend: false } }, series: [{ name: 'Percentage', colorByPoint: true, data: [ { name: 'Critical', y: {{range.0}} }, { name: 'Error', y: {{range.1}} }, { name: 'Information', y: {{range.2}} }, { name: 'Warning', y: {{range.3}} }, ] }] }); Highcharts.stockChart('container', { chart: { alignTicks: false }, rangeSelector: { selected: 0 }, series: [{ type: 'column', data: _data, }], dataGrouping: { units: [[ 'week', // unit name [1] // allowed multiples ], [ … -
Django Rest Framework different image size for different account tiers (Basic, Premium)
There are three bultin account tiers: Basic, Premium and Enterprise: Users that have "Basic" plan after uploading an image get: a link to a thumbnail that's 200px in height Users that have "Premium" plan get: a link to a thumbnail that's 200px in height a link to a thumbnail that's 400px in height a link to the originally uploaded image models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image def user_directory_path(instance, filename): return 'images/{0}'.format(filename) class Images(models.Model): title = models.CharField(max_length=250) image = models.ImageField(upload_to=user_directory_path) created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='author') def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) class Profile(models.Model): MEMBERSHIP = ( ('BASIC', 'Basic'), ('PREMIUM', 'Premium'), ('ENTERPRISE', 'Enterprise') ) user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.CharField(max_length=10, choices=MEMBERSHIP, default='BASIC') def __str__(self): return f'{self.user.username} {self.membership} Profile' serializers.py from rest_framework import serializers from blog.models import Images, Profile class ImagesSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ('author', 'title', 'image') views.py class ImagesViewSet(viewsets.ModelViewSet): queryset = Images.objects.all() serializer_class = ImagesSerializer def get_queryset(self): user = self.request.user return Images.objects.filter(author=user) -
import dm.xmlsec.binding as xmlsec, dm`Module not found :
I am working on django project. I am running this project on a venv using the command : "python manage.py runserver". But getting the error "import dm.xmlsec.binding as xmlsec, modulenotfounderror "dm" ". I have tried installing the module using pip install dm in the venv but still not able to bypass this error. Sharing the screenshot of the same. enter image description here Any help is appreciated. -
Why does nginx not redirect to https?
I'm trying to deploy my Django application but I'm having issues with the redirect to https added in my nginx config by Certbot. This is what my config looks like: server { server_name somedomain.com; location /static/ { root /var/www/somedomain; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/somedomain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/somedomain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = somedomain.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name somedomain.com; return 404; # managed by Certbot } With https the site works fine, but for http there is no response: curl http://somedomain.com curl: (28) Failed to connect to somedomain.com port 80 after 78173 ms: Operation timed out