Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom django inlineformset validation based on user permissions
The objective is to have a simple workflow where an order and associated orderlines (created in a previous step) needs to be approved by the relevant budget holder. The approval form shows all order lines but disables those lines that the current user is not associated with (they should be able to see the overall order but only be able to edit lines that they are permitted to). They should be able to add new lines if necessary. The user needs to decide whether to approve or not (approval radio cannot be blank) The initial form presents correctly and is able to save inputs correctly when all values are inputted correctly - however, if it fails validation then the incorrect fields get highlighted and their values are cleared. models.py class Order(models.Model): department = models.ForeignKey(user_models.Department, on_delete=models.CASCADE) location = models.ForeignKey(location_models.Location, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=30) project = models.ForeignKey(project_models.Project, on_delete=models.CASCADE) product = models.ManyToManyField(catalogue_models.Product, through='OrderLine', related_name='orderlines') total = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) def __str__(self): return self.description class OrderLine(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) project_line = models.ForeignKey(project_models.ProjectLine, on_delete=models.SET_NULL, null=True, blank=False) product = models.ForeignKey(catalogue_models.Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=20, decimal_places=4) total = models.DecimalField(max_digits=20, decimal_places=2) budgetholder_approved = models.BooleanField(null=True) def get_line_total(self): total = self.quantity * self.price return … -
Django templates error; Reverse for 'search' not found. 'search' is not a valid view function or pattern name
my layout: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action = "{% url 'search' %}" method="GET"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href = "{% url 'newpage' %}">Create New Page</a> </div> <div> <a>Random Page </a> </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> my views.py: def search(request): result = set() entries = util.list_entries() if request.method == 'GET': query = request.GET.get('q') if query == '': #If it's nothing query = 'NONE' if query in entries: return redirect(f'wiki/{query}') else: results = [entry for entry in entries if query.lower() in entry.lower()] return render(request, "encyclopedia/index.html", { "entries": results }) return render(request, 'encyclopedia/search.html', {'results':result}) my urls: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'encyclopedia' urlpatterns = [ path("", views.index, name="index"), path('newpage/', views.new_page, name = 'newpage'), path('wiki/<str:title>', views.entry, name = 'entries'), path('wiki/<str:title>/edit',views.edit, name = 'edit'), path('search', views.search, name = 'search'), … -
Unable to load logged in User's Profile Image in Django template
This is my frontend code of header.html where I am typing to display the currently logged-in user's profile picture after the user authenticates. It works when my current user is on the home page or its profile but as soon as it moves to another's profile it starts displaying that profile's picture. I want to make it such like where ever logged in user move he/she should always see their profile picture <div><b><a href="{% url 'index' %}">Bondly</a></b></div> {% if user.is_authenticated %} <div> -------> <img src="{{user_profile.img_profile.url}}" /> </div> {% endif %} </header> Here are code of my views.py def profile(request, pf): user_object = User.objects.get(username=pf) user_profile = models.Profile.objects.get(usr=user_object) print(request.user.__doc__) posts = models.Post.objects.filter(user=pf) postsNum = len(posts) follor = request.user.username if models.Followers.objects.filter(follower=follor, user=pf).first(): text = "Following" else: text = "Follow" followers = len(models.Followers.objects.filter(user=pf)) following = len(models.Followers.objects.filter(follower=pf)) context = { 'user_object': user_object, "user_profile": user_profile, "posts": posts, 'postsNum': postsNum, "text": text, "followers": followers, "following": following } return render(request, 'profile.html', context) and my models.py class Profile(models.Model): """docstring for Profile.""" usr: str = models.ForeignKey(User, on_delete=models.CASCADE) id_usr: int = models.IntegerField() Fname:str = models.TextField(blank=True,null=True) Mname:str = models.TextField(blank=True,null=True) Lname:str = models.TextField(blank=True,null=True) Fhone:int = models.IntegerField(blank=True,null=True) bio: str = models.TextField(blank=True) img_profile = models.ImageField( upload_to='ProfileIMG', default="blankprofile.png") location: str = models.CharField(max_length=250) def __str__(self): return self.usr.username -
aws s3 storage. ReactNative pass image data to Django
Django rest-framework uses aws s3 to save image. How to pass image data from React Native I am using aws s3 to store images on Django rest-framework. Work perfect on Django App but cannot work from React Native App pass image data to Django backend. Do I have to make aws s3 image url on React Native App and pass that url to Django database? -
when trying to send email OSError: [Errno 99] Cannot assign requested address i get error
I have a project consist of django - docker - celery - redis on Linode. I used celery workers for sending mail to clients in local celery is working fine but in my vps is not working and gives an error "OSError: [Errno 99] Cannot assign requested address". I used smtp.gmail.com system and i took an application password on google and used in project. Do I need to make a setting on linode related to mail? Please help me! I want to send email periodically with django celery. My task working fine in local but when try to send email on deploy server i get OSError: [Errno 99] Cannot assign requested address error. -
Changing class attributes in decorator
I'm using django as my framework for some web application I implemented a modelview of my own because I have few querysets and seriazliers in the same view. For this use, I needed to implement all the CRUD function myself. That look something like this. class Models1AndModel2View(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): model1 = Model1.object.all() model1_serializer_class = Model1Seriazlizer model2 = Model2.object.all() model2_serializer_class = Model2Seriazlizer def refresh_querysets(func): def inner(self, *args, **kwargs): value = func(self, *args, **kwargs) self.model1 = Model1.object.all() self.model2 = Model2.object.all() return value return inner @refresh_querysets def list(self, request, *args, **kwargs): ... @refresh_querysets def retrieve(self, pk, request, *args, **kwargs): ... @refresh_querysets def update(self, pk, request, *args, **kwargs): ... @refresh_querysets def delete(self, pk, request, *args, **kwargs): ... @refresh_querysets def create(self, request, *args, **kwargs): ... Notice that in calling the decorator's function before the objects refresh. I was notices that every attributes sets after the function calls is not actually set. For example - some test of mine: list all the models - 2 models instances delete one of them list them again - still 2 models instances (in model1 + model2) if you query the model1 and model2 you can see that one of the instances is deleted as expected, but … -
anchor do nothing after second index
I have a django-qcm with sections that change when clicking on anchors and using the scroll snap type property. <style> html{ scroll-behavior: smooth; } body{ background-color: #72a9d6; color: white; font-family: "Mont", sans-serif; overflow: hidden; } section{ overflow: hidden; height: 100vh; /*overflow-y: scroll;*/ scroll-snap-type: y mandatory; scroll-behavior: smooth; } .container{ padding: 5%; display: grid; position: relative; justify-items: center; gap: 3px; scroll-snap-align: center; height: 100%; } .question_title{ height: 50px; font-size: 25px; font-weight: 500; text-align: center; } .space_title{ height: 150px; } .container_reps{ max-width: 30%; display: flex; flex-wrap: wrap; justify-content: center; column-count:2; height: 20%; } .rep{ display: flex; align-items: center; border:1px solid white; padding: 0 5px ; max-width: 15%; min-width: 250px; border-radius: 5px; cursor: pointer; margin-top: 5px; margin-bottom: 10px; margin-left: 10px; max-height: 40px; } .rep:hover{ background-color: rgba(255, 255, 255, 0.3); } .dot_rep{ background-color: #63c7f5; border: 1px solid white; color: white; margin-right: 7px; padding: 5px 10px; border-radius: 5px; } .text_rep{ font-weight: 700; } .check{ margin-left: 40%; } </style> <section> <div id="1" class="container"> <div class="question_title"> <div class="space_title"></div> <p>Question 1</p> </div> <div class="container_reps"> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep">rep 1</p> </div> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep"> rep 2</p> </div> <div class="rep"> <span class="dot_rep">1</span><p class="text_rep">rep3</p> </div> </div> </div> <div id="2" class="container"> <div class="question_title"> <div class="space_title"></div> <p>Question 2</p> </div> <div … -
problem with adding javascript to django view form update
I have a django view to add an invoice to my application, that has added javascript, and it works fine. <p> <label for="id_total_without_vat">Price</label> <input type="number" name="total_without_vat" step="any" required="" id="id_total_without_vat" oninput="calculateTotalWithVat()"> <label for="id_currency_name">Currency</label> <select name="currency_name" id="id_currency_name" onchange="update_currency_rate()"> <option value="NIS">NIS</option> </select> <label for="units">Units</label> <span id="units"></span> <label for="id_currency_rate">Currency Rate</label> <input type="number" name="currency_rate" step="any" id="id_currency_rate" value=1.00 oninput="calculateTotalWithVat()"> <label for="nis_total">Total Price</label> <span id="nis_total"></span> </p> <p> <label for="id_total_vat_included">Total VAT Included</label> <input type="number" name="total_vat_included" step="any" required="" id="id_total_vat_included"> <label for="id_vat_percentage">VAT Perentage</label> <input type="number" name="vat_percentage" step="any" value="17.0" id="id_vat_percentage" oninput="updateVat(this.value)"> <label for="nis_total_with_tax">NIS Total With Tax</label> <span id="nis_total_with_tax"></span> </p> The problem is while trying to do something similar in the update view I see the oninput part of the command in the browser as text, this is the update view code: <p> <label for="id_total_without_vat">Total without VAT</label> {{ form.total_without_vat }} <label for="id_currency_name">Currency</label> <select name="currency_name" id="id_currency_name" onchange="update_currency_rate()"> <option value=" {{ form.currency_name }} "></option> </select> <label for="units">Units</label> <span id="units"></span> <label for="id_currency_rate">Currency Rate</label> <input type="number" name="currency_rate" step="any" id="id_currency_rate" value= "{{ form.currency_rate }}" oninput="calculateTotalWithVat()"> <label for="nis_total">Price</label> <span id="nis_total"></span> </p> <p> <label for="id_total_vat_included">Price Including VAT</label> {{ form.total_vat_included }} <label for="id_vat_percentage">VAT Percentage</label> <input type="number" name="vat_percentage" step="any" value=" {{ form.vat_percentage }} " id="id_vat_percentage" oninput="updateVat(this.value)"> <label for="nis_total_with_tax">Price Including Taxes</label> <span id="nis_total_with_tax"></span> </p> Can someone tell me why the add view … -
django-cms makemigrations error: No module named 'packaging'
I am starting out in django-cms and I am trying to install cms from the official cms documentation. I created my virtual environment and installed Django and django-cms. The next steps are to create a project with django-admin, and adding the django-cms in the installed apps. The project is going great till now. But, when I try to migrate my installed apps in the database I get the error "No module named 'packaging'". I don't understand what I am doing wrong. Another tutorial tells me to startproject using djangocms myproject but it doesn't work (it's probably outdated as I couldn't find any variations anywhere else) My settings.py: INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', ] SITE_ID = 1 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ] After this, I run the py manage.py makemigrations But I get the error Traceback (most recent call last): File "E:\art\Graphic Design\Coding\law-&-stuff\myproject\manage.py", line 22, in <module> main() File "E:\art\Graphic Design\Coding\law-&-stuff\myproject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "E:\art\Graphic Design\Coding\law-&-stuff\venv\Lib\site-packages\django\__init__.py", … -
ddjango score not work when i move aplication to another project
hi everybody i move app in another project for quiz he is work but showin the score is not work thats the template <div class="total" style="display:none"> <h2> {{total}}مبروك انت فزت مجموع ما حصلت عليه هو </h2> and thats a models.py from django_auto_one_to_one import AutoOneToOneModel class UserScores(AutoOneToOneModel(User, related_name='user_id')): score = models.PositiveIntegerField(default=0) def __str__(self): return str(self.score) and this views.py class GameplayView(TemplateView): template_name = 'gameApp/gameplay.html' def get_context_data(self, **kwargs): context = super().get_context_data( **kwargs) self.request.session['q_count'] = 0 self.request.session['winner'] =False self.request.session['score'] = 0 self.request.session['right_answer'] = "" -
Formset not showing label in django
I am developing a domestic worker booking app in django When I try to pass the formset, I am not geting the label of that field. I am only getting the field in html. {% for formset in formsets %} <form method="post"> {% for form in formset %} {% for field in form %} <div> <label for="{{ field.auto_id }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} </div> {% endfor %} {% endfor %} <input type="submit" value="Submit"> </form> {% endfor %} This the html code def staffApply(request,pk): if request.method == 'POST': selected_domestic_works = request.POST.getlist('domestic_works') formsets = [] if 'cook' in selected_domestic_works: formsets.append(CookingForm(request.POST,prefix='cook')) if 'driver' in selected_domestic_works: formsets.append(DriverForm(request.POST,prefix='driver')) print(formsets) return render(request, 'staffApply2.html', {'formsets': formsets}) return render(request,'staffapply.html',{'uid':pk}) enter code here This is my views.py class CookingForm(ModelForm): food_cooked=(('veg','veg'), ('non-veg','non-veg'), ('both','both') ) class Meta: model = Cook fields = '__all__' exclude=['user'] widgets={ 'food_cooked':forms.widgets.RadioSelect(), 'type_of_cuisine':forms.widgets.CheckboxSelectMultiple() } This is my forms.py I am getting the fields to type. But I am not getting hte label for those fields. Please help me fix this. -
Approach to tackle slow internet connection?
I am developing a web application on django for quiz. For each question that the teacher has entered, there is a qr code which the student have to scan from their mobile phones and select the correct option available on their screen. ISSUE: Whenever the student is scanning the qr code for answering the question, the link is not opening due to a slow network connection. Is there anyway I can solve this issue?? Thanks in advance.... -
How to make customize detail view set using ModelViewSet?
I am new to django. I have a model: class Class(models.Model): name = models.CharField(max_length=128) students = models.ManyToManyField("Student") def __str__(self) -> str: return self.name Now I want to create API to display the students in a particular class,the detail view, by giving the name of the class as a parameter using ModelViewClass. Currently, I have following viewset written: class ClassViewSet(ModelViewSet): serializer_class = serializers.ClassSerializer queryset = models.Class.objects.all() How to do that? -
ask user to login again in order to update user settings
Hello I have this view to able user to change data like username, password, etc: @login_required(login_url='core:login_view') def settings(request): form = UserUpdateForm(request.POST or None,instance=request.user) if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data.get('password1')) user.save() context = { 'form':form, } return render(request,'core/settings.html',context) Because in this view user can change password and username, I want the user to enter login and password again in order to access this view. Thanks for the help! -
Return QuerySet with extra pagination fields
My get_queryset return this. Also, this fields with ID's are foreign keys serialized. [ { "id": 1389, "nome": "Curso teste", "nivel": { "id": 5, "nome": "Ensino Fundamental II" }, "modalidade": { "id": 4, "nome": "Presencial" }, "periodo": { "id": 5, "nome": "Matutino" }, "ano": { "id": 21, "nome": "12º Semestre" }, "instituicao": { "id": 35, "nome": "Fncit-escola" } } ] I want to add to each object an extra pagination object, and it would be like this object below. But get_queryset do not accept this kind of object, and if I use just get, and serialize the queryset, it will not come with the ForeignKeys serialized, it will return only the id's of the Foreign keys. Anyone knows how do I return an object like this? [ "bolsas":{ "id": 1389, "nome": "Curso teste", "nivel": { "id": 5, "nome": "Ensino Fundamental II" }, "modalidade": { "id": 4, "nome": "Presencial" }, "periodo": { "id": 5, "nome": "Matutino" }, "ano": { "id": 21, "nome": "12º Semestre" }, "instituicao": { "id": 35, "nome": "Fncit-escola" } }, "pagination": { "elements": 1 } ] -
Attribute Error: 'bool' object has no attribute 'utcoffset'
I am new to django and I have been trying to learn from the past few days. I have added date time and duration fields into my model. Now when I am trying to add flights using Django admin site I am getting the following error: AttributeError at /admin/flights/flight/add/ 'bool' object has no attribute 'utcoffset' Request Method: GET Request URL: http://127.0.0.1:8000/admin/flights/flight/add/ Django Version: 4.1.3 Exception Type: AttributeError Exception Value: 'bool' object has no attribute 'utcoffset' Exception Location: /opt/homebrew/lib/python3.10/site-packages/django/utils/timezone.py, line 256, in is_aware Raised during: django.contrib.admin.options.add_view Python Executable: /opt/homebrew/opt/python@3.10/bin/python3.10 Python Version: 3.10.8 Python Path: ['/Users/janardhanareddyms/Documents/airline', '/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/janardhanareddyms/Library/Python/3.10/lib/python/site-packages', '/opt/homebrew/lib/python3.10/site-packages', '/opt/homebrew/opt/python-tk@3.10/libexec'] Server time: Sun, 15 Jan 2023 02:53:34 +0000 Error during template rendering In template /opt/homebrew/lib/python3.10/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 … -
django haystack rebuild_index fails if model id exluded
I'm trying to understand a rebuild_index error that results when using a very basic SearchIndex very similar to what is used in the haystack documentation. In the docs, the id of the model is excluded, which makes sense given that there seems little point in it influencing search results. I've tried something like this class CollectionIndex(indexes.SearchIndex, indexes.Indexable): #id = indexes.IntegerField(model_attr='pk') text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') def get_model(self): return Collection def index_queryset(self, using=None): # force just one item to be indexed to save a wait. return self.get_model().objects.filter(name="Test") ...but I get this error (I've applied some formatting to help legibility) elasticsearch.helpers.BulkIndexError: ('1 document(s) failed to index.', [ { "index": { "_index": "haystack", "_type": "modelresult", "_id": "my_project.collection.1", "status": 400, "error": { "type": "mapper_parsing_exception", "reason": "failed to parse [id]", "caused_by": { "type": "number_format_exception", "reason": 'For input string: "my_project.collection.1"', }, }, } } ]) The only way to get the indexing to work is to uncomment the id line. Is this just an elasticsearch thing, which is why the examples in the official docs don't have an equivalent, or am I misinterpreting things? Does it make sense to do a search for a number, and have a search result with an id matching … -
Force user to re-login when accessing admin page on Django
I have a django project that I want to force an administrator to login before accessing the admin area EVEN IF they are already logged into to the main site. The approach I have thought of was to creating a custom admin view where I logout the user (if they are already logged in) when they try to access the admin page but not sure what the cleanest way of doing this is. Currently my urls.py for admin is just url(r'^admin/', admin.site.urls) My ultimate goal is to have 2FA implemented just for my admin login. -
Psycopg2 duplicate key value violates unique constraint (when migrating from SQLITE to POSTGRESQL)
I have been trying to migrate a database from SQLite to POSTGRESQL. I am using json fixtures to dump and load the data, I tested multiple ways but I end up in a similar situation, and I say similar because I can reach 2 slightly different errors. So the 2 errors I can reach are the following: django.db.utils.IntegrityError: Problem installing fixture '/PATH/wcontenttypes.json': Could not load MyApp.DIN_STATUS(pk=1): duplicate key value violates unique constraint "MyApp_din_status_DSP_id_EA_id_1c1c3e96_uniq" DETAIL: Key ("DSP_id", "EA_id")=(542, 20324) already exists. The other one is the same but instead of pk=1, its pk=5 What did I check? If there's a duplicate -> but there is not If the row referenced by the id exist -> it does exist Removing the row that gives the error -> The next one gives the error (in case its pk=5, then pk=6, if pk=1 then pk=2) What did I test? I did multiple test looking around the internet, and testing almost anything I could find, the research ended up with 3 main ideas on how to do this Test 1 python manage.py dumpdata > wcontenttypes.json #-Swap to postgre find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete python manage.py makemigrations python … -
Django-Nginx- nginx returns default page when http is used in the request
I have a Django website with (nginx-gunicorn), the sock configuration for nginx is: server { server_name www.example.com; location /favicon.ico { access_log off; log_not_found off; } #static location /static/ { root /home/xx/xxx/xxx; } #media location /products/ { root /home/xx/xxx/xxxx; } location / { include proxy_params; proxy_pass http://unix:/home/xx/xxx/xxxx/bnb_6.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.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 { server_name example.com; location /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xxx/xxx/xxxx; } #media location /products/ { root /home/xx/xxx/xxxx; } location / { include proxy_params; proxy_pass http://unix:/home/xx/xxx/xxxx/xxxxx.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.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 return 301 https://www.example.com$request_uri; } But the site returns the default nginx page when I access it with http; I want is to change automatically from http to https, also the sharing of the site on social media displays the same nginx default page. Any suggestions? -
line 35 else: IndentationError: unindent does not match any outer indentation level
i want to solve problem line 35 else: ^ IndentationError: unindent does not match any outer indentation level else: if User.objects.filter(email=email).exists(): #email is taken pass else: patt = "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" if re.match(patt, email): user = User.objects.create_user(first_name=fname, last_name=lname, email=email, username=username, password=password) user.save() -
Saving new model overrides existing model
I have a form that I am using to create new models, but every time I submit the form, it overrides the only existing model in the database. My form view: class createItinerary(CreateView): template = "create.html" form_class = CreateItineraryForm def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template, {"form": form}) def post(self, request, *args, **kwargs): super().__init__(*args, **kwargs) form = self.form_class(request.POST) if form.is_valid(): destination = form.cleaned_data.get("destination") trip_length = form.cleaned_data.get("trip_length") start = form.cleaned_data.get("start") end = form.cleaned_data.get("end") sights = form.cleaned_data.get("sights") new = Itinerary(destination=destination, trip_length=trip_length, start=start, end=end) new.sights.set(sights) new.save() return redirect("/") else: form = CreateItineraryForm return render(request, self.template, {"form" : form}) My forms.py: from django import forms from django.forms.widgets import * from itineraries.models import Itinerary from sights.models import Sight sight_choices = () for sight in Sight.objects.all(): new_sight = (("%s" % sight.name, "%s" % sight.name)) sight_choices += new_sight class CreateItineraryForm(forms.ModelForm): class Meta: model = Itinerary exclude = [] destination = forms.CharField(label="Destination", max_length=100) start = forms.DateField(widget=NumberInput(attrs={"type" : "date"})) end = forms.DateField(widget=NumberInput(attrs={"type" : "date"})) sights = forms.ModelMultipleChoiceField( queryset=Sight.objects.all()) This is the only existing model in the database: When I use the form to save a new one: It replaces the old model with the newly created one every time. -
In django, how can I access the request object in the form's clean method when using a CreateView?
I'm following the answer from this question, but the request object isn't actually being passed into it: How do I access the request object or any other variable in a form's clean() method? I'm getting this error when I try to submit the form: 'NoneType' object has no attribute 'user' Here is my form code: class MyModelForm(ModelForm): class Meta: model = MyModel fields=['question',] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MyModelForm, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = self.cleaned_data['question'] user = self.request.user if user.author.number_of_questions < 1: raise ValidationError("You don't have any questions left") return data Here is my CreateView: class MyModelCreate(generic.CreateView): model = MyModel fields=['question',] def form_valid(self, form): # Code return super(MyModelCreate, self).form_valid(form) def get_success_url(self, **kwargs): # obj = form.instance or self.object return reverse_lazy('articles:thank-you') def get_form_kwargs(self): kw = super(MyModelCreate, self).get_form_kwargs() kw['request'] = self.request # the trick! return kw def get_context_data(self, **kwargs): #Code return context It's my understanding that the get_form_kwargs method in the CreateView is passing in self.request into the request kwarg of the form, which is then being accessed in the clean method of MyModelForm, but when I run this code, I get the error: 'NoneType' object has no attribute 'user' I have no idea why the … -
How to override UpdateView get_queryset django
I'm new to django, and I'm trying to make a simple update form where you can enter the PK of the object to be modified, and have the fields to be modified of the object in the same form, without entering the pk through the url, instead enter the PK from the form previously opened by the url http://127.0.0.1:8001/update/, I am using UpdateView and I try to cancel the get_queryset method, so far what I have achieved is to cancel the method and open the form but I must pass a pk if not it doesn't open I don't know how to make the form open blank. Model: class Lote(models.Model): lote = models.CharField(verbose_name='Lote', max_length=10, primary_key=True) codigo = models.CharField(verbose_name='Codigo', max_length=10, blank=True, null=True) producto = models.CharField(blank=True, max_length=50, null=True, verbose_name='Producto') timestamp= models.DateTimeField(auto_now_add=True) Forms: class LoteForm(forms.ModelForm): class Meta: model = Lote fields = ["lote","producto","codigo"] class LoteFormView(forms.Form): lote = forms.CharField(max_length=20) producto = forms.CharField(max_length=20) codigo = forms.CharField(max_length=20) View: class Update(UpdateView): model = Lote template_name = 'lote/updateview.html' fields = ['lote', 'codigo', 'producto'] success_url = '/update/' def get_object(self, queryset=None): return Lote.objects.get(pk=11111) url : url(r'^update/$', Update.as_view(), name='update'), Result: enter image description here what I want enter image description here I want to open the blank form and then pass … -
Django: Custom User Model Not Showing Profiles with StackedInLine
I have a custom user model which I am trying to associate a profile with. However I've been following other code to do this and I just cant seem to get it to work. admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Trickster_User, User_Profile class ProfileInline(admin.StackedInline): model = User_Profile fields = ['User', 'SkillLevel', 'UserDIfficultyLevel', 'LearnedTricks', 'Follows'] class UserAdminConfig(UserAdmin): model = Trickster_User inLines = [ ProfileInline ] search_fields = ('Email', 'Username', 'FirstName', 'LastName') list_filter = ('Email', 'Username', 'FirstName', 'LastName', 'is_active', 'is_staff') ordering = ('-DateOfJoining',) list_display = ('Email', 'Username', 'FirstName', 'LastName','is_active', 'is_staff') fieldsets = ( ('Personal Info', {'fields': ('Email', 'Username', 'FirstName', 'LastName')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('Email', 'Username', 'FirstName', 'LastName', 'password1', 'password2', 'is_active', 'is_staff')} ), ) admin.site.register(Trickster_User, UserAdminConfig) admin.site.register(User_Profile) models.py: class CustomUserManager(BaseUserManager): def create_superuser(self, Email, Username, FirstName, LastName, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(Email, Username, FirstName, LastName, password, **other_fields) def create_user(self, Email, Username, FirstName, LastName, password, **other_fields): if not Email: raise ValueError('You must provide an email address') Email = …