Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save data from a ModelForm?
I am new to Django, so I am trying to build a dummy site which contains most of the basic concepts, but when it comes to saving data from a form, I am really struggling. I have watched many videos and following tutorials everything works fine, but they all use different methods with class-based views and all. All I am trying to do is saving some data from a form following the Django documentation. The project at this stage is very simple: a homepage with a dropdown menu inside the navbar labelled 'Person'. From the dropdown, the user can select two links, and namely 'Persons List', and 'Create Person'. Now, I am using function-based views as you can see from views.py from django.shortcuts import render from .models import Person from .forms import CreatePersonForm from django.http import HttpResponse # Create your views here. def home_view(request): return render(request, 'home.html') def persons_list_view(request): persons = Person.objects.all() context = { 'persons': persons } return render(request, 'persons_list.html', context) def create_person_view(request): if request.method == 'POST': form = CreatePersonForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponse('Working!') else: form = CreatePersonForm() context = {'form': form} return render(request, 'create_person.html', context) From these functions, I am deriving the form to … -
Django Model Form not saving to db
I have a model for car dealers and I am trying to have a form to create them. The form does not save to the db for some reason however it does reach the redirect. No errors are shown either. models.py class Dealer(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=50) website = models.CharField(max_length=100) address = models.CharField(max_length=100) featured_image = models.ImageField(upload_to="dealers/") class Meta: verbose_name_plural = "Dealers" def __str__(self): return self.name views.py def create_dealer_view(request): if request.method == "POST": form = CreateDealerForm(request.POST) if form.is_valid(): dealer = form.save(commit=False) dealer.save() return redirect('main:homepage_view') else: form = CreateDealerForm context = { "title": "Create - Dealer", "form": form, } return render(request=request, template_name="main/create/create_dealer.html", context=context) forms.py class CreateDealerForm(forms.ModelForm): class Meta: model = Dealer fields = ('name', 'phone','website', 'address', 'featured_image',) widgets = { 'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}), 'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}), 'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}), 'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}), } create-dealer.html {% block content %} <div class="container text-center"> <form method="POST"> {% csrf_token %} {{ form.name }} {{ form.phone }} {{ form.website }} {{ form.address }} {{ form.featured_image }} <br> <button type="submit" class="btn btn-primary"><i class="fa fa-plus" aria-hidden="true"></i> Create Dealer</button> </form> </div> {% endblock content %} -
"You don't have permission to view or edit anything." even if user has access to model
I know this "error" message is common and there are already posts around this. But did not find a way to fix my issue. I am using the already existing "User", "Group", "UserManager" provided by Django. However, I have a custom authentication backend: class MyAuthentication: # ... # ... def has_perm(self, user_obj, perm, obj=None): permissions = Permission.objects.filter(user=user_obj) if perm in permissions: return True return False My user is an admin NOT a super user. He is part of a group which has all the permissions to view, edit, delete, add my models. He is able to access them by using the URL directly. However, when he tries to connect to the admin page /admin/, he is getting this error message. You don't have permission to view or edit anything I searched for a permission which will give him access to view the lists of models in django documentation, but found nothing. Do I need to add anything to my backend authentication? Add a new perm ? Even advice on where to look at in order to investigate would be very appreciated! -
How do I specify the order of fields in a form? [django-crispy-forms]
We are using Django 2.2 for Speedy Net. We have a contact form and recently it has been using by spammers to send us spam. I decided to add a "no_bots" field to the form where I'm trying to prevent bots from submitting the form successfully. I checked the form and it works, but the problem is we have 2 sites - one one site (Speedy Net) the order of the fields is correct, and on the other site (Speedy Match) the order of the fields is not correct - the "no_bots" field comes before the "message" field but I want it to be the last field. How do I make it last? Our template tag contains just {% crispy form %} and I defined the order of the fields in class Meta: class FeedbackForm(ModelFormWithDefaults): ... no_bots = forms.CharField(label=_('Type the number "17"'), required=True) class Meta: model = Feedback fields = ('sender_name', 'sender_email', 'text', 'no_bots') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelperWithDefaults() if (self.defaults.get('sender')): del self.fields['sender_name'] del self.fields['sender_email'] del self.fields['no_bots'] self.helper.add_input(Submit('submit', pgettext_lazy(context=self.defaults['sender'].get_gender(), message='Send'))) else: self.fields['sender_name'].required = True self.fields['sender_email'].required = True self.helper.add_layout(Row( Div('sender_name', css_class='col-md-6'), Div('sender_email', css_class='col-md-6'), )) self.helper.add_input(Submit('submit', _('Send'))) def clean_text(self): text = self.cleaned_data.get('text') for not_allowed_string in self._not_allowed_strings: if (not_allowed_string … -
How to make a sticky footer in Boostrap?
I am currently developing a project Django and I want to set up a footer pasted at the bottom of the page (sticky footer). looking for forums, I found a solution that 'does the job' (ie paste the footer at the bottom of page) but has an awkward behavior to know that depending on the size of the screen it masks some buttons (for example, the paging button of a dataTable) it is also embarrassing for my functional tests (selenium) because some tests fail when the butters are masked by the footer (see image in the red box) Is there a bootstrap footer or a way to overcome this problem? /* Sticky footer styles -------------------------------------------------- */ .asteriskField{ display: none; } form .alert ul li{ list-style: none; } form .alert ul { margin:0; padding: 0; } body > div > div.col-6 > div > div > h2 { font-size: 20px; } .footer { position: fixed; bottom: 0; width: 100%; /* Set the fixed height of the footer here */ height: 60px; line-height: 60px; /* Vertically center the text there */ background-color: #f5f5f5; /*background-color: red;*/ } -
How do i display a filtered selection list in django form
My problem is this: I have a list of people that can be selected as people that can attend a meeting. Accounts that are inactive should not be displayed in that list. I want to filter those accounts out of the list of possible users to select This is what the code looks like now: class StudioMeetingNoteAdmin(admin.ModelAdmin): fields = ('this_is_test',) fieldsets = [ ('Tijden', {'fields': ['meeting_start_time', 'meeting_end_time']}), ('Wie is de voorzitter/notulist', {'fields': [('chairman', 'secretary')]}), ('Opkomst', {'fields': [('attending_persons', 'absent_persons')]}), ] inlines = [OpeningAndParticularitiesInline, ActionListPointInline, RemarksPriorMeetingInline, IssuesToAddressInline, OurNextMoveInline, QuestionRoundInline] list_filter = ['meeting_start_time'] search_fields = ['meeting_start_time'] list_display = ('meeting_start_time', 'chairman', 'secretary') The field attending_persons should be filtered, so no inactive user accounts should be shown. I tried replacing 'attending_persons' with a method like they show in the link below, but that causes an error. https://docs.djangoproject.com/en/1.10/ref/contrib/admin/ class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title', 'view_birth_date') def view_birth_date(self, obj): return obj.birth_date view_birth_date.empty_value_display = '???' You can't do this with a fieldset So my question is: How do i display a filtered list to choose from? Thank you -
How to exclude multiple values of column using Django ORM?
I want to filter mytable & get rows where name does not contain '' or '-' values and for this purpose I have used below query but does not working. mytable.objects.exclude(name = ['','-']).order_by('name').count() returning 2000 all rows and whereas query mytable.objects.exclude(name = '').order_by('name').count() working perfectly and returning filtered 1460 results. Below one is my postgresql query which working perfectly and returning 1450 results excluding name values of ['','-']. select * from mytable where name != '-' and name != '' order by -id I tried to search online but not able to find answer. -
How to exclude data from a queryset in a single query in django according 2 independant fields in another related table in one to many condition
There are 2 models, transaction and payout. There will be one transaction record and 2 payout record. There are 2 flags in the payout record, Status & Referral. I need to get the transaction record which has The payout record Status = True and Referral = False I have tried the following queryset = queryset.exclude(payout_related_name__referral=Fasle, payout_related_name__status=True) This code is excluding the record as per first condition not according to both case combined -
getting error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty in django
When i try to run django, i am getting error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty , there is already SECRET_KEY exist in settings.py file SECRET_KEY = 'g1tmo148kxtw#^obw&apoms%n=&4g+2qi1ssuc$v3(fig-he4u' still i am getting the error, can anyone please help me how to resolve this issue ? -
How Django to Hot Reload Uwsgi every workers Singleton value?
I want to hot reload my server, I have a Singleton Object, I want to change some value and become effective to each workers. I try to use open an api to access my edit, but It only refresh "that" workers singleton, the other is same the old one Is there has anyway can guide me? like @uwsgidecorators.postfork but It just suit for start workers. -
Why My Django Admin Stacked Inline is Not Working
Currently I am Using admin.StackedInline in my DoctorAdmin class But when I Use inlines = [DoctorAdminInlines] in may DoctorAdmin Class it will gives me an error, 'NoneType' object is not subscriptable and Even I am not be able to use my model fields in my list_display Here is my StackedInline Class Which I am Using class DoctorAdminInlines(admin.StackedInline): model = Doctor form = select2_modelform(Doctor) exclude = ('total_online_consultancy','emergency_type','consultation_type','total_visit','age','service_zone',) class Media: if hasattr(settings, 'GOOGLE_MAPS_API_KEY') and settings.GOOGLE_MAPS_API_KEY: css = { 'all': ('/static/admin/css/location_picker.css',), } js = ( mark_safe("https://maps.googleapis.com/maps/api/js?key={}&libraries=places".format(settings.GOOGLE_MAPS_API_KEY)), '/static/admin/js/doctor_location_picker.js', 'http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js', '/static/admin/js/dates.js' ) and here is my Doctor Admin in Which I am using this Aboved StackAdminInline class DoctorAdmin(admin.ModelAdmin): class Media: from django.conf import settings media_url = getattr(settings, 'STATIC_URL') css = {'all': (media_url+'custom.css',)} # inlines = [DoctorAdminInlines] form = UserCreationForm list_display = ['doctor', 'email', 'created_at', 'updated_at',] list_filter = ('created_at',) list_display_links = ('doctor','email',) search_fields = ('username',) list_per_page = 10 def save_model(self,request,obj,form,change): from django.conf import settings from django.core.mail import EmailMessage subject = 'New Registration Of Doctor !!' from_email = settings.MAIL_FROM forgot_email_content = """<html><body><p>Hi {customer_name},<p>Your Account is created please use this username: {username} and password: {password} </p> <br /><br />Thanks""" html_message = forgot_email_content.format(customer_name=form.data.get('email'),username=form.data.get('email'),password=form.data.get('password')) message = EmailMessage(subject, html_message, from_email, [form.data.get('email')]) message.content_subtype = "html" message.send() return super(DoctorAdmin,self).save_model(request, obj, form, change) def … -
ModuleNotFoundError: No module named 'employee.urls'
While I'm trying to add a urls configuration in my urls.py file, I'm getting an error like ModuleNotFoundError: No module named 'employee.urls' and OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('employee/',include("employee.urls")) ] directory and file path -
Unexpected Django ORM behavior
I have a function, which must make things according to its name, but it works weird for me. def get_or_create_artists_by_metadata(metadata: Dict[str, str]) -> List[Optional[Artist]]: if artists := metadata.get('artist'): artists = parse_artists_from_string(artists) # returns list of strings try: existing = Artist.objects.filter(title__in=artists) # 1 except Exception as err: log.exception('Database error!') log.exception(err) return [] new_artists_list = list(set(artists) - set(itertools.chain(*existing.values_list('title')))) objs = [Artist(title=artist) for artist in new_artists_list] try: new_artists = Artist.objects.bulk_create(objs) # 2 except Exception as err: log.exception('Error during artists creating!') return [*existing] result = [*existing] if new_artists: # 3 result.extend(new_artists) return result else: return [] For instance, I have 2 strings in artists var. On the step 1 I have nothing at first, empty QuerySet. Then on the step 2 I create new artists and at the same time I have some entries in existing var! So on the step 3 I have true, extend result, and there are 4 entries already. Please, explain me this behavior and how should I manipulate this. -
getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python
i am new here in django python, right now i am working with rest api, so i have created new app trialrisk, first i have added my app in settings.py file, after then when i am trying to add url in urls.py file i am getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python, here i have added my whole code and my folder structure, can anyone please look my code and help me to resolve this issue ? Folder Structure settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'trialrisk', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('/', include('trialrisk.urls')) ] -
how to login in django from custom model
This is my table of register user photo This is model.py class SignupUser(models.Model): name = models.CharField(max_length=100) username = models.CharField(max_length=20) email = models.CharField(max_length=100) password = models.CharField(max_length=20) def __str__(self): return self.username this is my views.py for login my account page through this register user def login_page(request): ''' what code i write here ?? ''' context = {'form': SignupForm} return render(request, 'signup.html', context) please solve my views.py code on my login_page method .What i write here to login in this user profile ? -
How to integrate Flutterwave payment gateway
Does anyone know how to use forloop to get the total cost of product display in Flutterwave? I was able to integrate Flutterwave, but the total cost of my product added to cart is not showing in Flutterwave. -
I am unable to start Gunicorn on ec2 for Django
I am currently trying to set up my django website on ec2. If I run gunicorn --bind 0.0.0.0:8000 website.wsgi:application the website runs as long as I specify port 8000 at the end of the URL. I do not want to have to do this so my end goal is to use nginx. I created my gunicorn.service file via the following command: sudo nano /etc/systemd/system/gunicorn.service Its contents are as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=home/ubuntu/Fantasy-Fire/website ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Fantasy-Fire/website/website.sock website.wsgi:application [Install] WantedBy=multi-user.target When I run sudo systemctl start gunicorn I get the following error: Failed to start gunicorn.service: Unit gunicorn.service is not loaded properly: Exec format error. See system logs and 'systemctl status gunicorn.service' for details. The details given via the gunicorn.service are Nov 29 04:34:13 ip-172-31-27-152 systemd[1]: /etc/systemd/system/gunicorn.service:8: Working directory path 'home/ubuntu/Fantasy-Fire/website' is not absolute. I am pretty certain the file path is absolute so I can't seem to find what the issue is. Please let me know if you need any info about my file structure. -
Convert SOAP API(XML) to Rest API (JSON) and visa versa in python
I'm new in SOAP API, i trying to use soap API of simple calculator from "http://www.dneonline.com/calculator.asmx" and my back end work on REST API. Now my problem is first get SOAP API and convert this on JSON and work on REST API and also for user request also comes to JSON form, convert this to SOAP API and send to server. -
google_app_engine runtime process for the instance running on port 46765 has unexpectedly quit
I have successfully installed on Ubuntu digital ocean server but it's automatically close in time interval after 1 or 2 days and need to start again and again on server i have check process on 8000 port is running but on server 8080 its is not working error was port close unexpectedly. I am attach Error image so understand you can understand easily. Error: the runtime process for the instance running on port 46765 has unexpectedly quit ERROR 2019-11-28 05:52:48,879 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response response = middleware_method(request, response) File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response if response.status_code == 404: AttributeError: 'tuple' object has no attribute 'status_code' ERROR 2019-11-28 14:25:50,789 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response response = middleware_method(request, response) File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response if response.status_code == 404: AttributeError: 'tuple' object has no attribute 'status_code' -
ImportError: cannot import name 'views' from 'greetingsApp.views' (Use multiple app in one project)
I am beginner in django, simply i tried to use multiple app in one project i got error: ImportError: cannot import name 'views' from 'greetingsApp.views' project description: /thirdProject /greetingsApp /views.py from django.http import HttpResponse def greetings_view(arg): return HttpResponse(' Good Morning....') /timeApp /views.py from django.http import HttpResponse import datetime def time_view(arg): time = datetime.datetime.now() save = ' Current Server timr'+str(time)+'' return HttpResponse(save) /thirdProject /urls.py from django.contrib import admin from django.urls import path from greetingsApp.views import views as v1 from timeApp.views import views as v2 urlpatterns = [ path('admin/', admin.site.urls), path('greetings/', v1.greetings_view), path('time/', v2.time_view), ] /settings.py INSTALLED_APPS = [ 'django.contrib.admin', ........ 'greetingsApp', 'timeApp', Run: ] F:\djangoProject\thirdProject>py manage.py runserver Error: File "F:\djangoProject\thirdProject\thirdProject\urls.py", line 18, in from greetingsApp.views import views as v1 ImportError: cannot import name 'views' from 'greetingsApp.views' (F:\djangoProject\thirdProject\greetingsApp\views.py) -
Django how to do a conditional redirect after POST?
I have a form that displays some of the fields in the user profile among other things. In this form the fields from the profile are disabled. If the details are outdated the user can go to the edit profile view and update the details. For this, I included a button in the template of the form. After updating the profile I want the user to return to the form. This last part is the one I am having problems with. The link to edit the profile from the form looks like: <a class="btn btn-outline-info" href="{% url 'profile'%}?next={% url 'submission_resume' %}">Edit Profile</a> This is how the url looks comming from the form: http://127.0.0.1:8000/users/profile/?next=/submissions/resume/ The problem is that in the edit profile view I do not know how to implement the conditional redirect: def profile(request): """ View and edit the profile. It requires user to be login """ if request.method == 'POST': form = UserModifyForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, f'Your account has been updated!') #??? if next in url go back to the form ??? #??? return redirect(???) ??? #??? else: ??? return redirect('profile') else: form = UserModifyForm(instance=request.user) #--> Dict for template with the forms context = { 'form': form, … -
Django custom log only record custom message not include error message
I have create a custom log, and I only want to store custom message. However when this file have some bugs, this log will also record error log. Anyone know how to achieve this? (I have separate system error log to different file.) from django.http import HttpResponse import logging logging.basicConfig(filename='storage/log/trademoney.log', level=logging.INFO, format='%(asctime)s : %(message)s') def set_log(request): logging.info('ohla') <--custom log return HttpResponse(ohla) <--system error (undefined) log (I want this custom log only store info I setup, I don't want system error log) 2019-11-29 12:22:52,888 : ohla <----I only want this log (I don't want system error log) 2019-11-29 12:22:52,895 : Internal Server Error: /blog/zh_TW/log/ Traceback (most recent call last): File "C:\Python3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\xampp\htdocs\python\demo\blog\modules\log.py", line 7, in set_log return HttpResponse(ohla) NameError: name 'ohla' is not defined 2019-11-29 12:22:52,897 : "GET /blog/zh_TW/log/ HTTP/1.1" 500 27 -
Opencv Camera Face Detection with Django
I tried to detect face with opencv camera and save the detected face image to database with opencv and django, but it does not seem to work. Any suggestion? while True: # Read the frame _, img = cap.read() # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect the faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw the rectangle around each face for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) # Display cv2.imshow('img', img) -
How exactly does django 'escape' sql injections with querysets?
After reading a response involving security django provides for sql injections. I am wondering what the docs mean by 'the underlying driver escapes the sql'. Does this mean, for lack of better word, that the 'database driver' checks the view/wherever the queryset is located for characteristics of the query, and denies 'characteristics' of certain queries? I understand that this is kind of 'low-level' discussion, but I'm not understanding how underlying mechanisms are preventing this attack, and appreciate any simplified explaination of what is occuring here. Link to docs -
Unsure of how to manage email configurations
I am attempting to create Reset Password functionality using Djoser. I am successfully hitting my API's auth/users/reset_password/ endpoint, which is then sending an email as expected. But the problem is occurring in the content of the email. It is sending a redirection link to my api, rather than to my frontend. Please note, any <> is simply hiding a variable and is not actually displayed like that Here is an example of what the email looks like: You're receiving this email because you requested a password reset for your user account at <api>. Please go to the following page and choose a new password: <api>/reset-password/confirm/<uid>/<token> Your username, in case you've forgotten: <username> Thanks for using our site! The <api> team The goal with this email is to send the user to the /reset-password/confirm/ url on my frontend, not on my api, which is currently occurring. Here are my DJOSER settings: DJOSER = { 'DOMAIN': '<frontend>', 'SITE_NAME': '<site-name>', 'PASSWORD_RESET_CONFIRM_URL': 'reset-password/confirm/{uid}/{token}', } The expected behavior is for the DOMAIN setting to alter the link that is being placed in the email, but it is not. I can't seem to find reference to this particular problem within the docs. Any help here would …