Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ChatBot vs Messenger
Which of this is interesting and best for development ? if possible say the framework or language to proceed further! I'm comfortable with Python and Django framework. -
How to change sub-template in template in Django?
I try to make a template that include template in it. Is it possible to pass html file name to include? Now I use this code. {% include "edit_course.html" %} but I want to replace "edit_course.html" with value from context instead. {% include {{name}} %} How can I do this? -
object is not iterable - Django Modelform
I'm using Model forms to add a row to a table in Django, here are my views and forms file views.py def add_ad_mod(request): current_user = request.user current_ip = get_client_ip(request) selected = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0] selected_category = selected.cat selected_town = selected.town if request.method == 'POST': add_ad_mod_form = AddAdModForm(request.POST, request.FILES, cat=selected_category, loc=selected_town) if add_ad_mod_form.is_valid(): model_instance = add_ad_mod_form.save(commit=False) model_instance.created_by = current_user.email model_instance.category = selected_category model_instance.town=selected_town if request.user.is_superuser: model_instance.is_active = True else: model_instance.is_active = False add_ad_mod_form.save() return redirect('dashboard') else: add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town) context = { 'add_ad_mod_form': add_ad_mod_form, 'selected_category': selected_category, 'selected_town': selected_town, } return render(request, 'add_ad_mod.html', context) I am using views.py to send a variable as you see to the form itself forms.py class AddAdModForm(forms.ModelForm): def __init__(self, *args, **kwargs): current_categ = kwargs.pop('cat') current_loc = kwargs.pop('loc') super(AddAdModForm, self).__init__(*args, **kwargs) self.fields['sub_category'] = forms.ModelChoiceField(label="Sniffer", queryset=SubCate.objects.filter(main_category=current_categ)) self.fields['sub_location'] = forms.ModelMultipleChoiceField (widget=forms.CheckboxSelectMultiple,label="Sniffer", queryset=SubLoc.objects.filter(main_town=current_loc)) title = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Ad Title here', 'style': 'width: 100%; max-width: 800px;' } ) ) description = forms.CharField( widget=forms.Textarea( attrs={ 'placeholder': 'Ad description is here', 'style': 'width: 100%; max-width: 800px;' } ) ) image = forms.ImageField(required=True) image2 = forms.ImageField(required=False) image3 = forms.ImageField(required=False) image4 = forms.ImageField(required=False) image5 = forms.ImageField(required=False) address = forms.CharField(max_length=100, widget=forms.Textarea( attrs={ 'placeholder': 'Detailed Address is here ', 'style': 'width: 100%; max-width: 800px;' } ) ) … -
django: filter queryset when 2 fields have same value
I have a model which has 2 fields like, pickup_station_id = models.IntegerField(null=True) drop_station_id = models.IntegerField(null=True) I want a filter in admin which can filter the queryset based on, pickup and drop ids are different pickup and drop ids are same How can I get a queryset based on these conditions? I mean, something like this, Mymodel.objects.filter(pickup_station_id==drop_station_id) Mymodel.objects.filter(pickup_station_id!=drop_station_id) -
S3 image upload error with boto3 and dropzone.js
using this API i am able to upload the file to S3 using Postman. i gave direct path to the file "/home/user/Downloads/black-rose.png" header_logo = request.data['header_logo'] #local file path data = open(header_logo, 'rb') s3 = boto3.resource( 's3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4') ) #generatre a random url header_logo = "header_logo/" + get_random_string(length=20) + ".png" #AWS foler & file name with public access s3.Bucket(BUCKET_NAME).put_object(Key=header_logo, ContentType = 'image/png', Body=data, ACL='public-read') when i give the direct file path its working, but my front end developer says he cant give direct file path using javascript so he is using a plugin "dropzonejs" to encrypt the file path which gives file like like this data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAgAElEQVR4Xoy9B7hlZ3Xe/9u9nH5uL3OnabqkkTTqCFVAgA2SwQaX4GATHIc/DiFg which on directly giving this data to the api throws error -
Django: How to query from two models with a common foreign key to third model and a common non foreign key field?
I have two models, both of them have a foreign key to the User model and a common date field schedule_date. Here are the model definitions: class Schedule(models.Model): schedule_date = models.DateField() user = models.ForeignKey(User, related_name='schedule_set') start_time = models.TimeField() end_time = models.TimeField() breaks = JSONField() class Attendance(models.Model): schedule_date = models.DateField() user = models.ForeignKey(User, related_name='attendance_set') calculated_attendance = models.DecimalField(null=False, decimal_places=2, max_digits=3) adjusted_attendance = models.DecimalField(null=True, decimal_places=2, max_digits=3) approved_by = models.ForeignKey(User, related_name='attendance_approved_by_set', null=True) approved_at = models.DateTimeField(null=True) calculation_details = JSONField() I want to fetch the rows from Attendance model with some filter conditions and also want to access the corresponding Schedule row for each row where the schedule_date is the same. In terms on SQL, I want to run the following query: select a.user_id, a.schedule_date, a.calculated_attendance, a.calculation_details, s.start_time, s.end_time, s.breaks from "Attendance" a, "Schedule" s where a.user_id = s.user_id and a.schedule_date = s.schedule_date and <more filter conditions on Attendance table> -
How works Python Web Development when we request info from the database?
The only program with what I had experience with backend in development was PHP. The only thing I didn't like was the part when we do a request to the database we need to do F5 or do the request again. After a few research, I found someone telling Meteor show automatically the change on the info from the request and we don't need to restart the request or do F5 to see them. I just want to know if Django and Flask can do the same, so show data like Meteor in real-time or like PHP so I always need to reset my request to see if something is different on my database? -
Using gremlin-python Janus for social networking application
I'm getting started with graph databases. I want to migrate a social networking application from sql to Janus Graph database. I plan to build the application using Python Django framework. I also plan to scale the application using using IBM's ComposeForJanusGraph in the future. Problems I face: 1) I'm following the tinkerpop documentation for gremlin_python and I face several issues with the syntax because I couldn't find any good documentation. Only documentation I found here is also very short and not that helpful of how to do a CRUD. (For example how to create a new database, how to configure the search or storage database, how to create a node, how to create an edge, how to query for a vertex with a specific edge is not documented well clearly. None of them works when I try myself.) 2) Is there anything I should know before I learn and build it? -
In case the user forgot the password, how can I send him a reset link?
In case the user forgot the password, how can I send him a reset link? Django's PasswordChangeView, requests the old password, not resetting password. -
Passing variables from views.py to forms.py causes an error when form submitt
I've passed some variables from my views to forms to use it filtering some fields in the forms. but when I hit the submit button in the form it gives me the error. KeyError at /add_ad/mod/ 'cat' Here are the full traceback of the error : Traceback: File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\lito\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\views.py" in add_ad_mod 210. add_ad_mod_form = AddAdModForm(request.POST, request.FILES) File "C:\Users\lito\Desktop\DJ\JEHLUM - Copy - Copy\web_site\forms.py" in __init__ 47. current_categ = kwargs.pop('cat') Exception Type: KeyError at /add_ad/mod/ Exception Value: 'cat' And here are the codes I've used for my files : views.py def add_ad_mod(request): current_user = request.user current_ip = get_client_ip(request) selected = Temp.objects.filter(created_by_ip=current_ip).order_by('-created_at')[0] selected_category = selected.cat selected_town = selected.town add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town) if request.method == 'POST': add_ad_mod_form = AddAdModForm(request.POST, request.FILES) if add_ad_mod_form.is_valid(): model_instance = add_ad_mod_form.save(commit=False) model_instance.created_by = current_user.email model_instance.category = selected_category model_instance.town=selected_town if request.user.is_superuser: model_instance.is_active = True else: model_instance.is_active = False add_ad_mod_form.save() return redirect('dashboard') else: add_ad_mod_form = AddAdModForm(cat=selected_category, loc=selected_town) context = { 'add_ad_mod_form': add_ad_mod_form, 'selected_category': selected_category, 'selected_town': selected_town, } return render(request, 'add_ad_mod.html', context) Forms.py class AddAdModForm(forms.ModelForm): def __init__(self, *args, **kwargs): current_categ = … -
type object 'Questions' has no attribute 'objects'
Im new in django , When im learning django from documentation .i tried to make api using serializers and Function Based views .the this shows type object 'Questions' has no attribute 'objects models.py class Questions: title = models.CharField(max_length=40) description = models.TextField(max_length=50) status = models.CharField(default='inactive', max_length=30) created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE serializers.py from rest_framework import serializers from demoapp.models import Questions class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Questions fields = ( 'id', 'title', 'description', 'created_by', ) urls.py from django.urls import path from demoapp.views import * urlpatterns = [ path('poll', demoapp), ] views.py from django.shortcuts import render from rest_framework import viewsets from demoapp.models import Questions from demoapp.serializers import QuestionSerializer from django.http import JsonResponse def demoapp(request): if request.method=="GET": queryset=Questions.objects.all() serializer=QuestionSerializer(snippets) return JsonResponse(serializer.data,safe=False) -
Filter only by years in django admin
I would like to create a filter in the admin panel which would filter events based on the year. I've created a list of years, but I do not know how to combine it with lookup and queryset. class SearchByYear(admin.SimpleListFilter): title = _('title') parameter_name = 'year' year_list = models.Event.objects.values_list('date', flat=True) y = [i.year for i in year_list] print('this is list only with years: ', y) def lookups(self, request, model_admin): return ( ('year', _('2018')), ('year1', _('2019')), ) def queryset(self, request, queryset): if self.value() == 'year': return queryset.filter(date__year=2018) if self.value() == 'year1': return queryset.filter(date__year=2019) -
django orm : connecting 2 models using one base model
i have 3 models auth-user as my base model and other 2 models have the foreign key of auth-user . Now i want to combine all three tables and create an object which fetches all data from 3 tables combined. -- class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class employees(models.Model): employee_name = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, to_field='username') department = models.CharField(max_length=100) dob = models.DateField() doj = models.DateField() blood_grp = models.CharField(max_length=100, null=True) father_name = models.CharField(max_length=100, null=True) add1 = models.CharField(max_length=100, null=True) add2 = models.CharField(max_length=100, null=True) # doj = models.ImageField(upload_to='profile_pics', blank=True) con_relation = models.CharField(max_length=100) # email_id = models.EmailField(max_length=254, blank=True, null=True) webmail_id = models.CharField(max_length=100, blank=True, null=True) emergency_mob = models.CharField(max_length=100) contact_person = models.CharField(max_length=100, blank=True, null=True) biometric = models.CharField(max_length=100, blank=True, null=True) biometric_id = models.CharField(max_length=100, blank=True, null=True) offer_letter = models.CharField(max_length=100, blank=True, null=True) team_leader = models.CharField(max_length=100) manager = models.CharField(max_length=100, blank=True, null=True) employment_status = models.CharField(max_length=100, blank=True, null=True) company_id = models.CharField(max_length=100) adhar_id = models.CharField(max_length=100, blank=True, null=True) pan = models.CharField(max_length=100, null=True) class auth_ext(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, to_field='username') emp_code= models.CharField(max_length=100,unique=True,default=True) is_role = models.CharField(max_length=100) is_designation = … -
Django OAuth and SAML
I have a Django application and I have no experience on logins topics, so I would like to know if it is possible to integrate both authentication systems. SAML for some users (University f.e.) and OAuth (google, facebook,etc) for other users. Is it that possible? Thanks in advance -
Django unit testing
If a method returns each time different different values,how to do unit testing for that method i m trying result=someObject.someMethod() expected_result=someValue asertEqual(result,expected_result) but in each time the result is different ,so some time the test is clear and some times it fails -
how to use redirect with multiple parameters in django views?
I am trying to redirect to a function from another function in views. But i am getting following error NoReverseMatch at /sigma/status1/ Reverse for 'testview' with keyword arguments '{'amount': 1.000, 'stat':'Approved', 'ref': '10917'}' not found. 1 pattern(s) tried: ['sigma\\/status2/(?P<amount>\\d+)/(?P<stat>[a-z][A-Z]+)/(?P<ref>\\d+)/$'] Below is corresponding part of my views.py return redirect(reverse('testview',kwargs={'amount':1.000,'stat':'Approved','ref':str(res['ref'])})) def payment_status2(request,amount,stat,ref): return render(request, 'confirm1.html') Below is corresponding part of my urls.py urlpatterns = [ url('status1/', views.payment_status1), url(r'^status2/(?P<amount>\d+)/(?P<stat>[a-z][A-Z]+)/(?P<ref>\d+)/$', views.payment_status2,name="testview"), ] -
Setting Django CSRF Cookie
I'm using React as front and Django as back. Httprequest fails, prompting that the CSRF Cookie is not set. I have followed the django docs,I have this code: var jQuery = require("jquery"); // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } let header = new Headers({ "X-CSRFToken": getCookie("csrftoken"), "Content-Type": "application/json; charset=utf-8", "Access-Control-Request-Headers": "*", "Access-Control-Allow-Methods": "GET, POST, HEAD, OPTIONS, PUT, DELETE, PATCH" }); Using console.log(getCookie("csrftoken")); prints null, which leads me to believe that Django is not setting the cookie. My middleware looks like this: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Early in development I used this view for testing: @ensure_csrf_cookie def token(request): if request.method == 'GET': return HttpResponse(status=204) else: return HttpResponseNotAllowed(['GET']) This works well, but it does not feel very clean to call this everytime the user uses the website. -
What if I don't commit django migrations?
We have been working on a django project for months. You know for a dev team, migrations conflicts happen many times. I searched a lot to look what others do with this kind of problem and got results: What really annoys me about Django migrations django migrations - workflow with multiple dev branches Django Migrations and How to Manage Conflicts How to avoid migration conflicts with other developers? And many other articles about how to avoid and resolve migration conflicts. I want to know what if we just ignore migration files and just don't commit them? Any answer is appreciated. -
Python Unable to show Error with self.add_error()
I am having a problem and need your help. I am making a django website, following information need to be verified. If it pass registration will be success and fail notice will show up. But Mean while there are no problem with success, but Notice won't show up if fail. Here are my form.py, could anyone help me? Much Thanks. if settings.VERIFY_BY_SFID and all([i in cleaned_data for i in fields]): number = cleaned_data["mobile_number"] verified =SignUpFailureAttemptService.verify_mobile_number(number) if not verified: self.add_error(None, _("Your application was rejected.")) -
how to skip while loop from Django Channels2 receive handler
I want to subscribe redis channel in websocket receive handler. like this: async def receive(self, text_data=None, bytes_data=None): self.ps = redis_conn.pubsub() await self.ps.subscribe(settings.REDIS_CHANNELS) while True: msg = await self.get_msg_from_queue() if not msg: continue logger.info("get msg %s" % msg) await self.send(text_data=json.dumps(msg)) but when link is close by frontend. I get follow warning in server log: WARNING Application instance <Task pending coro= <AsyncConsumer.__call__() running at /data/tianyi/MozheAPI/venv/lib/python3.6/site- packages/channels/consumer.py:54> wait_for=<Future pending cb= [<TaskWakeupMethWrapper object at 0x7fc3ea6765b8>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 21506] path=b'/listen'> took too long to shut down and was killed. How to check the websocket status in while loop? -
How to stop a user from copying plain texts from my page and also from downloading any images in my post, nor can he right click onto the page?
https://www.freeprojectz.com/paid-projects/django-python-mysql/car-rental-system these people did it awesome, can i know how to do the same please, using django I'm also building a similar project like this -
how to lock access to django redis cache
I have concurrent access to a key in django-redis-cache by multiple gunicorn clients. How can I lock accessing to key so only one client can access key at each time? -
Better way to query and join multiple querysets other than using a forloop in django?
I have a model Item: Item: batch_no batch_no can be anything from 1 to 20. And there are 1000s of items in the database. Now. I need to get first 4 elements of each batch_no. I know to do it by querying and appending using forloop. batches = Items.objects.values('batch_no').exclude(batch_no__isnull=True).distinct() blist=[] for batch in batches: bitems= Item.objects.filter(batch_no=batch['batch_no']) blist.append(bitems) return blist Is there a better way than this? To do in a single Query? I'm new to Django. -
django admin one-to-one-field inline save data
I have the following classes in models.py: class Profile(models.Model): ....... class MyUser(AbstractUser): profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) ...... Admin.py: class MyUserInline(admin.StackedInline): model = MyUser ......... class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser class MyAdminPasswordChangeForm(AdminPasswordChangeForm): def save(self, commit=True): """ Saves the new password. """ password = self.cleaned_data["password1"] self.user.myuser.set_password(password) if commit: self.user.myuser.save() return self.user.myuser class ProfileAdmin(UserAdmin): inlines = (MyUserInline,) form = MyUserChangeForm ........ In my scenario, I want the user's username be his email, saving this can easily be done by overriding save_model in ProfileAdmin and save like this: def save_model(self, request, obj, form, change): saved_user = form.save() saved_user.myuser.username = saved_user.myuser.email saved_user.save() but the problem is when we are inserting a duplicated email. email field is not unique, but username is, so Profile is saved correctly, but saved_user.save() cannot do its job (UNIQUE constraint failed: accounts_myuser.username), nad this error is not caught in try..catch. I believe I should change the place of setting user's username, but O couldn't find the correct way. How should I do that? tnx -
Django migrations, added field before deletion old
14: operations = [ migrations.RemoveField( model_name='storesubscriptionplan', name='add_on', ), migrations.AddField( model_name='storesubscriptionplan', name='add_on', field=models.ManyToManyField(blank=True, to='account.SubscriptionAddOn'), ), ] 15. operations = [-------------------------SCROLL DOWN TO SEE FIELD-------------- migrations.AddField( model_name='storesubscriptionplan', name='add_on_display_order', field=models.BooleanField(default=0), ), migrations.AddField( model_name='storesubscriptionplan', name='add_on_is_deleted', field=models.BooleanField(default=0), ), migrations.AddField( model_name='storesubscriptionplan', name='add_on_last_updated', field=models.DateTimeField(auto_now=True, null=True), ), migrations.AddField( model_name='storesubscriptionplan', name='add_ony_created_date', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='storesubscriptionplan', name='monthly_created_date', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AddField( model_name='storesubscriptionplan', name='monthly_display_order', field=models.BooleanField(default=0), ), migrations.AddField( model_name='storesubscriptionplan', name='monthly_last_updated', field=models.DateTimeField(auto_now=True, null=True), ), migrations.AddField(---------------------ADDED------------------- model_name='storesubscriptionplan', name='add_on', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='account.SubscriptionAddOn'), ), migrations.AlterUniqueTogether(----------OF ANOTHER TABLE------------- name='storecredits', unique_together={('store', 'credit_type')}, ), migrations.RemoveField( model_name='storesubscriptionplan', name='created_date', ), migrations.RemoveField( model_name='storesubscriptionplan', name='last_updated', ), migrations.AlterUniqueTogether(---------THIS BOUGHT ME HEADACHE---------- name='storesubscriptionplan', unique_together={('store', 'add_on')}, ), migrations.RemoveField(---------------------REMOVED------------------- model_name='storesubscriptionplan', name='add_on', ), ] In the 14th migrations i choose to make my add_on field from foreign key to many-to-many so woked fine, then i choose to make it back to foreign key. As you can see in 15th migration it created the field before removing it and then removed the field, his made field deleted in the database table, when I visited django admin it gave me error no add_on_id exist, so I looked at table structure, it wasn't there as it was deleted, and since then everything went wrong, though in next migration when i changed a field name, it created the field as: …