Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a field in the model that does not require to be filled
how should I create a field in Django with a parameter that doesn't require to be filled for example i want to create a 'newprice' field that if i don't fill it,it doesn't give me an error if you know pls answer,thank you -
Best way to add third attribute to Django models choices
As the title suggests, what would be the best way to go about adding a third attribute to Django's model enum choice so that I could access the property in the same manner as value or label. For instance, let's call this third attribute text what I want: class Vehicle(models.Model): class VehicleType(??): HONDA_CIVIC = 1, _("New car"), _("Vroom vroom") FORD_MODEL_T = 2, _("Old car"), _("not so fast") type = models.IntegerField(choices=VehicleType.choices, default=VehicleType.FORD_MODEL_T) vehicle = Vehicle.objects.create() vehicle.type.text >>> not so fast Is this possible without overwriting the base ChoicesMeta? I've tried a version as outlined in the python enum docs by updating __new__ however this doesn't seem to work. (And yes, I know I could change it to models.TextChoices and nix the int value, but I'm curious if this is easily possible) -
Using the url path data to pre-load fields in my HTML template
Short story on my project: I'm working on an app for work orders. A work orders consist of serial different momentums, called operations. Each work order have different operations depending on the type of work to complete. For each operations you can report your working time as instances. So to start a new instance you need to define workorder, operation, user and start time. In the databases there will be several thousand work orders and each one will have 3-10 different operations. So to simplify start (and then in the other end stop) a work instance I had an idea to try to utilize url for the workorder and then use the workorder to filter the query set of operations. But with my limit knowledge I'm stuck. I've been looking for hints and tried out different solutions for several days now. I have been able to solve it with a AJAX dynamic filtering, but I wanted to see if there was a way to solve it at the instance of rendering the page. to make it simpler I have reduced my app to the parts related to this question. My models.py from django.db import models from django.urls import reverse #Work … -
Custom registration form in django is not working correctly
The form fills in successfully even when a short numeric password is entered. I want the form not to be able to set short passwords only consisting of numbers. #forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label='Адрес электронной почты') password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label='Пароль повторно', widget=forms.PasswordInput, help_text='Введите тот же самый пароль ещё раз для проверки') captcha = CaptchaField(label='Введите текст с картинки ', error_messages={'invalid': 'Неправильный текст'}, generator='captcha.helpers.math_challenge') def clean_password(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 and password2 and password1 != password2: errors = {'password2': ValidationError( 'Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user class Meta: model = AdvUser fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name', 'photo', 'description', 'captcha') How can I solve this problem? -
Send sms at a specific date and time in flask-restful?
I have an API using flask restful that stores user information like mobile number,message,date and time etc. I have to create a function that send sms to every users on their own date and time. Is there any way to do that? What are the best practices if there is more user? -
base64 to image using Django Rest Framework (DRF)
I am writing API, which accepts base64-encoded string and saves it as an image. It is trivial to do using standard library tools, such as base64, but how can I do it using viewsets.ModelViewSet? Which field should I modify? (I also have been trying to do it using custom middleware, but it is prohibited, since querydict cannot be modified) -
Is it worth to use `select_related()` when using just one instance of a model instead of a queryset?
I'll keep it short. Say we have this database structure: class Bird(models.Model): name = models.CharField() specie = models.CharField() class Feather(models.Model): bird = models.ForeignKey(Bird) And then we have some simple lines from an APIView: feather_id = request.query_params['feather'] feather = Feather.objects.get(pk=feather_id) bird_name = feather.bird.name # a lot of lines between bird_specie = feather.bird.specie Does it make any difference using: feather = Feather.objects.select_related('bird').get(pk=1) instead of: feather = Feather.objects.get(pk=1) in this scenario? I saw some people using select_prefetch() in this way and i wonder if it makes any difference, if not, which one should you use? Normally i agree that select_prefetch() is useful for optimization when using querysets to avoid querying each instance individually, but in this case, is it worth using it when you have just one instance in the whole APIView? In my opinion the only difference is that another query is just made later on, but when talking about performance, it's the same. Thanks in advance. -
Django crispy input from Ajax data
I need to Auto-fill up the crispy fields so I called the needed data from my database using ajax function as: views.py def load_record(request): PUITS_id = request.GET.get('PUITS') record = SurveillanceDesPuits.objects.filter(PUITS_id__id__exact=PUITS_id)[:1] my_record= [str(record[0].PUITS) , str(record[0].MODE), str(record[0].CS)] print(my_record) return render(request, 'measure/Surveill_Wells/Add_wellMntr.html', {'record': my_record}) And my HTML file is : <form method="POST" id="SurveillanceDesPuits_F" data-record-url="{% url 'ajax_load_record' %}"> {% csrf_token %} <!-- form from views.py--> <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div class="form-group col-md-3 mb-0"> {{ form.PUITS|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.CS|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> {{ form.MODE|as_crispy_field }} </div> </div> </div> <input class="btn btn-success mb-4" type="submit" value="ADD Record"> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_PUITS").change(function () { var url = $("#SurveillanceDesPuits_F").attr("data-record-url"); var PUITSId = $(this).val(); $.ajax({ url: url, data: { 'PUITS': PUITSId }, success: function (data) { $("#id_MODE").html(data); } }); }); </script> After selecting an item (PUITS) from the dropdown list, I want to set the value of CS and MODE automatically from the received data. so in the console, it gives me this error: File "D:\WikiPED\venv\lib\site-packages\crispy_forms\templatetags\crispy_forms_filters.py", line 102, in as_crispy_field raise CrispyError("|as_crispy_field got passed an invalid or inexistent field") crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field [07/Sep/2021 17:30:05] "GET /ajax/load-record/?PUITS=1 HTTP/1.1" 500 25693 what I … -
Where to add Many to Many in django?
So, Am creating a app where user can add universities to their fav or wishlist ! The problem is, am just confused how and where add ManyToMany ? Model Student: name = models.CharField ..... Model University: name = models.CharField ..... Model Wishlist: wish = models.ManyToMany(University) Is this correct, is it okay to create a seprate model class as "wishlist" or can i have the wishlist on the Student: Am totally confused, all i need to do is "user needs to able to click heart button and add university to wishlist and if they reclicks it needs to removed" -
Django - create many to many objects inline simirly to inlinetabular for admin
I want to allow users to create inline/on-the-fly an object of model A that has a many to many relationship with a field of a model B, while creating an object B...basically just like TabularInline allows you to do on the admin. -
Why is my template html file not using bootsrap css?
[This is the output of my django website im working on, bootstrap css are not being applied on tags for some reason][1] This is the template code of django website im referring to. [This is the output of my command prompt, i'm newbie at using django im currrently learning and i have no idea how to fix this idea and get ahead with learning.][3] [this is my bootstrap file folder, as you can see the file path in link tag of my html file is correct, i dont know what is wrong with those errors[][4]4 -
How to add tokens to URL for running CSS file? [django]
when I run the program, the CSS file doesn't work with the project. when I see that on AWS and click on the "open file" button I see the file opening with the appendix query string which I can't add and I don't know where I should get it and placed it in. this query looks like this: ?response-content-disposition=inline&X-Amz-Security-Token=xx&X-Amz-Algorithm=xx&X-Amz-Date=xx&X-Amz-SignedHeaders=xx&X-Amz-Expires=xx&X-Amz-Credential=xxx&X-Amz-Signature=xxx but the real path I get from my own machine is the real path that precedes the query string that looks like: https://django-testing-files.s3.us-east-2.amazonaws.com/static/student_grade/css/style.css?... so, can anyone tell me where I should get and put this tokens? I googled then I understood that there's something called "disposition" that I should use but don't understand how can I get it. these are the codes I used: # settings.py AWS_ACCESS_KEY_ID = "xxx" AWS_SECRET_ACCESS_KEY = "xxx" AWS_STORAGE_BUCKET_NAME = "django-testing-files" AWS_HEADERS = {'Cache-Control': str('public, max-age=3')} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = True DEFAULT_FILE_STORAGE = "website.storage_backends.MediaStorage" AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_LOCATION = 'media' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-east-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_STORAGE = "website.storage_backends.StaticStorage" STATIC_LOCATION = 'static' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = True class StaticStorage(S3Boto3Storage): … -
How to render custom return_uri in google_auth_oauthlib
I have tried to add custom return_uri but it's now allowing to add. It assigns default its own localhost URL. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) enter image description here Please anyone could help me with this -
temp emails and avoid them using django
i want to block temp emails and just make user can to register just if the email is real (like gmail , outlook , yahoo) forms.py class SginupForm(UserCreationForm): class Meta: model = User fields =('username', 'first_name','last_name','email','password1','password2' ) views.py @unauthenticated_user def signup_form(request): if request.method == 'POST': form=SginupForm(request.POST) if form.is_valid(): user=form.save() send_action_email(user,request) messages.add_message(request, messages.SUCCESS, 'we v sent ur activtion link') return redirect('core:login') else: form=SginupForm() return render(request,'user/sign-up.html',{'form':form}) -
How do I reload Django model-forms?
Currently my models look similar to this, def feature_tuples(): features = (('a', 'a'), ('b', 'b')) return features class Sample(models.Model): choices_tuple = models.CharField(max_length=20, blank=True, null=True, choices=feature_tuples()) I than created a model form of this model. However, at some point i want to change the choices of choices_tuple from a, b to c, d. I can't find a way to reload the choices of choices_tuple in the form. Help? -
How to get QuerySet of ForeignKey field Django
I have two models. First one: class KvantMessage(models.Model): text = models.TextField(blank=True) style_text = models.TextField(blank=True) receivers = models.ManyToManyField(MailReceiver) date = models.DateField(default=timezone.now) files = models.ManyToManyField(FileStorage, blank=True) title = models.CharField(max_length=120, default='Письмо') sender = models.ForeignKey(KvantUser, on_delete=models.CASCADE, related_name='sender') And second one: class ImportantMail(models.Model): user = models.ForeignKey(KvantUser, on_delete=models.CASCADE) mail = models.ForeignKey(KvantMessage, on_delete=models.CASCADE) The question is, how to get all mails instances as "KvantMails" from "ImportantMail" where user is equal to some user. P.S. Hope you understand my question -
How to get a unique serial_number for a abstract base class in Django?
I have a abstract base model and two child models: class Component(models.Model): serial = models.PositiveIntegerField(unique=True) last_modified = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class ChildComponentA(Component): name = models.CharField(max_length=200, null=True, blank=True) class ChildComponentB(Component): name = models.CharField(max_length=200, null=True, blank=True) I want the serial field to be unique for all children but this does not work for me. How can I achieve this? -
What is the difference between Django and Flask [closed]
I want to start backend development with Python and am confused on which web framework to choose. Which one should i start with Django or Flask -
How to pass S3 URL instead of file in DRF request?
I am currently migrating an application from a low-code application to a full backend. As a part of the migration, I'm currently in the middle of DB migration. The values of the current proprietary DB are fetched as a JSON via an API and the files are stored in an S3 bucket. I am using DRF serializers to remap the values and I want to retain the S3 URLs when mapping them to an ImageField. However, DRF keeps expecting a file object and I am unable to figure out a way to set the URL into the DB with DRF Viewsets. -
Speaking and Listening simultaneously like Alexa [closed]
I am trying out on something which is very new to me. I wanted to develop a feature which is something like Alexa. So, Here goes the feature I wanted to develop. When I click on play button, the system has to read out the contents stored as a pdf. While speaking it also has to listen out for any queries from the user. What have I tried so far? I have tried working out this feature using pyttsx3 module. But this module only speaks but it doesn't listen. I also have a problem in pausing and resuming the speech. import pyttsx3 import pdfplumber import PyPDF2 file = 'C:/Users/Downloads/Books/Eleven Minutes.pdf' #Creating a PDF File Object pdfFileObj = open(file, 'rb') # creating a pdf reader object pdfReader = PyPDF2.PdfFileReader(pdfFileObj) #Get the number of pages pages = pdfReader.numPages speaker = pyttsx3.init() if 'play' in request.GET: with pdfplumber.open(file) as pdf: #Loop through the number of pages for i in range(0, pages): page = pdf.pages[i] speaktext = page.extract_text() speaker.say(speaktext) speaker.runAndWait() if 'stop' in request.GET: speaker.endLoop() spaker.stop() What is my system based on? It is based on Python, Javascript, SQlite. I would appreciate any help with this. TIA -
How do I set the default value for instance variable?
class SafetyValveSerializer(serializers.ModelSerializer): # Instead of exposing the state's primary key, use the flag field state_flag = serializers.SlugRelatedField(source='sv_state', queryset=SafetyValveState.objects.all(), slug_field='flag') class SafetyValveState(models.Model): sv_state_key = models.AutoField(primary_key=True) flag = models.IntegerField(unique=True) description = models.CharField(max_length=50) How do I set the default value of state_flag to 0 when call SafetyValveSerializer partially not passing state_flag? -
How can i in Django Oscar filter EAV Attributes in Frontend?
In Django Oscar when i add a new product class i can insert new dynamic attributes. This is a implementation from Django EAV. Now i want in frontend to view a form with all EAV Attributes and when this form is submit then Django Oscar filter products after this EAV attributes. Have anyone a idea how i can implement this? I try nothing till yet. I know that i can filter with products.objects.filter(eav_attributename='blabla') but how can i make a form with all EAV Attributes? When user submit it how can a filter products after several EAV fields? -
Django - Annotate Count() of distinct values grouped by Date
I have the following Model: class Visualization(models.Model): .... user: FK user start_time: DATETIME product: FK product .... Example data: | User ID | Start Time | Product ID | | :----: | :----------: | :-------: | |1|2021-09-07 14:03:07|3| |2|2021-09-07 13:06:00|1| |1|2021-09-07 17:03:06|1| |4|2021-09-07 04:03:05|5| |1|2021-09-07 15:03:17|4| |1|2021-09-07 19:03:27|1| |2|2021-09-06 21:03:31|3| |1|2021-09-06 11:03:56|9| |1|2021-09-06 07:03:19|9| I need to get the active users for days, the active users are those who made at least one reproduction, if a user made many reproductions, it still counts as 1. A correct answer would be: | Total | Date | | :----: | :----------: | |3|2021-09-07| |2|2021-09-06| First I make an annotation a Truncate of StartTime to keep only the Date and then I make Group By for this annotation, so far everything without problems. The problem is when I try to count the Users since they have repetitions. I have tried to count the User_id with Distinct = True, but the numbers still give me bad, also by a very big difference. I also tried grouping by user_id and period (annotation of Truncate StartTime) but it didn't work for me either -
how can i replicate admin.TabularInline outside of the admin (on the user side?)
Given a mode A and a model B that has a field with a many to many relationship with model A, I am trying to allow users creating an object of model B to also create an object of model A inline/on-the-fly just like TabularInline allows you to do on the admin. -
React Django Auth
I'm trying to login thru ReactJS app and here is the error I get: Access to XMLHttpRequest at 'http://localhost:8000/auth/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. even though I added CORS_ALLOW_CREDENTIALS: True to the settings.py: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ["http://localhost:3000"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "corsheaders", 'rest_framework', 'service_get_data', 'background_task', 'service_append_data', ] MIDDLEWARE = [ …