Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
zip on the fly files also made on the fly with python-django
I'm creating an excel file on the backend of my django app, it works but now i need to zip it before sending it back to download and i'm having problems using zipfile to do it The code for the excel works just great but is the zipping that is presenting some problems, it seems that i cant just simply put "write(output)" (output being an stringio file) output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output) sheet = workbook.add_worksheet() data = [[14, 11, 2], [48, 47, 63], [650, 89, 47]] for rownum, columns in enumerate(data): for colnum, cell_data in enumerate(columns): sheet.write(rownum, colnum, cell_data) workbook.close() output.seek(0) # Creating the zip file s = StringIO.StringIO() zf = zipfile.ZipFile(s, "w") zf.write(output) zf.close() resp = HttpResponse(zf, content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=file.zip' return resp With this code i get the following error: coercing to Unicode: need string or buffer, instance found and when i use "output.getvalue()" i get: stat() argument 1 must be encoded string without null bytes, not str -
How to generate a Word document using Django
I'm new to Django and would like to create a form where users can input some data, and have a Word document be created for download. I was using the templated-docs library (https://pypi.org/project/templateddocs/) to accomplish this task, but I'm receiving an error. in my views.py: from templated_docs import fill_template from templated_docs.http import FileResponse def get_document(request): """ A view to get a document filled with context variables. """ context = {'user': request.user} # Just an example filename = fill_template('sample.odt', context, output_format='pdf') visible_filename = 'greeting.pdf' return FileResponse(filename, visible_filename) After the user inputs information in the form, I'm getting this error: get_template_sources() takes 2 positional arguments but 3 were given the error is produced from the variable that's in views.py: filename = fill_template('sample.odt', context, output_format='pdf') -
Django: order by and coalesce
What would be the Django equivalent of this query Comment.objects.raw('SELECT * FROM comments_comment where post_id=11 order by coalesce(parent_id, id), (case when parent_id is null then 1 else 2 end ), created_at') -
Admin side modification django
I have this class In which when I submit a name it goes to admin and only admin can approve this. I want that when admin approve a email automatically should be sent to user. class myab(models.Model): generic_name = models.CharField(max_length=50, null=False) timestamp = models.DateTimeField(auto_now_add=True) is_approved = models.BooleanField(null=False, default=False) I only wanted to know how to trigger email code . I have everything else just wanted to understand how to trigger that function when Admin will approve this post. -
How to Upload files in graphene-file-upload with apollo-upload-client to Python Database.?
I'm trying to upload a file to a django backend using graphene-file-upload which has the mutation to link the backend to the react frontend where I'm trying to use apollo-upload client to link it with graphql. In my django model an empty file is being successfully uploaded but it is not uploading the real file which I'm selecting but uploads an empty file. Like it uploads nothing {} but the instance is created in the database where another story is added which is empty. Here is some of my code. My Database Model. models.py class Story(models.Model): file = models.FileField(null=True) created_at = models.DateTimeField(auto_now_add=True) MY schema.py from graphene_file_upload.scalars import Upload class StoryType(DjangoObjectType): class Meta: model = Story class UploadFile(graphene.Mutation): story = graphene.Field(StoryType) class Arguments: file = Upload() def mutate(self, info, file): for line in file: print(line) story = Story(file=file) story.save() return UploadFile(story=story) My frontend File.js import React from 'react'; import { Mutation } from 'react-apollo'; import {withStyles} from '@material-ui/core/styles'; import gql from 'graphql-tag'; const styles = theme => ({ layoutRoot: {} }); const UploadFile = () => ( <Mutation mutation={gql` mutation($file: Upload!) { uploadFile(file: $file) { story { file } } } `} > {mutate => ( <input type="file" required onChange={({ target: … -
Django Wagtail: Is there any option to make wagtail fieldPanel disabled?
Another question concerning Wagtail admin. I have django model for received emails. I show these models in Wagtail using ModelAdmin. I would like to make this only read-only. A good solution would be possibility to disable Wagtail fieldPanels. But I can't find any info if that is possible. Only workaround so far seems to be register custom .js file inside ModelAdmin Class: my admin.py class EmailAdmin(ModelAdmin): model = Email menu_label = "Emails" menu_icon = "mail" menu_order = 300 add_to_settings_menu = False exclude_from_explorer = False empty_value_display = 'N/A' list_per_page = 10 index_view_extra_js = ["js/wagtail.js",] # extra .js code to disable fields list_display = ('subject', 'name_surname', 'phone', 'email', 'text_', 'date', 'sent', 'change_seen') I would like to ask you if there is some more native Wagtail way how to disable fieldPanels. -
Django: Dump data from models directly into a file
I used python manage.py dumpdata -a --format yaml to output it as yaml which is okay, but how would I do it if I want it in a file that I can keep and use again if necessary? -
i can't see my form.py on the modal, i using ajax and django
Actually i a beginner, and i try to do a CRUD with django and ajax, my problem is the next: i try to see my form on the modal (i using bootstrap) but i can't see nothing , i just see a little screen black. enter image description here my CreateAutor.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'Autor:add' %}" class="create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Agregar autor</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button> <button type="submit" class="btn btn-primary">Guardar</button> </div> </form> my ListsAuto.html: {% extends 'jencinas/dashboard.html' %} {% block content %} <h1 class="page-header">Autores</h1> <button class="btn btn-primary show-form" data-url="{% url 'Autores:add' %}"> <span class="glyphicon glyphicon-plus"></span> Nuevo autor </button> <table class="table" id="autor-table"> <thead> <tr> <th>#</th> <th>Title</th> <th>Author</th> <th>Type</th> <th>Publication date</th> <th>Pages</th> <th>Price</th> </tr> </thead> <tbody> {% include 'jencinas/Posts/ListsAutor2.html' %} </tbody> </table> <div class="modal fade" id="ModalAutor"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> {% endblock%} my ListsAuto2.html: {% for autors in Autor %} <tr> <td>{{ autors.id }}</td> </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">No hay autores</td> </tr> {% endfor %} my urls.py: from django.urls import path from . import views PersonalWeb_urlpatterns = ([ #Url principal de … -
Modifying save() in django model keeps looping
I'm trying to create a model based on the Google Map API. If the object does not exists, I want to save the name, address, longitude, latitude and google place ID. Below is my code: However, when I run it, it goes into a loop and does stop checking Google Map. Can you tell me what is wrong? class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) logitude = models.CharField(max_length=20, null=True, blank=True) latitude = models.CharField(max_length=20, null=True, blank=True) id_google = models.CharField(max_length=50, null=True, blank=True) date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): try: place = Place.objects.get(name=self.name) except Place.DoesNotExist: gmaps = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY) geocode_result = gmaps.geocode(self.address) place = Place(name=self.name, address=geocode_result[0]['formatted_address'], logitude=geocode_result[0]['geometry']['location']['lng'], latitude=geocode_result[0]['geometry']['location']['lat'], id_google=geocode_result[0]['place_id'], ) place.save() return place -
Django PermissionRequiredMixin results in HTTP error 405
I am using Django 2.2 and trying to follow this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication#Views. Unfortunately when following it and trying to use PermissionRequiredMixin I get an HTTP error 405. I couldn't find the solution. Thank you in advance for your help. model.py from django.contrib.auth.models import User from django.db import models import uuid from datetime import date from django.urls import reverse # Used to generate URLs by reversing the URL patterns class id_adress(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular adress' ) street = models.CharField(max_length=200, help_text='street') city = models.CharField(max_length=200, help_text='city') zipcode = models.IntegerField(help_text='zipcode') def __str__(self): return f'{self.street},{ self.city}' class Patient(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular patient' ) firstname = models.CharField(max_length = 200, help_text = 'Firstname') lastname = models.CharField(max_length = 200, help_text = 'Lastname') mail =models.CharField(max_length = 200, help_text = 'E-mail') phone = models.IntegerField(help_text='country code + number (e.g 33 6 12 34 56 78)') adress = models.ForeignKey('id_adress',on_delete=models.SET_NULL,null=True) def __str__(self): return f'{self.firstname},{ self.lastname}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('Patient-detail', args=[str(self.id)]) class Doctor(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text = 'Unique ID for this particular doctor' ) firstname = models.CharField(max_length = 200, help_text = 'Firstname') lastname = models.CharField(max_length … -
Can I call a ListAPIView class from within another function?
I have a ListAPIView class that takes a parameter from the URL, does some permission checking, fetches the data, then serializes it. I'm setting up GraphQL, and rather than redoing all that logic for all routes, I'd like to be able to just call that view and return the results in the query. Is that possible and how would I go about doing it if so? I've tried doing something like the following but doesn't work, and seems pretty hacky regardless. view = ListView() view.kwargs = { "pk": id } data = view.get_queryset() serialized = ListViewSerializer(data) return serialized.data -
how to display retrieved data from database using django
i have a django project that is connected to SQL Server i tried to retrieve data from the database. if i try to display all the data it run correct and display all the values. but if i try to display the data in an html table it doesn't display anything. views.py def connect(request): conn = pyodbc.connect( 'Driver={ODBC Driver 17 for SQL Server};' 'Server=DESKTOP-LPD1575\\SQLEXPRESS;' 'Database=testDB;' 'UID=test;' 'PWD=test;' ) cursor = conn.cursor() c = cursor.execute('SELECT * FROM Artist') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} this code in the html template work and display the data. but if i try to do as below it will not work <table align = "center"> <tr align="center"> <th>ID</th> <th>FolderNumber</th> <th>Title</th> </tr> {% for row in c %} <tr align="center"> <td>{{ row.id }}</td> <td>{{ row.artistName }}</td> <td>{{ row.activeFrom }}</td> </tr> {% endfor %} </table> anyone can help me? -
ManyToMany relationships (Every category needs to has its own unique features(Booleanfield) for items)
Basically, I`m working on a software catalog, which will have software categories(for example Accounting Software, Payroll Software, Data Visualisation Software, etc.) And of course, there will be some software items in these categories. Each category has its own unique features. For instance, Accounting software has: - Accounts payable - Expense Tracking - Billing & Invoicing etc. These features will be boolean fields. The reason is showing all the features in the software item page as 'pros and cons'. (For better UX). I have created a software category models and software item models with m2m relations. Now I want to add new features to my categories and show them in my software items page. But each feature (boolean fields) should be unique (True or False) for the software item. Sorry for my basic English. But I hope you can understand the problem. I have tried to add the through model for my m2m relation. But it is not handy and I believe there must be a much more elegant way than this. -
Download multiple files from a single Django Rest Framework API endpoint
I have some files located on a server with different file types (.geojson and .pbf) which I would like to download to a client device with a single API call. The server uses Django and the Django Rest Framework. Below is some code I have written which successfully downloads one of the files, however, I cannot figure out how to return the second file at the same time. class DownloadFiles(APIView): permission_classes = (IsAuthenticated,) def get(self, request): try: user = request.user # This is a .geojson place = Places.objects.filter(user_id=user)[0] # This is a .pbf # food = Foods.objects.filter(user_id=user)[0] # How do I return both files here? return FileResponse(open(place.filepath, 'rb')) except: return Response({'status': 0}, content_type="application/json") Note - I would prefer to not ZIP the files together since the client device will be Android/iOS and that can be complicated to handle on those platforms. -
Is there a option to make quiz (form) with text input and then check the answers (are correct)?
I'm using a newest Django (2.2), and I want to make a quiz with input (type: text), which you need to fill (complete quiz - write your answer, not to choose), and after click on "Check my answers", to then compare answers with the correct answers (Which are already made and saved) - and show the evaluation. Here are my models that I'm using: (my method doesn't need to be good - if you know other method just scroll down to the website view (image) to see what I exactly mean or just read what I've done) Quiz models (models.py) class UctoTest(models.Model): # This is the main quiz nazov_testu = models.CharField(max_length=50) # here's the name of the quiz datum_testu = models.DateField() # here's the date where was quiz released obsah_testu = models.ManyToManyField(UctovnyPripad, blank=True) # THERE ARE ALL "question" that you need to answer slug = models.SlugField(blank=True) # there's slug of my quiz def __str__(self): return self.nazov_testu def save(self, *args, **kwargs): self.slug = slugify('test-' + self.nazov_testu) super(UctoTest, self).save(*args, **kwargs) Example of quiz (obsah_testu) That I'm choosing in administration class UctovnyPripad(models.Model): ### UCTOVNE DOKLADY ### VYBER_DOKLADU = [ ('VPD', 'Výdavkový podkladničný doklad'), ('PPD', 'Príjmový pokladničný doklad'), ('VBÚ', 'Výpis z bankového účtu'), ('PFA', … -
Django + DRF Create file from json value
I'm building a part of django+drf app that will create article models from the given JSON request. Example of request: { "title":"title" "author":"author" "text":"possible huge amount of text" ... } Article model: class Article(models.Model): title = models.CharField(max_length=config.ARTICLE_TITLE_MAX_LENGTH) views = models.IntegerField(default=0) author = models.ForeignKey(User, related_name='articles', on_delete=models.CASCADE) date_created = models.DateTimeField('Date created', auto_now_add=True) published = models.BooleanField(default=False) text = models.FileField(upload_to='content/articles_storage/', null=True) This data is processed by article serializer class ArticleSerializer(serializers.ModelSerializer): # content = serializers.CharField() ??? class Meta: model = Article # fields = ['id','title','views','date_created','content'] fields = ['id','title','views','date_created','text'] Serializer expects text field to be a file, however, it is gonna be plain text, so when the user makes a POST request to the server, I want the server to validate the text, create a file from this text, save it to the folder content/article_storage When the user makes a GET request, I want the server to read that file and create a JSON response like above. My question is what is the best way to do this? I definitely don't want to use django's TextField. Also I'm wondering if I actually need FieldFile, maybe it's better to store the text in a file with the name = article id? -
Django models for multiple foreign keys and getting inputs through forms
I'm trying to build SCM models that involve multiple layers of foreignkeys, and then get inputs for them in one form. For example, when a purchase order is made, it may contain multiple products which may ship in multiple shipments. A shipment is defined as a group of containers with same origin and destination leaving on the same date under one trade documentation. Each container may contain multiple products, and in rare cases, inventory for one product may belong to multiple purchase orders. A container cannot belong to more than one shipment. What would be the best way to structure these relationships? And how can I use one template to get input using forms and save them via view? Below is some of the relationship I tried to build. I'm not sure if this class and relationships are the best designs. If I want to collect information on purchase order and related shipments, containers, and products in one HTML template, how should I use the Django forms? Here is some pseudo code for example: class PurchaseOrder(models.Model): issuedBy = models.ForeignKey('Company') issuedAt = models.DateTimeField() class Shipment(models.Model): purchaseOrder = models.ManyToManyField('PurchaseOrder') origin = models.ForeignKey('Address', related_name='origin_for') destination = models.ForeignKey('Address', related_name = 'destination_for') shippedAt = models.DateTimeField() … -
In Django getting data from two different models that models are got from MySQL database and need to use Django_filters on it
Actually I got the MySQL database using inspect db... Database is based on sales. One model OcOrder that contains the customer details such as orderid , customer name ,email, date_added etc and another model OcProduct contain productid , orderid , productname etc. I have render data from both models in django tables ... Now I need to create a django_filters based on customer name, date_added , product name... How should I write Django_filters for it? -
Can't install new packages or list existing packages in virtual environment with pip
When trying to install the django import_export module with pip install django-import-export into my virtual environment, it indicates that it was successfully installed, however, when I try to use the import_export module in my project, I receive an error: ModuleNotFoundError: No module named 'import_export'. I'm also unable to list any previously installed apps with pip list or pip freeze, and trying to upgrade the pip version using pip install --upgrade pip also says the new version is successfully installed, but isn't installed within my virtual environment. I've made sure to activate my virtual environment with source /home/travis/Documents/Python/Django/Projects/issuetracker/.env/bin/activate. Output from pip install django-import-export: (.env) [travis@spooky issuetracker]$ pip install django-import-export Collecting django-import-export Using cached https://files.pythonhosted.org/packages/62/7a/ddd9aef718243504e7715bda9bb5a100cfc353be37dc819d9914a7073cba/django_import_export-1.2.0-py2.py3-none-any.whl Collecting tablib (from django-import-export) Using cached https://files.pythonhosted.org/packages/7b/c7/cb74031b330cd94f3580926dc707d148b4ba9138449fc9f433cb79e640d8/tablib-0.13.0-py3-none-any.whl Collecting diff-match-patch (from django-import-export) Using cached https://files.pythonhosted.org/packages/f0/2a/5ba07def0e9107d935aba62cf632afbd0f7c723a98af47ccbcab753d2452/diff-match-patch-20181111.tar.gz Requirement already satisfied: django>=1.8 in ./.env/lib/python3.7/site-packages (from django-import-export) (2.2.4) Collecting openpyxl>=2.4.0 (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/f5/39/942a406621c1ff0de38d7e4782991b1bac046415bf54a66655c959ee66e8/openpyxl-2.6.3.tar.gz Collecting xlwt (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/44/48/def306413b25c3d01753603b1a222a011b8621aed27cd7f89cbc27e6b0f4/xlwt-1.3.0-py2.py3-none-any.whl Collecting xlrd (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/b0/16/63576a1a001752e34bf8ea62e367997530dc553b689356b9879339cf45a4/xlrd-1.2.0-py2.py3-none-any.whl Collecting backports.csv (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/8e/26/a6bd68f13e0f38fbb643d6e497fc3462be83a0b6c4d43425c78bb51a7291/backports.csv-1.0.7-py2.py3-none-any.whl Collecting odfpy (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/85/7d/8f6d1f2a4683be362b101c00232b4c3839e4e4a90e0945d8d43ec6aa671d/odfpy-1.4.0.tar.gz Collecting pyyaml (from tablib->django-import-export) Using cached https://files.pythonhosted.org/packages/e3/e8/b3212641ee2718d556df0f23f78de8303f068fe29cdaa7a91018849582fe/PyYAML-5.1.2.tar.gz Requirement already satisfied: sqlparse in ./.env/lib/python3.7/site-packages (from django>=1.8->django-import-export) (0.3.0) Requirement already satisfied: pytz in ./.env/lib/python3.7/site-packages (from django>=1.8->django-import-export) (2019.2) Collecting jdcal (from openpyxl>=2.4.0->tablib->django-import-export) … -
Django checks form validity multiple times
I am working on an old Django 1.8 application and adding ReCaptchas to contact forms. Since this Django version is not supported by current Captcha modules I am rolling my own functionality which is pretty straightforward thanks to Googles good documentation. The problem I am having is with form validation. I have a class based form in which I am implementing my own clean method. In the clean method I am handling the request/response to Googles ReCaptcha Service. This is all well and good. When submitting the form, the post method in my views.py calls is_valid() on the form which calls the clean method of the form. I get a successful response from Google and move on to render the view. But then, for some reason, the forms validity is checked once again but then I get a failure from Googles ReCaptcha service because it is a duplicate request. I then get of cause a ValidationError and get sent back to the form. I stepped through the code with pdb and found that my clean methods get called again when response.render() gets called in ../django/core/handlers/base.py(164)get_response(). Why does Django check the forms validity twice? Can I circumvent it? If not, how … -
How to store URLs in Django right way?
I'm new in Django and sorry for such silly question. I wonder how to store URLs right way. I have in mine .html some hardcoded URLs to third party webserveces. And I know hardcode is a bad way. It's impossible to add those URLs to urlpatterns cause url() or path() requires to set certain views which I don't have. It will be great to concatinate URLs. Should I store these URLs variables in settings.py or somewhere else? Will be appriciated for any answers. -
Django 2 -403 forbidden error : Not able to make a get request from views.py
I want to enable GET request from a function in views.py and read the data. My function is in views.py which is triggered upon POST request. @csrf_exempt def paysuccess(request): #process requests URL ="http://example/apiusername=111390&pwd=123&circlecode=2&format=json" #make get request request=urllib.request.Request(URL) response = urllib.request.urlopen(request) #read response Traceback shows issues in csrf.py file. Traceback (most recent call last): File "/usr/lib/python3.4/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/lib/python3.4/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.4/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/rhtry/redirect/redirect/views.py", line 174, in paysuccess response = urllib.request.urlopen(request) File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.4/urllib/request.py", line 470, in open response = meth(req, response) File "/usr/lib/python3.4/urllib/request.py", line 580, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python3.4/urllib/request.py", line 508, in error return self._call_chain(*args) File "/usr/lib/python3.4/urllib/request.py", line 442, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 588, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden -
User will not authenticate Django
I've asked this question a few times and have been working on this a few days and it still does not work. User will not authenticate in Django. I'm using the base user model. My user does not get authenticated and the form does not submit and I'm unclear what is going wrong. Here is my views.py: def payments(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # this is because they need to fill out another form before I deem them active user.set_password(form.cleaned_data['password1']) user.save() user = authenticate(request, username=form.cleaned_data['username'], password=form.cleaned_data['password1']) if user.is_authenticated: login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('agreements') else: raise ValidationError("User could not be authenticated.") else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) Here is my forms.py: class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) first_name = forms.CharField(label='First Name', widget=forms.TextInput(attrs={'class': "form-control"})) last_name = forms.CharField(label='Last Name', widget=forms.TextInput(attrs={'class': "form-control"})) email = forms.CharField(label= 'Email', widget=forms.EmailInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") … -
How to annotate queryset with its own count()??? Django
Is it possible to annotate or add somehow to queryset same queryset count? For example I have following queryset: queryset = User.objects.filter(username__startswith=”A”) and I want to annotate each row of fetched data with queryset count, that is an amount of objects this queryset contains. Lets call this field “amount”. Finlay I want to do something like this after queryset got fetched from DB: Lets say queryset contain 50 objects. queryset.first().amount <<< 50 This needs to be done in one query as sample size realistically over 10K objects. Thank you! -
How to access a Django website from remote server in a local browser?
I've looked and tried things for hours, and nothing seems to work. Here's the info: On my Windows machine, I use PuTTY or MobaXterm to connect to a remote Linux server using SSH (command line only). I started a new project with this command: django-admin startproject mysite. I activate a virtual environment using the source command. I run the server using this command: python3 manage.py runserver 0.0.0.0:8000. Let's say the output of ip a results in the following fake IP addresses: 1: inet 127.0.0.1/8 scope host lo 2: inet 172.10.12.50/24 brd 172.10.12.200 scope global ens3 3: inet 62.3.8.10/26 brd 62.3.8.22 scope global ens4 Now what? I can't figure out how to visit the website. I've tried the various IP addresses, I've tried using PuTTY's tunneling/port forwarding capabilities, I've tried figuring out MobaXterm's tunneling/port forwarding capabilities, and I think I've tried every possible combination of IP addresses in those settings. Nothing works. I am supposedly able to access the site using http://127.0.0.1:8000 when the port forwarding works correctly, but that hasn't happened yet. I have also tried using the other IP addresses from the ip a command.