Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Auth User Model Set different field name for password
I recently look into Django framework and plan to migrate my old system into it. Therefore, there is legacy mysql database that I need to follow. Is there anyway to change the field name of password of Django User Model? such as "pwd" or "password2". I got research the Django document, only able to find out changing the username field https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD -
Django - Working With different Timezones
I am working on a Django application on Dietitian Portal, in which there are client from different countries.Now For appointment booking for client i need to send availabe time slots to user according to dietitian's timezone. Now the problem is that if dietitian's timezone is Asia/Calcutta and client's timezone is Us/Eastern or other.when the client is requesting for slots than there is a date 19 and accoring to dietitian's timezone 20th, So how can i manage this that i can cover the whole day of dietitian in client's timezone It works Fine if date is same but if two different dates are there than the problem comes.Client is not able to fetch slots of dietitian because according to dietitian's timezone date is 20th. -
D j a n g o app has not valid view function
I have an app for quiz. It shows registered quiz, but when I press submit button - it goes to /quiz/1/do/ to do function in views.py which should do this return HttpResponseRedirect(reverse('quiz.views.results', args=(q.id,))) But it throws an error msg NoReverseMatch at /quiz/1/do/ Reverse for 'quiz.views.results' not found. 'quiz.views.results' is not a valid view function or pattern name. I wonder where could be a problem? Here are my codes views.py from quiz.models import Quiz, Question, Score from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.template import RequestContext from django.contrib.auth.decorators import login_required @login_required() def index(request): latest_quiz = Quiz.objects.all().order_by('-created')[:5] return render_to_response('quiz/index.html', {'latest_quiz': latest_quiz}) def detail(request, quiz_id): q = get_object_or_404(Quiz, pk=quiz_id) context = {'quiz': q} return render(request, 'quiz/detail.html', context) def results(request, quiz_id): return HttpResponse("You're looking at the results of quiz %s." % quiz_id) def do(request, quiz_id): q = get_object_or_404(Quiz, pk=quiz_id) try: answer = '' for question in q.question_set.all(): answer += request.POST['q%d' % question.id] except (KeyError, Question.DoesNotExist): # Redisplaying the form return render_to_response('quiz/detail.html', { 'quiz': q, 'error_message': "You didn't do the quiz %r " %request.POST, }, context_instance=RequestContext(request)) else: s = q.score_set.create(student=request.user.username, submit_answer=answer, score=100) s.save() return HttpResponseRedirect(reverse('quiz.views.results', args=(q.id,))) # HERE !!! def not_found(request, exception=None): response = render(request, '404.html', {}) … -
Have I to delete SQLite database from the directory after migrating to PostgreSQL on Django 2.2?
I am new to Django 2.2 and I found that SQLite is default database engine here. But I want to use the PostgreSQL instead of SQLite. I have created a new project and migrate the (ex: Post) model after creating and adding the app to the settings.py and admin.py file. And after that, I decided to use the postgreSQL, and I did it too by migrating to postgreSQL. Before migrating I created a postgres database and add all the necessary details to the settings.py file's DATABASE settings according to instruction of Django. It's working fine. I haven't got any problem yet. Though I see still the sqlite database file still in the project directory. It looks bit odd though. I'm new to Django. Can you please tell me should I keep that file there or delete sqlitedb file? And is there any security issue with sqlitedb file if I keep there? I love to want a neat and clean project settings. Thanks in advance my dear friends! -
can not make migration multiple databases in Django 2.2
No matter what database I use when doing a ./manage.py migrate it is migrating all tables to the database. Goal The goal is to be able to have an app that all models in that app go to a seperate database, other models like the django-admin, go to default. Expected I expect that when I target no database it migrates all existing migrations, not in my new app, to the default database connection. Then when I run ./manage.py migrate --database=otherdatabase it only migrates those models in the new app, or none at all. This could be a flawed expectation, but it is my understanding of what should happen. What is happening No matter what database I use when doing a ./manage.py migrate it is migrating all tables to the database. Steps to reproduce Install create virtualen environment Setup a postgres database. I am doing this throud docker version: "3" services: db: image: postgres:10.1-alpine environment: POSTGRES_DB: "database1" POSTGRES_USER: "postgres" ports: - 5432:5432 Install psycopg2-binary and Django django-admin.py startproject routing Edit routing/settings.py adding the following to the database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database1', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, 'database2': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database2', … -
django - How to check choices of an object and display corresponding item on html
I am working on a photo app, which allows one to upload images. From there, there are choice options for each photo -- either "PUBLIC" or "PRIVATE"--. For images that are "PUBLIC", the image will be shown on the home page without need for user authorisation. However, I am finding difficulty in filtering the images based on the choices and display the relevant object on the home page. I am new to coding and Django, would appreciate some advice here. Thanks in advance! This is my models.py file: class Images(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') PRIVATE ='PR' PUBLIC = 'PU' PUBLISH_CHOICES = [ (PRIVATE, 'Private'), (PUBLIC, 'Public'),] publish = models.CharField(max_length=7, choices=PUBLISH_CHOICES, default=PRIVATE) def __str__(self): return self.title This is my views.py file class HomePageView(ListView): model = Images template_name = 'index.html' def my_view(request): myimages = Images.objects.all() for entry in myimages: publish_status = entry.get_publish_display() return publish_status This is my index.html file: {% for images in images_list %} {% if publish_status == Public %} <div class="container"> <h3>{{images.title}}</h3> <img src="{{images.image.url}}" alt=" {{images.title}}"> </div> {% endif %} {% endfor %} -
Attribute Error when trying to authenticate
I am using django o_auth2 toolkit for authentication and trying to incorporate throttling to limit the number of requests, but this throws me an error. The settings.py can be observed below: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication' ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '1/day', # 'user': '1000/day', 'user': '2/day', # 'user': '15/second' } } And my class view is below: DEFAULT_PERMISSION_CLASSES = permissions.IsAuthenticated class GetSomeValues() permission_classes = DEFAULT_PERMISSION_CLASSES throttle_classes = (UserRateThrottle,) def get(self,request,**kwargs): # do something But it gives me the following error: 'NoneType' object has no attribute 'is_authenticated' And it doesn't give any error when throttle_classes = () but then throttling doesn't work. -
Django app in Heroku POSTing to Amazon s3 gets 403
I have a Django app hosted in Heroku configured to upload/download/view files stored in Amazon S3. I can only upload files to S3 when public access is enabled, and I've gone through all the steps to set things up in my app and in S3, and I always get 403 FORBIDDEN. Settings.py: AWS_ACCESS_KEY_ID = '<my id>' AWS_SECRET_ACCESS_KEY = '<my key>' AWS_STORAGE_BUCKET_NAME = '<my bucket>' AWS_S3_REGION_NAME = 'us-east-1' AWS_S3_ENDPOINT_URL = 'https://s3.us-east-1.amazonaws.com' S3DIRECT_DESTINATIONS = { 'files': { 'key': '/' } } IAM Policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::<my bucket>/*" } ] } CORS Policy: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>https://<my app>.herokuapp.com</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>ETag</ExposeHeader> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Any ideas? I can try creating another access key but I just can't seem to get my app to properly authenticate. -
How to gradually shift current Django unit tests to pytest?
Currently, I have a Django 1.11 project. It's setup to act solely as an API backend using Django Rest Framework. I write unit tests using mostly APITestCase from rest_framework.test, TestCase from django.test, and sometimes TestCase from test_plus. When I execute my tests I typically use commands like python manage.py test python manage.py test somemodule.tests.some_test_file.TestClass.specific_test_case Or the above but with the keepdb flag to shorten the testing time python manage.py test --keepdb python manage.py test somemodule.tests.some_test_file.TestClass.specific_test_case --keepdb How do I shift to using pytest gradually? By gradually, I mean long term I move to pytest and pytest commands, but in the meantime, the tests already written can still be used in a single commmand because my CICD on CircleCI is still dependent on the tests to pass. -
Can anyone give the exact explanation of below code line by line
//import from django.db import connections from django.db.utils import OperationalError //db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True -
Try to insert loop into __init__
I have a object Quiz in Django database, which contain test_name and num_of_questions columns. I'm trying to get that values all render name, count questions and render columns for the questions in a next step(with appropriate quiz name). I'm new in classes, so I would like to ask, if I'm doing it right? from .models import Quiz class rendered(): quizs = Quiz.objects.all() for quiz in quizs: quizname = quiz.test_name n_o_q = quiz.num_of_questions tup = (quizname, n_o_q) def __init__(self, quiz_sum): self.quiz_sum = tup super(rendered, self).__init__() -
How to fix AuthError on django app using dropbox for profile upload?
I'm creating a simple blog site. The site has a profile page and it can change profile image. I'm using Dropbox to save the images because of it's free tier. I can already save the images to Dropbox and it shows on my template/views but when I log out and log in, the error occurs. It says "AuthError('3ebf1ce1d4452c9087fba3bbb05e29a5', AuthError('invalid_access_token', None))" I'd already search for some documents on how to fix this but I can't find any solutions. This is what I set up my setting on Django. ''' DEFAULT_FILE_STORAGE = storages.backends.dropbox.DropBoxStorage' DROPBOX_OAUTH2_TOKEN = os.environ.get('DROPBOX_OAUTH2_TOKEN') DROPBOX_ROOT_PATH = os.environ.get('DROPBOX_ROOT_PATH') ''' -
Multiple lists in modelChoiceField in django modelForm
I have a Profile, work, education and current occupation models. Relationship between models, Profile ------- ManytoMany ------ Work Profile ------- ManyToMany ------ Education Profile ------- OneToOne ------ Current_occupation I want to a dropdown for current occupation which will have all the work and education values. So far I am able to show job title of work experience, What I want is the dropdown to show all values from education table and organization like this, How should I approach? Profile class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=30, null=True, blank=True) experience = models.ManyToManyField(Work_Experience, blank=True) education = models.ManyToManyField(Education, blank=True) current_occupation = models.OneToOneField(Current_occupation, on_delete=models.CASCADE, null=True, blank=True) Education class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) Experience class Work_Experience(models.Model): job_title = models.CharField(max_length=100, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) Current_occupation class Current_occupation(models.Model): title = models.CharField(max_length=100, null=True, blank=True) organization = models.CharField(max_length=100, null=True, blank=True) Form class ProfileSettingsForm(forms.ModelForm): class Meta: model = Profile fields = ['image','full_name','biography','profile_email','linked_in','facebook', 'twitter','phone','education', 'is_active', 'current_occupation'] def __init__(self, request, *args, **kwargs): super(ProfileSettingsForm, self).__init__(*args, **kwargs) self.request = request self.fields['current_occupation'].queryset = Profile.objects.filter(user=self.request.user.profile.id).values_list('experience__job_title', flat=True) View class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.object.id,)) def … -
Large transfer of data between several Django models
I have 6 models, three of 2 types. The types being private and public, but, in this case, all the models have the same fields. class AbstractModel(models.Model): text = models.CharField(max_length = 1) in_group = models.ForeignKey(GroupTable, on_delete=models.SET_NULL, null=True) class Meta: abstract = True class Public1(AbstractModel): pass class Public2(AbstractModel): pass class Public3(AbstractModel): pass class Priv1(AbstractModel): pass class Priv2(AbstractModel): pass class Priv3(AbstractModel): pass class GroupTable(models.Model): private = models.BooleanField(default=True) post_save.connect(herd_migration, sender=DecidingTable) Ok, so with these models, time for signals.py. I'm trying to transfer all the charfields from Public to Priv tables, and Public1 data goes to Priv1, Public2 to Priv2, and Public3 to Priv3. The problem is mostly user end: The models are designed like a nested tree path for specific design purposes. When a group switches the attribute private to False, the signal is "sent" to start data transferring of all records in Priv1-3 that are in that specific group to Public1-3. I was thinking of these two options: 1) Temporarily shutdown the group so that no more POST reqs are sent that corresponds to the group and quickly transfer all Priv1 data to Public1, Priv2 to Public2, and Priv3 to Public3. 2) Add a table that's kinda like a queue to add … -
Bad Request with rest framework javascript requesting a pdf file
I have this javascript (actually coffeescript but in the end it's the same thing) and I have this python code that receives the code and returns a pdf, however. It's getting me a bad request code and the pdf isn't working, I am aware that the server is receiving correctly the html string and the pdf code works because the same render is the same that renders a table. So I assume the issue is with the javascript. But, what could be the problem? I basically tried rewrite the code and tried to convert to a get request. However, the html code that I send easily exploded the url limit. Which I didn't know existed. Here's the python code in the server of the render: class CustomPdfResponse(CustomHtmlRender): media_type = "application/pdf" format = "pdf" def get_pdf(self, html_string): url = 'http://localhost:9288/' pdf_name = "test.pdf" header = {"pdf-options": "landscape"} return requests.post(url + pdf_name, data=html_string, headers=header) def render(self, data, accepted_media_type=None, renderer_context=None, **kwargs): graphics = renderer_context['request'].query_params.get("graphics", False) title = renderer_context['request'].query_params.get("title").strip() title = title.replace("\n", "").encode('ascii', 'xmlcharrefreplace').decode("utf-8") filter_context = renderer_context['request'].query_params.get("date_filter").strip() filter_context = filter_context.replace("\n", "").encode('ascii', 'xmlcharrefreplace') filter_context = filter_context.decode("utf-8") if not graphics: if not isinstance(data, DataFrame): data = data["results"] table, is_multi_index = self.get_table(data, renderer_context, without_perms = True) table … -
Django Forms ChoiceField: How to get the selected Value
I want to filter the count of objects in the template with a HTML Select/Django forms.ChoicheField. I have a Submit Button where I send a POST request to the view. There I create my form, but I my form isn't valid. Example of Choices: MY_CHOICES = ( ('1', '20'), ('2', '30'), ) HTML Code: in object_selected_option the currently selected value is saved. {% if form %} <select id="select-count" name="select_fields"> {% for option in form.select_fields.field.choices %} <option value="{{option.id}}" {% if option == object_selected_option %} selected="selected"{% endif %}> {{ option.option }} </option> {% endfor %} </select> {% endif %} views.py: form = SelectCountForm(request.POST) if form.is_valid(): #count_ = get selected value ??? queryset_vocab = queryset_vocab[:count_] forms.py def get_all_select_options(): return SelectCountVocabsOptions.objects.all() class SelectCountForm(forms.Form): def __init__(self, *args, **kwargs): super(SelectCountForm, self).__init__(*args, **kwargs) self.fields['select_fields'] = forms.ChoiceField(choices=get_all_select_options()) models.py class SelectCountOptions(models.Model): option = models.IntegerField(verbose_name="option") class SelectedCountOption(SingletonModel): selected = models.OneToOneField(SelectCountVocabsOptions,on_delete=models.CASCADE) I store all select options and the selected option separate in an own model. Why is my form invalid? How is it possible to retrieve the selected item from the POST request? I think, I have to change something with my form, but I don't know what. Thanks in advance. -
Azure/Kudu update python PATH from 2.7 to 3.6
I have tried all day to publish my Django Project from Visual Studio and I think I have nailed down the problem. When it automatically created the environment, it installed Python 2.7. I am using Django 2.2+, which only runs on Python 3+. Python 3.6 path: D:\home\python364x64> I can get the environment to use 3.6 for a session but I can't work out how to make the change permanent from either the Kudu Powershell or the Azure portal. I am clearly missing something very simple but none of the documentation covers this problem. This is also the web.config file. I dont know if it helps at all so I'll add it as it is better to have too much info than not enough: <configuration> <system.webServer> <handlers> <add name="PythonHandler" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python364x64\Scripts\pip3.exe" resourceType="Unspecified" requireAccess="Script"/> </handlers> <rewrite> <rules> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> </conditions> <action type="Rewrite" url="handler.fcgi/{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/> </handlers> <httpPlatform processPath="D:\home\python364x64\Scripts\pip3.exe" arguments="D:\home\site\wwwroot\runserver.py --port %HTTP_PLATFORM_PORT%" stdoutLogEnabled="true" stdoutLogFile="D:\home\LogFiles\python.log" startupTimeLimit="60" processesPerApplication="16"> <environmentVariables> <environmentVariable name="SERVER_PORT" value="%HTTP_PLATFORM_PORT%" /> </environmentVariables> </httpPlatform> </system.webServer> <appSettings> … -
Passing a date to a queryset based on a button click in Django
I have Manifest View that querys date_scheduled and returns distinct values. I pass that queryset to a template and loop over the values and present them as buttons on the HTML file. I am able to click any button and pass the corresponding date into the URL,((localhost/schedule/2019-06-20) when I click on the June, 20 2019 button) thus redirecting me to my RoastManifestDetailView. Now I want to be able to filter my RoastManifestDetailView based only on the date passed to the URL (or which date button was clicked). I have tried RoastManifest.obejects.filter(date_scheduled__date=date.today())just to see if I could return anything schedule for today but I keep getting Fielderrors (Unsupported lookup 'date' for DateField or join on the field not permitted.). Please note I know that is not the exact queryset for me. I wish to pass in a variable into the queryset. This is the model: (NOTE: roast_order is in there only to allow for use of adminsortable2 library) def batch_number_incrementer(): current_max = RoastManifest.objects.order_by('-batch_number').first() if current_max: return current_max.batch_number + 1 else: return 8000000 batch_number = models.IntegerField(unique=True, default=batch_number_incrementer, ) product = models.ForeignKey(Product, related_name="products", on_delete=models.PROTECT) date_scheduled = models.DateField() roaster_profile = models.ForeignKey(RoasterProfile, on_delete=models.PROTECT) roast_order = models.PositiveSmallIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('roast_order',) This is … -
SSL error in Django MySQL Connection (2026 SSL_CTX_set_tmp_dh failed)
Attempting to connect to RDS MySQL instance through databases dict in settings.py file yields django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed'). Setup (Similar to SSL connection error when connecting to RDS MySQL from Django) Standard Django application MySQL RDS instance with security group allowing connections from all IP addresses MySQL user is setup to allow connections from any host Amazon's pem has been downloaded and is specified in Django settings Connection through cli works, as does connecting in interpreter through PyMySql. I've tried verifying that the path to the ca is absolute, which it is, and making sure that I'm not using python to attempt to build it, as in SSL connection error when connecting to RDS MySQL from Django. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev', 'USER': os.environ['DEV_DATABASE_USERNAME'], 'HOST': os.environ['DEV_DATABASE_HOST'], 'PASSWORD': os.environ['DEV_MYSQL_PASSWORD'], 'OPTIONS': { 'ssl': { 'ca': <PATH TO CA CERT> }, } } } -
django-filter filter on annotated field
class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer def get_queryset(self): return super().get_queryset().annotate( is_active=ExpressionWrapper( Q(start_date__lt=timezone.now()) & Q(end_date__gt=timezone.now()), output_field=BooleanField() ), ) search_fields = [ 'name', 'short_desc', 'desc', ] filterset_fields = [ 'is_active', ] I have this ViewSet that I want to filter on an annotated field, normally you can simply just filter on the annotation in django querysets, however the above combined with this serializer: class EventSerializer(serializers.ModelSerializer): is_active = serializers.SerializerMethodField() @staticmethod def get_is_active(obj): return obj.is_active class Meta: model = Event fields = [ 'timestamp', 'id', 'name', 'short_desc', 'desc', 'start_date', 'end_date', 'is_active', ] I haven't looked deep into the source code but I'd assume it would do a simple qs.filter for the fields in filterset_fields but I'm getting this beautiful error that fails to explain much(at least to me): 'Meta.fields' contains fields that are not defined on this FilterSet: is_active -
Django is not sending me an email when there is an error 500
After deploying my website, I would like to get an email with the errors when there is an error 500. I am able to send normal emails with send_mail. I alsp have DEBUG= False, ADMINS=[('name'),('email')] andSERVER_EMAIL = "domain email", however I and not getting any emails. I believe it is because I created a custom template for handler500 urls.py handler500 = myapp.error_500 views.py def error_500(request): data = {} return render(request,'.../error_500.html', data) How do I send the email with an error? -
Is it possible cache the whole page in Django?
I'm currently working this website. The problem is that the pages takes 3-4 seconds to get the first bye, and I think it's because query to load data in the pages is very slow. In the store page, it basically uses an object of a store to show the store's basic information and uses ForeignKey relation to access the store's images. In addition, it uses ManyToManyField to access the store's similar stores which are a store object as well. For this solved, I used prefetch_related and select_related so minimized many of duplicated queries. But still it shows a low performance. After that I thought, I could improve it with caching, so I did the below. To be honest, what I expected with caching was like super fast loading as it is supposed to store all the processed queries and just show the data from the requested cache. But, to be honest, it still shows 3-4 seconds loading performance. Am I using the cache in a wrong way? settings.py ... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'django_cache', } } ... views.py class StoreDetailView(View): def get(self, request, *args, **kwargs): store_domainKey = self.kwargs['store_domainKey'] cache_store = 'store-{0}'.format(store_domainKey) store = cache.get(cache_store, None) if … -
Add extra value before save serializer
My form sends data to django-rest-framework, but the form contains two fields, and I want to save 5 fields in the database, other fields I calculate on my own (they are not sent by the form). How can I add additional values before saving? so, form send 'user' and 'comment' values, I want add 'article', 'ip_address' before save to DB models.py class Comments(models.Model): article = models.ForeignKey(Articles, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) comment = models.TextField(verbose_name=_('Comment')) submit_date = models.DateTimeField(_('Created'), auto_now_add=True) ip_address = models.CharField(_('IP address'), max_length=50) is_public = models.BooleanField(verbose_name=_('Publish'), default=False) serializers.py class CommentsSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.first_name') class Meta: model = Comments fields = ('user', 'comment') views.py class AddCommentViewSet(viewsets.ModelViewSet): queryset = Comments.objects.all() serializer_class = CommentsSerializer -
Django ORM: filter for tuples of foreign key attributes
I'm writing a matching service that will match you with profiles based on overlapping expertise. E.g. if you are REQUESTING python expertise, it will match you with folks OFFERING python expertise. I'm having trouble determining how to structure that query with the Django ORM. Setup I have models: class Profile(models.Model): pass class Expertise(models.Model): profile = db.ForeignKey('profile', on_delete=models.CASCADE) name = db.CharField(choices=[(1, 'python'), (2, 'javascript'), (3, 'golang')], max_length =255) direction = db.CharField(choices=[('offered', 'offered'), ('requested', 'requested')], max_length = 255) Data I've got data that essentially looks like the following: # setup some fields profile = Profile() profile.save() Expertise(profile=profile, name=1, direction='requested').save() Expertise(profile=profile, name=2, direction='offered').save() Obviously Wrong Attempt Profile.objects.filter( expertise__name__in = [e.name for e in profile.expertise_set()] expertise__direction__in = [e.direction for e in profile.expertise_set()] ) I'm essentially looking for the ability to combine boolean AND and boolean OR in the query. In a different technology, I'd... In SQL I'd do something along the lines of: SELECT * FROM app_profiles JOIN app_expertise on app_profiles.id = app_expertise.app_profiles_id WHERE (app_expertise.direction = 'offered' AND app_expertise.name = 1) OR (app_expertise.direction = 'requested' AND app_expertise.name = 2) -
strange data display in select at Django
Already a dead hour I puzzle over a problem with. Why in the first case is SECURITY_WITHOUT displayed, and in the second - display? After all, everything is identical ... In general, in both cases, the translated phrase with django.po should be displayed. But how to achieve this? ... models.py SECURITY_WITHOUT = 'Without display' CONFIRMATION_WITHOUT = 'display' #this displayed SECURITY_CHOICES = ( (SECURITY_WITHOUT, _('Without display')) #SECURITY_WITHOUT displayed ) CONFIRMATION_CHOICES = ( (CONFIRMATION_WITHOUT, _('Display')), ) income_proof = models.CharField(_('proof'), max_length=255, choices=CONFIRMATION_CHOICES, default=CONFIRMATION_WITHOUT) security = models.CharField(_('security'), max_length=255, choices=SECURITY_CHOICES, default=SECURITY_WITHOUT) forms.py security = forms.ModelChoiceField(queryset=CreditPayment.objects.values_list('security', flat=True).distinct(), widget=forms.Select(attrs={'class': "selectpicker form-control", 'title':_("Security")})) income_proof = forms.ModelChoiceField(queryset=CreditPayment.objects.values_list('income_proof', flat=True).distinct(), widget=forms.Select(attrs={'class': 'selectpicker form-control', 'title':_("Income proof")})) template {{ big_form.security }} {{ big_form.income_proof }} html <div class="form-group"> <div class="dropdown bootstrap-select form-control show"> <select class="selectpicker form-control" id="id_big-security" name="big-security" tabindex="-98"> <option value="" selected="selected">---------</option> <option value="SECURITY_WITHOUT">SECURITY_WITHOUT</option> </select> <button type="button" class="btn dropdown-toggle bs-placeholder btn-light" data-toggle="dropdown" role="button" data-id="id_big-security" title="---------" aria-expanded="true"><div class="filter-option"><div class="filter-option-inner"><div class="filter-option-inner-inner">---------</div></div> </div></button> <div class="dropdown-menu show" role="combobox" style="max-height: 394px; overflow: hidden; min-height: 0px; position: absolute; transform: translate3d(0px, 61px, 0px); top: 0px; left: 0px; will-change: transform;" x-placement="bottom-start"><div class="inner show" role="listbox" aria-expanded="true" tabindex="-1" style="max-height: 376px; overflow-y: auto; min-height: 0px;"><ul class="dropdown-menu inner show"><li class="selected active"><a role="option" class="dropdown-item selected active" aria-disabled="false" tabindex="0" aria-selected="true"><span class=" bs-ok-default check-mark"></span><span class="text">---------</span></a></li><li><a role="option" class="dropdown-item" aria-disabled="false" tabindex="0" …