Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get selected value in dropdown list, then pass it to views.py
I'm working on an upload file feature with dropdown and dropzone. But, whenever I submit the uploaded file with selected option, it always says that the selected option is None. I found it None after I printed the nama_bimbingan in views.py. Here it is my code. url.py .... url(r'bimbingan/add/upload', mengelola_bimbingan.upload_data_bimbingan, name='add-bimbingan-excel'), url(r'bimbingan/download-template/', mengelola_bimbingan.bimbingan_template, name='bimbingan-template'), .... forms.py class UploadBimbinganForm(forms.Form): ... ... dropdown_choices = tuple(zip(all_pembimbing, all_pembimbing)) nama_pembimbing = forms.ChoiceField(choices = dropdown_choices) upload_bimbingan.html <form method="POST" action="{% url 'app:add-bimbingan-excel' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="py-3"> <label for="id_nama_pembimbing"> Nama Pembimbing Akademik: </label> <select class="form-control mb-2" id="id_nama_pembimbing" name="nama_pembimbing" required> <option value = "" selected="selected">---------</option> <option value = {{form.nama_pembimbing}}></option> </select> </div> <div id="myDropzone" class="dropzone" drop-zone> <h6 class="dz-message"> Drop file here or click to upload</h6> </div> <div class="py-3"> <a href="{% url 'app:bimbingan-template' %}">Download Template</a><br> <div class="row justify-content-between py-3"> <div class="col-md-5 mb-1"> <a href="{% url 'app:read-all-bimbingan' %}" class="btn btn-blue-outlined">Batal</a </div> <div class="col-md-5"> <input type="submit" value="Simpan" class="btn btn-block btn-blue"> </div> </div> </div> </form> views.py @login_required(redirect_field_name='index') @user_passes_test(only_admin_access) def upload_data_bimbingan(request): form = UploadBimbinganForm(request.POST or None) if request.method == "POST" and 'file' in request.FILES: nama_pembimbing = request.POST.get('nama_pembimbing') excel_file = request.FILES["file"] data = get_data(excel_file, column_limit=1) bimbingans = data["Bimbingan"] ... ... if(len(duplicate) == 0): space_parsed_query = nama_pembimbing.replace(' ', '%20') cleaned_query = space_parsed_query.replace(',', '%2C') nip_pembimbing … -
ModuleNotFoundError: No module named error when starting Django shell
When running 'python manage.py shell', I'm getting the following message: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Anaconda3\envs\mysite\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "D:\Anaconda3\envs\mysite\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Anaconda3\envs\mysite\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "D:\Anaconda3\envs\mysite\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package I have tryed another solution where I had to use ./manage.py shell --plain, but this didn't work. Also tryed a solution that stated the ipython version wasn't correct, but that solution didn't solve anything for me either. -
Squash migrations in Django
I'm quite new to Django, I have some 30 migration files and squashed last 6 migration files into 1 migration file. Now that I have squashed migrations into one file, can I delete the old 6 migration files? -
django form is not valid but validation not working
When I submit form it doesn't show any validation error and form is not valid views.py def institute(request): context = {} if request.POST and request.FILES: form = InstituteForm(request.POST, request.FILES) context['form'] = form if form.is_valid(): form.save() messages.add_message( request, messages.SUCCESS, "Successfully Added Institute Information") return redirect('accounts:profile') else: context['form'] = InstituteForm() return render(request, 'institute.html',context) according to forms.py it should return email or phone validation error but there is no errors in template and form data is saving in database forms.py class InstituteForm(forms.ModelForm): class Meta: model = Institute fields = '__all__' exclude = ('create', 'update', 'admin') def clean_phone(self): phone = self.cleaned_data['phone'] emp = Employee.objects.filter(phone=phone).count() ins = Institute.objects.filter(phone=phone).count() if emp > 0 or ins: raise ValidationError('This Phone Number is already used, try new one') return phone def clean_email(self): email = self.cleaned_data.get('email') emp = Employee.objects.filter(email=email).count() ins = Institute.objects.filter(email=email).count() if ins > 0 or emp: raise ValidationError('This email is already used, try new one') return email -
django NOT NULL constraint failed: " ............... "
I'm new in django and I want to ask you the following question. I have two models: monthly income, that rappresents my single item monthly income and total montly income, that rappresent the summ of all items monthly income. My models.py is the following: from django.db import models from djmoney.models.fields import MoneyField class Vendite(models.Model): ricavi_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_dalle_vendite_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_dalle_vendite_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) class Totale_Vendite(models.Model): ricavi_tot_dalle_vendite = models.CharField(max_length=100, editable=True) ricavi_01 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) ricavi_02 = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) My views is the following: def ricavi_dalle_vendite(request): items = Vendite.objects.all() if request.method == 'POST': form = VenditeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = VenditeModelForm() data_jan = list(Vendite.objects.aggregate(Sum('ricavi_dalle_vendite_01')).values())[0] data_feb = list(Vendite.objects.aggregate(Sum('ricavi_dalle_vendite_02')).values())[0] jan = data_jan feb = data_feb total_income = Totale_Vendite(ricavi_01=jan, ricavi_02=feb, id=1) total_income = Totale_Vendite(ricavi_01=jan, ricavi_02=feb, id=1) total_income.save() context= { "form": form, 'items': items, } return render(request, "app/vendite.html", context) The code works well, but when I'm going to delete the first items inserted in the models "Vendite" django give me the error NOT NULL constraint failed: app_totale_vendite.ricavi_01. I think that the error is about my constraints "id=1" in my views, but I need to have in Totale_vendite model only a row, that update itself … -
How do I store multiple values in a single variable or list in django views.py?
Here is my views.py @login_required def appsc(request): allapplied = Applied_Scholarships.objects.filter(user_id = request.user.id) for applied in allapplied.iterator(): print('hi') sch_id = applied.scholarship_id queryset = ScholarshipDetails.objects.filter(id = sch_id) print(queryset) context = {"object_list":queryset} return render(request,'applied-scholarships.html',context) Here, I need to check the applied scholarships of a student. So for that, I have filtered the entries from the Applied_Scholarship table. Now from that, I took scholarship_id and filtered the entries in ScholarshipDetails table so that I get the name and other details of the scholarship. Now how do I prevent object_list to get overridden? This code gives me value of only 1 scholarship instead of 2. Here is my template: <table class="table mb-0"> <tr> <th>Scholarship name</th> <th>End Date</th> <th>Status</th> <th></th> <th></th> </tr> {% for instance in object_list %} <tr> <td>{{instance.name}}</td> <td>{{instance.end_date}}</td> <td>{{applied.status}}</td> <td><a href = "government/home">{{schdets.link}}</a></td> </tr> {% endfor %} </table> Do I need to use list? If yes, then how? -
Django TruncDate gives null
I'm using Django 2.2 I'm filtering records using Django query like from datetime import datetime from django.db.models.functions import TruncDate start_date = datetime.strptime('2020-02-01', '%Y-%m-%d').date() end_date = datetime.strptime('2020-03-31', '%Y-%m-%d').date() lead_list = LeadList.objects.all() # Filter query query = LeadListEntry.objects.filter( lead_list__in=lead_list ) # Filter by start date query = query.filter( created__gte=start_date ) # Filter by end date query = query.filter( created__lte=end_date ) # Annotate date query = query.annotate( created_date=TruncDate('created') ).order_by( 'created_date' ).values('created_date').annotate( **{'total': Count('created')} ) The SQL query generated is SELECT DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC')) AS `created_date`, COUNT(`lead_generation_leadlistentry`.`created`) AS `total` FROM `lead_generation_leadlistentry` WHERE ( `lead_generation_leadlistentry`.`lead_list_id` IN ( SELECT U0.`id` FROM `lead_generation_leadlist` U0 WHERE U0.`deleted` IS NULL ) AND `lead_generation_leadlistentry`.`created` >= '2020-02-01 00:00:00' AND `lead_generation_leadlistentry`.`created` <= '2020-03-31 00:00:00' ) GROUP BY DATE(CONVERT_TZ(`lead_generation_leadlistentry`.`created`, 'UTC', 'UTC')) ORDER BY `created_date` ASC This is behaving different on local and staging server Local Development server +--------------+-------+ | created_date | total | | ------------ | ----- | | 2020-02-25 | 15 | | 2020-02-27 | 10 | +--------------+-------+ Staging server +--------------+-------+ | created_date | total | | ------------ | ----- | | null | 15 | +--------------+-------+ The date column is null NOTE: Django has timezone enabled by USE_TZ=True -
Django: How to make model attribute dependent on foreign key present in that model
I have two models in Django : State and City class State(models.Model): #regex = re.compile(r'^[a-zA-Z][a-zA-Z ]+[a-zA-Z]$', re.IGNORECASE) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100, unique=True) class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100, unique=True) postalcode = models.IntegerField(unique=True) In city model I have attribute state which is foreign key from State model. In city model I want to make attribute name dependent on state attribute, as one state will have one city with same name but one city name can be in many states. Like City Udaipur is in both Rajasthan and UttarPradesh in India, but Rajasthan will have single city as Udaipur. -
how to implement function the same as make_password, check_password without Django
I have used Django and handled password with make_password and check_password. however, I get to change a framework to another (other than Django). With another framework, I need to verify passwords that are created by Django because I should use the same database with the data. How to encrypt(make_password) and verify(check_password) the same as Django did without Django? I think it is possible to implement the function like Django's one if I know the internal logic. Password's format stored in database is like that 'pbkdf2_sha256$100000$Dl6Atsc1xX0A$0QFvZLpKdcvcmCNixVCdEA5gJ67yef/gkgaCKTYzoo4=' -
Django duplicate migrations in apps
Django keeps making duplicate migrations in for my application. I've ran makemigrations and migrate before I changed my model. After the changes I ran makemigrations again to make migrations for the updated model, I got the following error: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0001_initial 3 in sessions; 0002_remove_content_type_name 3, 0002_remove_content_type_name, 0001_initial 3 in contenttypes; 0002_alter_permission_name_max_length 3, 0010_alter_group_name_max_length 3, 0007_alter_validators_add_error_messages 3, 0006_require_contenttypes_0002 3, 0005_alter_user_last_login_null 3, 0001_initial 3, 0008_alter_user_username_max_length 3, 0009_alter_user_last_name_max_length 3, 0011_update_proxy_permissions, 0011_update_proxy_permissions 3, 0004_alter_user_username_opts 3, 0003_alter_user_email_max_length 3 in auth; 0003_logentry_add_action_flag_choices 3, 0002_logentry_remove_auto_add 3, 0003_logentry_add_action_flag_choices, 0001_initial 3 in admin). To fix them run 'python manage.py makemigrations --merge' Running makemigrations --merge doesn't work: ValueError: Could not find common ancestor of {'0002_remove_content_type_name', '0002_remove_content_type_name 3', '0001_initial 3'} There are many duplicate migrations in apps that I haven't touched (auth, admin, etc.): admin [ ] 0001_initial 3 [X] 0001_initial [ ] 0002_logentry_remove_auto_add 3 [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices [ ] 0003_logentry_add_action_flag_choices 3 auth [ ] 0001_initial 3 [X] 0001_initial [ ] 0002_alter_permission_name_max_length 3 [X] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length 3 [X] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts 3 [X] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null 3 [X] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 3 [X] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages 3 [X] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length 3 … -
How can I go to specific url from template in django?
I have bunch of urls in urls.py , and In template I have defined like below : <li><a href="{% url 'vieweinvoices' %}">Billing</a></li> <li><a href="{% url 'proformainvoice' %}">Proforma Invoice</a></li> <li><a href="{% url 'viewequotations' %}">Quotation</a></li> But the problem is if I click on one line say viewinvoices, and after that I click on proformainvoice, it redirects to localhost:8000/vieweinvoices/proformainvoice.html but it should go to localhost:8000/proformainvoice.html how can I do that? -
return data from json file if another one is not exist
i'm trying to return data to django model, from Overpass API json data after downloaded "elements": [ { "type": "node", "id": 662934404, "lat": 35.572157, "lon": 45.3898839, "tags": { "addr:postcode": "46001", "name": "City Center", "name:en": "City Center Mall", "name:ku": "City Center Mall", "shop": "mall", "website": "http://www.citycentersul.com" } }, { "type": "node", "id": 2413990402, "lat": 35.5014386, "lon": 45.4457576, "tags": { "addr:city": "sulaymaniyah", "designation": "ASSAN", "name": "ASSAN STEEL CO.", "opening_hours": "3 min", "shop": "doityourself", "source": "ASSAN Steel Company General Trading Co, Ltd" }, { "type": "node", "id": 2414374708, "lat": 35.506121, "lon": 45.4417229, "tags": { "addr:city": "sulaymaniyah", "name:ku": "ASSAN Steel Company General Trading Co, Ltd", "shop": "doityourself", } }, but some of the data dosent have both of them together name , name:ku ,name:en so what should i do if name is none then return name:ku , if its exists then name:en i've tried this but doesnt work with open('data.json') as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType = obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name') if not name: name = tags.get('name:en') elif not name: name = tags.get('name:ku') elif not name: name = tags.get('name:ar') else: name = tags.get('shop','no-name') is there something else i've missed ? thanks for … -
Django - First call to reverse is slow
I have to call several times Django reverse method in order to return several urls to the client. The first reverse call takes between 1 and 2 seconds while all the following, even with different routes are very fast. What exactly is happening with the first one ? Is there a way to speed this up ? -
How to translate dates and date times in django rest framework?
I want to translate dates and times to current language. I don't know how to combine current language with translation with dates. So what is the best way to translate dates in django rest framework? -
Django's authenticate method returns 'None' for a an already saved User
Settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) Tests.py which has the code triggering the error class LoginTest(TestCase): def test_can_redirect_to_user_page_if_authentificated(self): test_user = User(username='foo', password='bar', first_name='Testy', last_name='McTestingTon', email='testy@email.com', is_active=True) test_user.save() current_user = authenticate(username=test_user.username, password=test_user.password) print(current_user) response = self.client.post('/login', data = {'username' : current_user.username, 'password' : current.password}) self.assertEqual(response.url, '/users/Testy') current_user is always returned as None I've tried numerous advices from other posts here on SO but authenticate still returns None for a user whose is_active I've explicitly set to True and with the ModelBackend added to my settings.py. -
Django Form Tools not Working with Dynamic Formsets
Anyone who has worked with integrating Django formtools with Dynamic Formsets? I have 7 forms in my form wizard and in one of the forms I am trying to add/remove as many questions as I can dynamically. However, when I submit the wizard, only one of the questions (last text input) gets saved regardless of how many I have added. Below is my wizard view class JobWizard(SessionWizardView): form_list=[JobForm7FormSet,JobForm1,JobForm2,JobForm3, JobForm4,JobForm5,JobForm6 ] file_storage= FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'jobs')) template_name="jobs/jobforms.html" def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, form_dict, **kwargs): form_dict = self.get_all_cleaned_data() categories = form_dict.pop('categories') sub_categories = form_dict.pop('sub_categories') # job_question=form_dict.pop('formset-0', None) # print(job_question1) print("_________________________") job_question = form_dict.pop('job_question') job=Job.objects.create(**form_dict) job.categories=categories job.job_question=job_question print("_________________________") for sub_category in sub_categories: job.sub_categories.add(sub_category) # for question in job_question: # job.job_question.append(question) job.save() return redirect('job_list') And my forms.py is as below. I am using model forms and creating a formset from the model form. class JobForm7(forms.ModelForm): class Meta: model = Job fields = ['job_question'] JobForm7FormSet = modelformset_factory(Job,extra=1,max_num=10, fields=('job_question',), form=JobForm7) The rendering in my template as below: {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype="multipart/form-data" id="job-question">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form |crispy … -
get foreign key values drf django
every thing working just want to modify the views: models.py: class TypeOfCity(models.Model): key = models.CharField(verbose_name=_("key"), max_length=15, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=15) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) def __str__(self): return self.key class CityTier(models.Model): key = models.CharField(verbose_name=_("key"), max_length=10, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=10) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) def __str__(self): return self.key class City(BaseModel): name = models.CharField(_("City Name"), max_length=80, null=False, blank=False) state_name = models.ForeignKey(State, to_field="uid", on_delete=models.DO_NOTHING, max_length=55, null=False, blank=False) city_type = models.ForeignKey(TypeOfCity, to_field="key", on_delete=models.DO_NOTHING, max_length=15, null=False, blank=False) city_tier = models.ForeignKey(CityTier, to_field="key", on_delete=models.DO_NOTHING, max_length=10, null=False, blank=False) status = models.SmallIntegerField(_("Status: 1 for Active; 0:Inactive"), default=1) serializers.py: class TypeOfChoiceSerializer(serializers.ModelSerializer): class Meta: model = TypeOfChoice fields = ('value',) class CityTierSerializer(serializers.ModelSerializer): class Meta: model = CityTier fields = ('value',) class CitySerializer(serializers.ModelSerializer): city_type = TypeOfChoiceSerializer(read_only=True) city_tier = CityTierSerializer(read_only=True) def get_typeofchoices(self,obj): return TypeOfChoiceSerializer(TypeOfChoice.objects.all()).data def get_city_tiers(self,obj): return CityTierSerializer(CityTier.objects.all()).data class Meta: model = City fields = '__all__' views.py: @api_view(['POST']) def cityList(request): queryset = City.objects.all() serializer_obj = CitySerializer(queryset, many=True) return HttpResponse(serializer_obj.data) output: [{ "id": 1, "city_type": { "value": "Normal City" }, "city_tier": { "value": "Tier I" }, "name": "test", "status": 1, }] i'm expecting output like this: [{ "id": 1, "city_type": "Normal City", "city_tier": "Tier I", "name": "test", "status": 1, }] or just add … -
What Is The Best Way To Store User Details After Login?
I Try To Develop School Management System , Each Teacher Will Be Having Its Own Role And Department And Class Her/his Belong . I Finish To Build Authentication (login And Logout ) . Using Django Restframework And Jwt The Problem I Face Is When Teacher After Login In I Want To Store His/her Profile Details Through Multiple Page So When Teacher Doing Certain Action In A Certain Model It Will Be Easy To Know A Certain Action Has Been Done By This Teacher . I Use Django And Angular 8 As Front End Thanks. -
How to query in django view to add two numbers?
I want to query in view.py such that I can display the sum of two integers input by the client. I can't seem to find a way on how to add numbers entered by client and display on server. Any suggestion on how to approach this problem will be real helpful. If any query related to question please ask, I will try to make it clearer. Models.py:: from django.db import models from django.conf import settings class Addition(models.Model): name = models.CharField(max_length=10) int1 = models.IntegerField(default=True) int2 = models.IntegerField(default = True) Form.py:: from django import forms from . models import Addition class AdditionForm(forms.ModelForm): class Meta: model = Addition fields = [ 'name', 'int1', 'int2', ] Serializer.py:: from rest_framework import serializers from . models import Addition, Subtraction class AdditionSerializer(serializers.ModelSerializer): class Meta: model = Addition fields = '__all__' View.py:: from django.shortcuts import get_list_or_404,render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . forms import AdditionForm from . models import Addition from . serializers import AdditionSerializer from .forms import SubtractionForm from . models import Subtraction from . serializers import SubtractionSerializer class AdditionList(APIView): def get(self,request): additions = Addition.objects.all() serializer = AdditionSerializer(additions,many = True) return Response(serializer.data) class AdditionListForm(APIView): def post(request): form = AdditionForm(request.POST … -
how to implement password reset in Django without using Django auth and forms
I am new to python and i want to implement reset password using emails. is it possible to make it without using Django auth and Django forms? -
CRUD operations in django rest framework having many-to-many fields relationship
I am using django rest framework for creating REST APIs. My model contains one many-to-many field and I am facing some complications in serializing it. models.py class CustomerMaster(models.Model): customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase. first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase. last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase. gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase. dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase. address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'customer_master' def __str__(self): return self.first_name + self.last_name class Segment(models.Model): name = models.CharField(max_length=100) folder = models.CharField(max_length=100) selection = JSONField() createdAt = models.DateTimeField(null=True) updatedAt = models.DateTimeField(null=True) createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) contact = models.ManyToManyField(CustomerMaster) def __str__(self): return self.name Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'email', 'first_name', 'last_name',) class CustomerEmailSerializer(serializers.ModelSerializer): class Meta: model = CustomerMaster fields = ('email', ) class SegmentSerializer(serializers.ModelSerializer): contact = CustomerEmailSerializer(many=True) createdBy = UserSerializer(required=False) class Meta: model = Segment fields = ('name', 'folder', 'selection', 'createdAt', 'updatedAt', 'createdBy', 'contact') … -
How can I add a prefix to ALL my urls in django
I want to add a prefix to all my URLs in Django python (3.0.3) so all my path that I defined in urls.py will start with "api/". The prefix may be changed in the future so I want it to be dynamic as possible -
Accessing other fields in ModelForm
I've got the following model. class FAQ(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) question = models.CharField(max_length=100, null=True, blank=False) answer = models.TextField(max_length=500, null=True, blank=False) def __str__(self): return self.user.username I've also got the following ModelForm class FAQForm (forms.ModelForm): class Meta: exclude = ('user',) model = FAQ def __init__(self, *args, **kwargs): super(FAQForm, self).__init__(*args, **kwargs) Within my model form, how can I access the the value within the user field of the FAQ model? I'd like to be able to access it under def init(self, *args, **kwargs): or super(). Thanks so much! -
django w/ uwsgi Fatal Python error: initfsencoding: Unable to get the locale encoding
I am trying to do a uwsgi installation and I get the following error Fatal Python error: initfsencoding: Unable to get the locale encoding in my logs. in my .ini I set the pythonpath $ cat /etc/uwsgi/sites/exchange.ini [uwsgi] project = exchange uid = kermit base = /home/%(uid) chdir = %(base)/www/src/%(project) home = %(base)/Env/ module = %(project).wsgi:application pythonpath = /home/kermit/www/src/exchange master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true but I can't tell if it is actually loaded echo $PYTHONPATH comes up empty, even when attempting from user environment in my .bashrc I have fi export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export WORKON_HOME=~/Env #export PYTHONPATH=~/www/src/exchange source /usr/share/virtualenvwrapper/virtualenvwrapper.sh directory structure: (secret) kermit@tuna:~ $ ls Env exchange pgp uwsgi-ini www (secret) kermit@tuna:~ $ ls Env/ get_env_details postactivate postmkproject postrmvirtualenv predeactivate premkvirtualenv secret initialize postdeactivate postmkvirtualenv preactivate premkproject prermvirtualenv (secret) kermit@tuna:~ $ ls www/ src treefrog (secret) kermit@tuna:~ $ ls www/src exchange $ cat www/src/exchange/exchange/settings.py """ Django settings for exchange project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Django: date format management and unique_together -> 'date format "20/03/2020" is invalid. Correct format is "yyy-mm-dd"
I develop a Django project with internationalization English/French dates have to be displayed with the dd/mm/yyyy format when user webbrowser is FR and yyyy-mm-dd when user webbrowser is EN to do that, I use JS that test webbrowser user favorite language and display format accordingly That works fine until I change my model to add unique_together constraint with this date Now, I got the error when webbrowser is in french and I try to register date (asp_ent_dat) 'date format "20/03/2020" is invalid. Correct format is "yyy-mm-dd". models.py: class Entree(models.Model): asp_ent_cle = models.AutoField(primary_key=True) asp_ent_loc = models.CharField("Site concerned by the operation", max_length=10, null=True, blank=True) med_num = models.CharField("Trial batch number", max_length=3, null=True, blank=True,) asp_ent_dat = models.DateField("Entry date", null=True, blank=True) asp_ent_pro_pay = models.CharField("Country of treatment origin in case of entry", max_length=10, null=True, blank=True) asp_ent_pro_sit = models.CharField("Processing source site in case of entry", max_length=10, null=True, blank=True) opr_nom = models.CharField("Input operator", max_length=10, null=True, blank=True) opr_dat = models.DateField("Entry date", null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'pha_asp_ent' verbose_name_plural = 'Entries' ordering = ['asp_ent_cle'] unique_together = ['asp_ent_loc','med_num','asp_ent_dat'] JS: $(function(){ if(window.navigator.language == 'fr-FR' | window.navigator.language == 'fr'){ $("#id_asp_ent_dat").datepicker( { dateFormat: 'dd/mm/yy', } ); } else { $("#id_asp_ent_dat").datepicker( { dateFormat: 'yy-mm-dd', } ); });