Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I use docker in order to be able to run ChomeDriver on Azure Web App Services in Django Server?
Recently I have started a Django server on Azure Web App Service, now I want to add a usage of "ChromoDriver" for web scraping, I have noticed that for that I need to install some additional Linux packages (not python) on the machine. the problem is that it gets erased on every deployment, does it mean that I should switch to Docker ? -
Unable to connect aws RDS to django local
I am trying to connect my local django application to amazon RDS (tried with both MySQL and PostgreSQL) but I am not able to connect as it shows the following errors, Currenty seeking answer for PostgreSQL: In my Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database_name', 'USERNAME': 'my_username', 'PASSWORD': 'my_password', 'HOST': 'database-abc.xxx.us-region-yyy.rds.amazonaws.com', 'PORT': '5432', } } In AWS database configuration: Error: Is the server running on host "database-abc.xxx.us-region-yyy.rds.amazonaws.com" (69.420.00.121) and accepting TCP/IP connections on port 5432? I reffered to all the available data but still am unable to resolve this issue! Thanks in advance! -
Saving User details in UserDetail Table using One-To-One Relation Django Rest API
I am new to django. I am trying to save User details in another table using One-To-One relation by following Django document but is giving me an error Models.py class UserDetails(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) phone=models.CharField(max_length=10) address=models.CharField(max_length=200,default="") created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) objects=models.Manager() def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserDetails.objects.create(user=instance,phone="",address="") receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userdetails.save() Serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetails fields= ['phone','address'] class CreateUserSerializer(serializers.ModelSerializer): user=UserDetailsSerializer() class Meta: model =User fields=['id','url','username','email','password','user'] def create(self, validated_data): user_data=validated_data.pop('user') user=User.objects.create(**validated_data) UserDetails.objects.create(user=user,**user_data) return user When i write above in serializer.py user=UserDetailsSerializer(read_only=True) else give me following error Got AttributeError when attempting to get a value for field user on serializer CreateUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. I found one way to make it work but I have to define every field manually but I want the above serializer to work Working Serializer.py class CreateUserSerializer(serializers.HyperlinkedModelSerializer): last_login=serializers.ReadOnlyField() date_joined=serializers.ReadOnlyField() phone=serializers.CharField(source='userdetails.phone') address=serializers.CharField(source='userdetails.address') updated=serializers.ReadOnlyField(source='userdetails.updated') # password=serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields=['id','first_name','last_name','username','password','phone','address','url','email','is_superuser','is_staff','last_login','date_joined','updated'] extra_kwargs={ 'password':{'write_only':True}, } def create(self, validated_data): userdetails_data=validated_data.pop('userdetails') user=User.objects.create_user(**validated_data) user.userdetails.phone=userdetails_data.get('phone') user.userdetails.address=userdetails_data.get('address') user.save() return user -
How to write reverse function of django mptt data migration
I am writing a data migration for an old table, In this migration, I want to rebuild the tree so that I can persevere the old parent-child relationship. Here is how I am doing this: # Generated by Django 3.0.6 on 2021-07-14 13:03 from django.db import migrations, transaction from mptt import register, managers def rebuild_tree(apps, schema_editor): Category = apps.get_model('core', 'Category') manager = managers.TreeManager() manager.model = Category register(Category) manager.contribute_to_class(Category, 'objects') with transaction.atomic(): manager.rebuild() class Migration(migrations.Migration): dependencies = [ ('core', '0269_auto_20210714_1303'), ] operations = [ migrations.RunPython(rebuild_tree) ] But I am confused about how to write it reverse function? What exactly to do in it? -
Django 'ascii' codec can't encode characters despite encoding in UTF-8? What am I doing wrong?
I'm still in the process of learning Django. I have a bit of a problem with encoding a cyrillic strings. I have a text input. I append it's value using JS to the URL and then get that value in my view (I know I should probably use a form for that, but that's not the issue). So here's my code (it's not complete, but it shows the main idea I think). JS/HTML var notes = document.getElementById("notes").value; ... window.location.href = 'http://my-site/example?notes='+notes <input type="text" class="notes" name="notes" id="notes"> Django/Python notes= request.GET.get('notes', 0) try: notes = notes.encode('UTF-8') except: pass ... sql = 'INSERT INTO table(notes) VALUES(%s)' % str(notes) The issue is, whenever I type a string in cyrillic I get this error message: 'ascii' codec can't encode characters at position... Also I know that I probably shouldn't pass strings like that to the query, but it's a personal project so... that would do for now. I've been stuck there for a while now. Any suggestions as to what's causing this would be appreciated. -
trying to iterate through 2 lists using destructuring
I am trying to iterate through 2 lists using destructuring .. however, I am getting this error view job_skill_ = request.POST.getlist('job_skill_name[]') job_skill_level = request.POST.getlist('job_skill_level[]') job_pst = JobPost(creater=request.user, title=job_title, job_type=job_type, job_loc=job_loc, cmpny_name=compny, job_description=job_descrip, salary=salary) # job_pst.save() print(job_skill_) print(job_skill_level) for skill_, level in zip(job_skill_, job_skill_level): skil_set = Skillset.objects.get(skill_name=skill_) job_skill_set = Job_Skillset( skill=skil_set, job_post=job_pst, skill_level=level) job_skill_set.save() 'str' object is not callable print(job_skill_level) **for skill_, level in zip(job_skill_, job_skill_level): …** > <-- error is here skil_set = Skillset.objects.get(skill_name=skill_) job_skill_set = Job_Skillset( -
Calculating Percentiles using Django Aggregation
I maintain a Django service that allows online community moderators to review/approve/reject user posts. Right now we measure the average "time to approval" but we need to start measuring the 90th percentile "time to approval" instead. So where we used to say "on average content gets approved in 3.3 hours", we might now say something like "90% of content is approved in 4.2 hours or less". # Models.py class Moderation(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) message_id = models.TextField(blank=True, null=True) class ModerationAction(models.Model): moderation = models.ForeignKey(Moderation) action = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) # stats.py average_time_to_approve_7days = ModerationAction.objects.filter( action__in=moderation_actions, created_at__gte=timezone.now() - timedelta(days=7) ).annotate( time_to_approve=F('created_at') - F('moderation__created_at') ).values( 'action', 'time_to_approve' ).aggregate( Avg('time_to_approve') )['time_to_approve__avg'] # This returns a value like datetime.timedelta(0, 4008, 798824) My goal: I'm seeking a way to get the 90th percentile time rather than the average time. -
django custom action name change according to model name
I have created a custom admin action. I am using that action in more than one listing page. In my admin.py file def custom_action(request, modelAdmin, queryset): #do something here return response custom_action.short_description = 'My custom action for X' class MyXAdmin(admin.ModelAdmin): actions = [custom_action] class MyYAdmin(admin.ModelAdmin): actions = [custom_action] In both of my X and Y listing page it appears "My custom action for x". Is there any way to change the "X" => "Y" for Y listing page. OR How can I achieve to rename the custom_action name for individual listing page in djagno without writing custom method for each model. -
Resize image before submit form
I am trying to resize two images before sending them by ajax using javascript in case the size is too big. The formdata is more than 20 fields. Attached is part of the code. .on('core.form.valid', function (event) { var parameters = new FormData(document.getElementById("formulario")); // The fields are named 'DNI_img' and 'ficha_img'. $.ajax({ url: window.location.pathname, type: 'POST', data: parameters, dataType: 'json', processData: false, contentType: false, }).done(function (data) { // console.log(data); if (!data.hasOwnProperty('error')) { Swal.fire({ icon: 'success', title: '¡Tus datos han sido recibidos!', text: 'Pronto nos comunicaremos contigo.', confirmButtonText: '<a href="#">Ir a inicio</a>', }) return false; } message_error(data.error) }).fail(function (data) { alert("error"); }).always(function (data) { // alert("complete") }); }); Thanks in advance. -
Is it possible to use FastAPI as an alternative to Django Rest Framework with Django?
Hey guys I came to know about FastAPI and its benefits and would like to try use it with my Django project as an alternative to DRF. Is it possible to do that? Can anyone help me with an answer and also some leads if possible? Thanks -
Manage category and subcategory in django in admin panel
I want to display only related sub-categories when selecting a parent category in Django admin. How should I structure the model to achieve this? Or is there any packages available? Code (models.py) class Category(models.Model): name = models.CharField(max_length=200 , null=True) no_of_products = models.IntegerField(blank=True , null =True) image = models.ImageField(null=True , blank = True) class SubCategory(models.Model): main_category = models.ForeignKey('Category' , on_delete= models.SET_NULL , null = True) name = models.CharField(max_length=200 , null=True) no_of_products = models.IntegerField(blank=True , null =True) image = models.ImageField(null=True , blank = True) -
Multiple Models for SearchFilter - Django
Using Django 3.2 with Restframework. Iam trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. I found a blog on how to use multiple Models together? I tried for following from that: views.py class GlobalSearchList(generics.ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): query = self.request.query_params.get('query', None) users = MasterUser.objects.filter(Q(firstname__icontains=query) | Q(lastname__icontains=query) | Q(email__icontains=query) | Q(category__icontains=query)) webinar = MasterWebinar.objects.filter(Q(host__icontains=query) | Q(title__icontains=query)) resource = MasterResource.objects.filter(Q(route_name__icontains=query)) section = ResourceSection.objects.filter(Q(resource_name__icontains=query)) item = SectionItem.objects.filter(Q(item_title__icontains=query)) all_results = list(chain(users,webinar, resource,section,item)) return all_results serializers.py class GlobalSearchSerializer(serializers.ModelSerializer): class Meta: model = MasterUser fields = "__all__" def to_native(self, obj): if isinstance(obj, MasterIndividualMembers): serializer = MasterIndividualMembersSerializer(obj) elif isinstance(obj, MasterUser): serializer = MasterUserSerializer(obj) elif isinstance(obj, MasterWebinar): serializer = MasterWebinarSerializer(obj) elif isinstance(obj, MasterResource): serializer = MasterResourceSerializer(obj) elif isinstance(obj, ResourceSection): serializer = ResourceSectionSerializer(obj) elif isinstance(obj, SectionItem): serializer = SectionItemSerializer(obj) else: raise Exception("Not found in any instance!") return serializer.data Here I stuck at meta class, since it accepts only 1 model. -
getting no such table error when it actually exists in Django?
my views.py def analysis(request): serializer = QuizIDSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data student = Student.objects.get(user=2) responses = student.response_set.get(quiz_id=validated_data['quiz_id']) quiz = responses.quiz_id questions = quiz.question_set.all().order_by('id') print(questions) return Response(status=status.HTTP_200_OK) here I am getting error as OperationalError at /assessment/analysis/ no such table: assessment_response when i tried to execute line responses = student.response_set.get(quiz_id=validated_data['quiz_id']) my models.py class Quiz(models.Model): name = models.CharField(max_length=31) description = models.CharField(max_length=255, blank=True) classroom = models.ManyToManyField(Classroom, blank=True) instructions = RichTextUploadingField(max_length=10000, blank=True) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) name = models.CharField(max_length=31, null=True, blank=True) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) name = models.CharField(max_length=4) option = RichTextField() state = models.PositiveSmallIntegerField(choices=O_STATE, default=0) class Response(models.Model): student_id = models.ForeignKey(Student,verbose_name="Student ID",null=True,on_delete=models.SET_NULL) quiz_id = models.ForeignKey(Quiz,verbose_name="Quiz ID",null=True,on_delete=models.CASCADE) responses = models.ManyToManyField(Option,verbose_name="Responses") my serializers.py from rest_framework import serializers class QuizIDSerializer(serializers.Serializer): quiz_id = serializers.IntegerField() I didn't understand the reason of the error, i have removed unnecessary details from the model, if you feel anything wrong please comment, i have this response table still it is giving error , please help -
How to get employee id using excel sheet
I have created a system (in Django) where whenever I upload an excel file to the website, it will be loaded into the database. How do I retrieve the EmpID from the DB and show it in HTML ? This is my views.py def upload_file_view(request): form = EmployeeForm(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save() form = EmployeeForm() with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) next(reader) for row in reader: print(row) EmpID = row[1].upper() EmpName = row[2].upper() EmpEmail = row[3].upper() Employee.objects.create( EmpID = EmpID, EmpName = EmpName, EmpEmail = EmpEmail, ) obj.activated = True obj.save() return render(request, "EmpDBUpload/upload.html", {'form':form}) This is my Viewclaim.html <h1> Emp id: {{EmpID}} </h1> This is my views.py for ViewClaim def ViewClaim(request): context = initialize_context(request) user = context['user'] claims = Claims.objects.all() emp_ids = Employee.objects.values('EmpID') context = {'emp_ids': emp_ids} return render(request, 'User/ViewClaim.html', {'date': x, 'user':user, 'claims':claims} ,context=context) -
My CSS for Django website does not work when hosting it using AWS
I have used AWS to host my Django website. It works fine when I run it on my regular OS which is Ubuntu. But when I try to run it on my windows rdp that I set up using AWS, the CSS doesn't work. Can someone please help with this?! -
AttributeError: 'NoneType' object has no attribute 'startswith' error when trying to migrate legacy database in django
trying to migrate a legacy sqlite database (database.sqlite) in django to inspect_db and pull model information from datbase.sqlite. python manage.py makemigrations seems to be okay but when running python manage.py migrate there's an error. AttributeError: 'NoneType' object has no attribute 'startswith' Tried to trackback error but got lost in all the code. Django==3.2.5 python== 3.7.9 Running migrations: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 91, in migrate self.recorder.ensure_schema() File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 68, in ensure_schema editor.create_model(self.Migration) File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 35, in __exit__ self.connection.check_constraints() File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 347, in check_constraints self.ops.quote_name(primary_key_column_name), File "/Users/cp/Documents/dsi/django_project/django_env/lib/python3.7/site-packages/django/db/backends/sqlite3/operations.py", line 171, in quote_name if name.startswith('"') and name.endswith('"'): AttributeError: 'NoneType' object has no attribute 'startswith' Here is settings.py database info(commented out other database for troubleshooting purposes.. commented out db.sqlite3 works fine): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'database.sqlite', } # 'default': … -
NGINX doesn't work when proxy_set_header is set to $host
I've been setting a simple docker-compose for a Django application, in which I have 3 containers: the Django app, a Postgres container, and NGINX. I successfully set up both Django and Postgres and tested connecting directly to their containers, so now the only thing left was to set up NGINX on the docker-compose file. I used the following NGINX default.conf file, from another template repository: upstream django { server app:8000; } server { listen 80; server_name localhost; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://django; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /static/ { autoindex on; alias /static/; } location /media/ { autoindex on; alias /media/; } } And this was my docker-compose file: version: "2" services: nginx: image: nginx:latest container_name: NGINX ports: - "80:80" - "443:443" volumes: - ./test:/djangoapp/test - ./config/nginx:/etc/nginx/conf.d - ./test/static:/static depends_on: - app app: build: . container_name: DJANGO command: bash -c "./wait-for-it.sh db:5432 && python manage.py makemigrations && python manage.py migrate && gunicorn test.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./djangoapp/test:/djangoapp/test - ./test/static:/static expose: - "8000" env_file: - ./config/djangoapp.env db: image: postgres:latest container_name: POSTGRES … -
Djangp Model form does not display when I include it in the Parent template
Long story short , My form.html Only shows submit button rather than all the fields of the model form <div class="form"> <form action="{% url 'name' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> <p style="color: red;">Watch it before it gets removed on The Internet</p> </div> Here is forms.py from django import forms from django.forms.models import ModelForm from .models import Person class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name','email'] when I tried adding html inputs manually on forms.html I was able to make the inputs show on the page , Is something wrong with importing model form like that ?? Also what's weird is that when I click on that submit button since its the only one showing on the page … It takes me to a plain form.html with validation error , since I was submitting empty values Here is how I include it in the Parent template {% include "form.html" %} -
Is there caching property with argument Instead of cache_proerty in django?
I have a serializer like this class PaperEveryoneSerializer(ReadOnlyModelSerializer): author = serializers.SerializerMethodField() address = serializers.SerializerMethodField() def get_author(self, instance): if instance.paper_contractors.filter(profile__user=self.context['request'].user).exists(): return str(instance.author) else: return '' def get_address(self, instance): if instance.paper_contractors.filter(profile__user=self.context['request'].user).exists(): return {"old_address": instance.address.old_address, "old_address_eng": instance.address.old_address_eng} address_with_bun = instance.address.old_address.split("-")[0] hidden_address = address_with_bun[0:address_with_bun.rindex(" ")] old_address_eng = instance.address.old_address_eng hidden_address_eng = old_address_eng[old_address_eng.index(" ")+1:len(old_address_eng)] return {"old_address": hidden_address, "old_address_eng": hidden_address_eng} I am using this code hiding the private info. But this code will evaluate two time for instance.paper_contractors.filter(profile__user=self.context['request'].user).exists() Is there way to prevent evaluating two times for queryset? I am trying to do that with cached property. But it doesn't allow to send arguments. -
Serve Django views with React?
I am making a web application with react as frontend and django-rest-framework as backend. For django, I am following a tutorial. https://www.techwithtim.net/tutorials/django/user-registration/ - here they have made a registration form with django that has proper validation. Is there a way to do the same with React? Essentially, is there a way to show Django templates and views with React? If not, should I just link to the specific Django page hosted on the Django server? Thanks! -
change the Django Rest Framework's default url to a custom
changing default url (http://127.0.0.1:8000/v1) to a custom (https://api.abc.com/v1) Moving the app to another server with custom url is giving me problems in apache What we write in apache configuration to remove port number in ec2 instance for django rest framework -
How to edit and delete records in modelformset in Django
everyone. I can’t solve my problem now. I would like to edit and delete old records and add new records in Update-function. I can create new records in Create-function, though I can’t edit and delete old records in Update-function. I can only add new records in Update in Other-model, though I can’t edit and delete. Whereas, I can’t add new records and edit and delete old records in Update in Spot-model. Then when I try to add new records in Spot-model, this error happens. I don’t understand why the error happens. NOT NULL constraint failed: make_trip_spot.spot_cost I think the difference between Spot-views and Other-views is small. I use modelformset though I don’t understand how to use this formset. Here is my code. models.py class Other(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name='extra') extra_name = models.CharField(max_length=50) extra_cost = models.IntegerField(validators=[MinValueValidator(0, 'Please input 0 or more')]) class Spot(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, related_name='spot') spot_name = models.CharField(null=False, blank=False, max_length=50) spot_time = models.DateTimeField(blank=False, null=False) spot_cost = models.IntegerField(null=False, blank=False, validators=[MinValueValidator(0, 'Please input 0 or more')]) forms.py class OtherForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['extra_name'].required = False self.fields['extra_cost'].required = False class Meta: model = Other fields = ('extra_name', 'extra_cost') widgets = { 'extra_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'extra_name', 'name': … -
how to create user profile automatically when I register with graphene django
I am learning graphql with graphene I would like to know how I can do when registering a user, the profile is also created, I do not upload code because I am only asking for information on how I can do it, I am not asking for it to be given to me by simply providing information -
How can I resolve Circular import?
enter code here from django.urls import path from . import views app_name ='store' urlpattherns =[ path('', views.all_products,name ='all_products') -
Rationale behind __lt field lookup in Django's DateFieldListFilter
What is the idea behind Django's admin filter DateFieldListFilter adding an __lt query for future dates? See excerpt below: self.lookup_kwarg_since = '%s__gte' % field_path self.lookup_kwarg_until = '%s__lt' % field_path ... self.links = (_('This year'), { self.lookup_kwarg_since: str(today.replace(month=1, day=1)), self.lookup_kwarg_until: str(next_year), }) For one, I don't see the need to add next_year to the search here, wouldn't tomorrow (this one actually is there for a daily search and a 7-day search) or something like end_of_the_day be enough? It seems very arbitrary and unnecessary to me. Secondly, wouldn't just having a __gte query without __lt faster? Or, perhaps, even using __range when the dataset is smaller could improve the search performance.