Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access specific choice in django choice field for conditional statements
I have an Account model which extends django's standard User model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) joined_groups = models.ManyToManyField(Group, related_name='joined_group', blank=True) EMAIL_PREFERENCES = [ ('user_emails', 'User Emails'), ('group_emails', 'Group Emails'), ('leader_emails', 'Leader Emails'), ] email_preferences = MultiSelectField( verbose_name = 'Email Preferences', choices=EMAIL_PREFERENCES, blank=True, max_choices=3, max_length=255, default=['user_emails', 'group_emails', 'leader_emails'] ) I also have many celery tasks that send email notifications for when Users create, update, delete, join, or leave Groups. However, I want these emails to only be sent if the User wants them to. When a new User registers, their email preferences default to accepting all emails, but they have the ability to change their preferences in this view: class EmailPreferencesUpdate(UpdateView): model = Account form_class = EmailPreferencesUpdateForm template_name = 'accounts/update_email_preferences.html' def form_valid(self, form): instance = form.save() email = instance.user.email update_email_preferences_notification.delay(email) return HttpResponseRedirect(reverse('user_detail', args=[str(instance.pk)])) My issue is I'm trying to have conditionals, before I run my celery tasks, to see if the User allows this type of email, but I can't figure out how to access the User's choices to see if that specific choice was selected. For example, I have a UserUpdate view: class UserUpdate(generic.UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/update_user.html' def get_object(self): return self.request.user def … -
KeyError in Django REST's POST request only occurs when sent from frontend but not when sent from postman
Frontend This is my code in the frontend. In short, it fetches the bing queries from third-party api, maps through the results to create a new array, and makes a POST request to Django REST axios .get( "exampleapi.bing.com/query", { withCredentials: true } ) .then((response) => { const webPages = response.data.webPages.value.map((page: any) => ({ id: nextId(), documentId: draftId, url: page.url, title: page.name, desc: page.snippet, isNews: false, })); console.log('webPages: ', webPages); axios .post( `${process.env.NEXT_PUBLIC_API_URL}/api/v1/recsources/`, { data: webPages, }, { withCredentials: true } ) .catch(AxiosCatch); }) .catch(AxiosCatch); This is what I see when I console.log the webPages right before I make the POST request, [ { "id": "id19", "documentId": "AVD4Mpy", "url": "https://www.verywellmind.com/social-media-and-depression-5085354", "title": "The Link Between Social Media and Depression - Verywell Mind", "desc": "Studies also indicate that social media may trigger an array of negative emotions in users that contribute to or worsen their depression symptoms. Defining Depression Clinical depression or major depressive disorder is a mood disorder characterized by ongoing feelings of sadness and loss of interest in activities that an individual once enjoyed.", "isNews": false }, { "id": "id20", "documentId": "AVD4Mpy", "url": "https://www.tuw.edu/school-news/does-social-media-cause-depression/", "title": "Does Social Media Cause Depression? | Study Media Psychology", "desc": "Recent research seems to link excessive … -
How to manipulate uploaded file in Django
I'd like to know how to manipulate in other function the file uploaded. I views.py I have the code that will read the file: def upload(request): global up myfile=request.FILES['myfile'] fs=FileSystemStorage() filename=fs.save(myfile.name, myfile) uploaded=fs.url(filename) up=myfile return render(request, 'pacote_u.html', {'uploaded': uploaded}) I'm trying to open and manipulate it, part of the code I'm trying to do this: def knapsack_upload(request): p = 0 perc = p / 100 # Leitura dos arquivos start = time.time() #path = pasta + arquivo path=up data = np.loadtxt(path, dtype=float, delimiter=" ") path = path.replace('.txt', '') In a function I receive the file and in other function I want to manipulate the values of the uploaded file. -
csrf token error for class based views in django
CSRF TOKEN error for class based views I am creating a CRUD model using class based views. For the create I used the class based view, CreateView and the crispy template when displaying it on the html file. But for some reason when I am deploying the code on to my development environment I am getting the following error: CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed - https://torii-dev-internet.azurewebsites.net does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need … -
Django/Apache2 not serving media files in production when "manually" added new media
I'm using Django (Django 4.0.3.) with Apache2 to run a webserver and serving media locally. Part of the site is a warehouse item tracker and is working fine, user can upload media (images) to items, categories etc and everything is displayed as expected. The other part displays multiple images downloaded from an ftp server via a script I wrote in python, which downloads images, stores them in its specific folder (in the media folder) and edits the Sqlite3 db to point Django to the correct media path - these images however is not displayed when "debug=False". It works when "debug=True". When clicking image I get the message: Not Found The requested resource was not found on this server. It's my first Django project so I'm a little out of my depth and I'm not really sure what to google. Anyone have any ideas how to make this work or how I could do this another way? My guess would be that it has something to do with static files? Project structure: |mysite |__warehouse |__static |__mysite |__media | |__lots of folders | |__(image) |__cameras Apache django.config: Alias /static /home/usr/mysite/static <Directory /home/usr/mysite/static> Require all granted </Directory> Alias /media /home/usr/mysite/media <Directory /home/usr/mysite/media> Require … -
How to force fill field to Inline Models in Django
We added the model named Comment as inlines in the Course model. We want to make it mandatory to fill in the fields in the Inlines model when the Save button is clicked. # models.py class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... updated_at = models.DateTimeField(auto_now=True)) class Comment(models.Model): CHOICES=[(1,'Approved'), (0,'Rejected')] course = models.ForeignKey(Course, on_delete=models.PROTECT) opinion = models.IntegerField(choices=CHOICES) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # admin.py class CommentInline(admin.StackedInline): model = Comment max_num = 1 radio_fields={'opinion':admin.HORIZONTAL} @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ('title', 'category', 'reviewer', 'created_at',) inlines = [CommentInline,] -
Django forms - 'CalculatorFormProduct' object has no attribute 'kwargs'
I am trying to filter my dropdown list and I get the following error KeyError at /product/product-name/ 'slug' I am not sure how to apply a slug filter in my formset so the user can only see components that are related to this product. Based on few answers and articles I know that I can pass slug by using kwargs.pop() in init method but it doesn't work in my case What I've tried so far: product_slug = kwargs.pop('related_product__slug') product_slug = kwargs.pop('slug') I even tried this: product_slug = self.kwargs['slug'] But I get this error: 'CalculatorFormProduct' object has no attribute 'kwargs' None of the above approached worked. I am confused about how should I do it correctly. Any advice on what am I doing wrong will be appreciated. forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(),required = False) number_of_units = forms.IntegerField(min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) def __init__(self, *args, **kwargs): # product_slug = kwargs.pop('related_product__slug') product_slug = self.kwargs['related_product__slug'] super().__init__(*args, **kwargs) self.fields['related_component'].queryset = CostCalculator.objects.filter(related_product__id=product_slug) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units', 'total_price') readonly_fields = ('created', 'related_product') CalculatorFormsetProduct = formset_factory(CalculatorFormProduct, extra=0) views.py ProductDetailView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'calculator/cost_calculator.html' model … -
Sometimes i get No changes detected when i try to do makemigrations
so my problem is that sometimes when I try to do makemigrations it gives me No changes detected error while I did some changes to my tables . I also tried py manage.py makemigrations ( name of my app ) at first it acts like everything is ok and successful but then when you want to display the tables you edited in models.py it raise error which the new row doesnt exist. anyway i also tried to used python manage.py migrate --fake Please give me some suggestion what to do ! -
filtering before joining django orm
I have three imaginary models: class Singer(BaseModel): singer_name = models.CharField(max_length=50, db_index=True) album = ForeignKey(album, on_delete=models.CASCADE, null=True, related_name="singer_album") class Album(BaseModel): album_name = models.CharField(max_length=50, db_index=True) class Fan(BaseModel): fan_name = models.CharField(max_length=50, db_index=True) admired_singer = ForeignKey(Singer, on_delete=models.CASCADE, null=True, related_name="fan_singer") now lets say I want to query all singers + albums starting with 'g' that belong to the singer that the fan 'RSNboim' admired. my intuition is to go like queryset = Fan.objects.values('admired_singer','album_name').filter(album_name__startswith='g') and now is my primary Question my real DB is running on about 6M records so I wish I could force Django to filter before it executes the join statement because it's consuming more effort first to join and only then filter by criteria. will inserting the filter() before the values() actually execute filtering before joining? or does Django/Postgres have their own way of prioritizing the operation's order? -
problem in loading css and js files in django project
can anyone pls help in loading and linking html css and js files so that files can be show on local host server when i run django project im newbie if anybody can help i can email them code so they can make corrections i tried almost more than 26 hours trying to solve it but cant i provided my codes here if anyone want to contact they can contact me on my email or msg or can drop their ids ill send them code this is my urls.py code from django.contrib import admin from django.urls import path from final import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.homepage), path('aboutUS/',views.aboutUS), path('course/<int:courseid>',views.courseDetail), ] this is my setting.py code """ Django settings for final project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-!&f8&!k2uik_#y^b@o%4wmxxh%+xnw=gp9g=2o_h85d^^kpqd&' # SECURITY WARNING: don't run with debug turned … -
Search by multiple parameters, Django?
I have model Person: name, phone, address i have person1 with : name1, phone1, address1 Is it possible to find all entries of a model that has the same name and address but must have a different phone ? -
Order Django Queryset by attribute that could be char or int?
I have the following model that I need to order by the grade attribute, but that attribute can be either a character or integer (K, KA, KF, NA, 1, 2, 3, etc.)... what is the best way to accomplish that? We are using MS SQL as a backend (I cannot use __regex because the DB version does not support it). I annotated a first_letter_group attribute onto the queryset because any grade with multiple letters should be treated as it's first letter (KA = K, KN = K, etc.) I'm trying to order these results by alpha first, then ascending numerically (e.g. 'P, K, 1, 2, 3, 4...') # This is an unmanaged model class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="loc_id") grade = models.CharField(db_column="grade", max_length=10) end_year = models.IntegerField(db_column="end_year") run_date = models.DateField(db_column="run_date") student_count = models.IntegerField(db_column="students") I've tried annotating additional fields where I cast the results to CharField or IntegerField but they (expectedly) error out when they hit something that does not convert. all_enrollments = ( Enrollment.objects.filter( location_id__in=location_ids, end_year=today.year, ) .order_by("-run_date") .annotate(first_letter_group=Substr("grade", 1, 1)) ) ordered_enrollment_list = ( all_enrollments.annotate( number_field=Cast( "first_letter_group", output_field=IntegerField() ), str_field=Cast( "first_letter_group", output_field=IntegerField() ), ) .order_by("-str_field", "number_field") ) I can't figure out how to do this without the … -
How we can verify Email and SMS OTP at same time
I'm implementing 2FA with Twilio. I want to verify email and SMS OTP both at the same time. If I send Email and SMS OTP if the User enters the wrong OTP one of the. The valid otp verifies but the other one is not. how we can achieve this to verify both at the same time. -
Django ckeditor unable to save edited initial values of a form field
I am using a class based create view to show a form to the end user. One of the fields of the form shows an initial value, which would be changed by the end user, before saving the values to the database. The form looks like the below: class R1Form(forms.ModelForm): interview_date = forms.DateField(widget=DateInput()) feedback = forms.CharField(widget=CKEditorWidget()) def __init__(self, *args, **kwargs): super(R1Form, self).__init__(*args, **kwargs) self.initial['feedback'] = template_R1.objects.all().first().template class Meta: model = R1 fields = ['interview_date', 'interviewers', 'feedback', 'comment', 'recommended_level', 'progress'] widgets = {'feedback': CKEditorWidget()} In the above form the field called 'feedback' shows an initial value from the database. The class based, create view looks like below: class R1CreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = R1 form_class = R1Form template_name = "interviews/r1/create.html" # This a quick way to populate fields not present in the model form, but required in the model. def form_valid(self, form): form.instance.candidate_id = self.kwargs['candidate'] return super().form_valid(form) # Required because with HTMX we need to provide a url for post request, and our url also requires additional parameters def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = self.request.GET.get('page', 1) context['candidate_pk'] = self.kwargs['candidate'] return context def get_success_url(self): return reverse_lazy("cvscreenings-success", kwargs={'candidate': self.kwargs['candidate'], 'message': 'Saved!'}) def test_func(self): return True When the form is shown to … -
How to create custom db model function in Django like `Greatest`
I have a scenario that, i want a greatest value with the field name. I can get greatest value using Greatest db function which django provides. but i am not able to get its field name. for example: emps = Employee.objects.annotate(my_max_value=Greatest('date_time_field_1', 'date_time_field_1')) for e in emps: print(e.my_max_value) here i will get the value using e.my_max_value but i am unable to find out the field name of that value -
== operator not working in if statement in Python Django
Hi Everyone I am creating one function and use row sql query to get data but when use if statement with == operator then expected output is not coming, inside for loop what data if date is today that day of trips 0 but i am getting null value, please help me out. views.py def car_report(request): start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') dates = request.GET.getlist('dates[]') team_id = int(request.GET.get('team_id')) today_date= datetime.today().strftime('%Y-%m-%d') car_report= connection.cursor() car_report.execute(''' SELECT * from table ''', [dates[0],dates[1],dates[2],dates[3],dates[4],dates[5],dates[6],team_id,start_date,end_date]) car_report_data = car_report.fetchall() json_res=[] for row in car_report_data: srow = [x.decode('utf-8') if isinstance(x, bytes) else x for x in row] json_obj=dict(car_number=srow[0],name=srow[1],total_trips=srow[2],status=srow[3],day1_trips=srow[4],day2_trips=srow[5],day3_trips=srow[6],day4_trips=srow[7],day5_trips=srow[8],day6_trips=srow[9],day7_trips=srow[10],total_online_hours=srow[11],total_revenue=srow[12],dead_km=srow[13],yesterday_online_hours=srow[14],yesterday_revenue=srow[15],today_trips=srow[16]) print(json_obj) if dates[2] == today_date: #if statement is not exicuted print(dates[2]) print(today_date) json_obj['day3_trips']=0 json_res.append(json_obj) return JsonResponse(json_res, safe=False) -
Pytorch Model causing 500 server error in Django App
This is My Django project Directory, and in the "bills" app, I am trying to import my YOLOV5 pre-trained custom model (which works fine on its own). So Views.py : def crop(request): model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True) return render(request, '../templates/results.html') This is causing my app to return a 500 server error when hitting that URL; I know the model is causing it because if I comment out that first line #model = torch.hub.load('../yolov5-master', 'custom', path='../best.pt', force_reload=True) Then the page shows fine. I looked up many articles on how to load a Pytorch model into Django and it seems I am doing it right, can you please help me figure out what's the problem ? -
Django Rest Framework/Djoser sending role information to frontend (Vue)
I am working on a simple site with a login functionality. To handle auth in the backend I am using the Djoser library. I have login functionality working. However now I want to create a site on my frontend which has restricted access based on a users roles. What I want is that if a users is admin/staff then the frontend site has another page in the navbar. So my question is, how should I go about handling this. My first thought is that, when the user is logging in, then the token is sent to the frontend and stored, and then with the token I would also send the users role and store this aswell. However I am not sure how to extend Djoser to do this. Another option would be to simply say that after the user has logged in and received the token and stored it in the frontend, I would make a subsequent request to the backend to get that users information including its role and store that aswell. This of course takes 2 backend calls instead of one as in the first option. To me it seems optimal to use the first option, however I … -
import ra.admin.admin could not be resolved django
I am having issues using the ra framework in django, I am using vs code, python 3.8.10, each time I try to import the ra framework there is a yellow line. what do I do to resolve this -
How to swap a Django ManytoMany relationship
I have a situation where two models have been previously created: class Publisher(models.Model): name = models.CharField(max_length=255) publications = models.ManyToManyField('Publication') class Publication(models.Model): name = models.CharField(max_length=255) and now due to a change in how these models are being used, I need to move the ManyToManyField over to the other model, to hopefully end up with: class Publisher(models.Model): name = models.CharField(max_length=255) class Publication(models.Model): name = models.CharField(max_length=255) publishers = models.ManyToManyField('Publisher') while maintaining the existing relations between the two models. Is this possible? I've tried swapping the relation over but the migration that is generated only removes the field from the old model, which doesn't seem right. How can I preserve the ManyToMany link when I move the field from one Model to the other? -
Notification in django?
I have been developing in django for sometime now, and have developed a neat website having functionality such as writing blogs, posting questions, sharing content etc. However there is still one thing that is missing and i.e. creating notification for users. What I want to do is to inform users in their profiles, whenever somebody comments on their posts, or if they are following a particular post and there is an update on it, then inform the user of that update. I have looked around many applications but I am still very confused about how to do it. In case of using django-notification I seem to have an impression(which can be wrong) that I can use this only to inform the user via email, i.e. I cannot show these notifications in the user profile, just like we have on facebook. Firstly I would like to know if I am wrong, and then I really need some proper tutorial or guidance on how to go about doing it. I know how to register a notification and send it on proper signal but there is no documentation on how to show these notices in a template, if this can be done. Any … -
Creating fake model in djanago rest framework without migrating it for using in swagger
I am trying to implement swagger ui using in Django Rest Framework using drf-spectacular. I don't have any database insatlled yet and in this phase I don't want to implement or create any database or table. I only want to create an API Contract with different Endpoints and showing required and response data types in swagger ui. My question is, that how can I create a model (fake model) without implementing it and without migration? -
Positive Validation Check Django Not Working
I have to create this validation rule when Start= (start_new + start_old) >0 or is positive and End = (end_new + end_old) >0 or is positive then the validation error will raise that" Positive Strat and Positive End are not allowed in the conjunction", But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. my code in django form.py for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) if (start_new + start_old) > 0 and (end_new+end_old) > 0: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
custom email verifivcation template
I am using dj rest auth for authentication and i need to override email verification template with my custom html , according to documantion, i added these files to account/email directory: account/email/email_confirmation_signup_subject.txt account/email/email_confirmation_signup_message.txt account/email/email_confirmation_subject.txt account/email/email_confirmation_message.txt account/email/email_confirmation_signup_message.html account/email/email_confirmation_message.html and i put the custom html codes in email_confirmation_message.html file , but still i get the default html template in email , is there any step i am missing? -
Dynamic django select field returns form-invalid
I have form with one select field, when page is loaded I will send ajax request to fetch current user's company categories. Upto this point everything is working as expected, but when I submit the form will return form-invalid. I am not familier with django forms. I will really appreciate if you can figure out what is wrong with my code MODEL class Expense(models.Model): slug = models.SlugField(max_length=80, unique=True) debit = models.DecimalField(decimal_places=2, max_digits=10) date = models.DateTimeField(default=timezone.now) category = models.CharField(max_length=50, choices=()) remark = models.CharField(max_length=50, validators=[MinLengthValidator(3)]) company = models.ForeignKey(Company, on_delete=models.CASCADE) VIEW def expense_types(request, company_id): company = Company.objects.filter(company_id=company_id).first() types = ExpenseType.objects.filter(company=company).all() output = [] for typ in types: data = {} data['category'] = typ.category output.append(data) return JsonResponse({'categories': output}) URL path('<str:company_id>/ExpenseTypes', views.expense_types, name='get-expense-types') TEMPLATE <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form|as_crispy_errors }} <div class="row"> <div class="col-md-6 col-sm-6"> {{ form.date|as_crispy_field }} </div> <div class="col-md-6 col-sm-6"> {{ form.debit|as_crispy_field }} </div> </div> <div class="row"> <div class="col-md-6 col-sm-6"> {{ form.category|as_crispy_field }} <input type="hidden" id="company_id", value="{{ user.company.company_id }}"> </div> <div class="col-md-6 col-sm-6"> {{ form.remark|as_crispy_field }} </div> </div> <div class="form-group"> <button class="btn btn-outline-warning btn-block" type="submit">Save</button> </div> </form> <script type="text/javascript"> let category = document.getElementById('id_category') let company_id = document.getElementById('company_id').value fetch('/' + company_id + '/ExpenseTypes').then(function(response){ response.json().then(function (data){ let optionHTML = '' for …