Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to format timzone.now() in Django in models.py?
I have a DateField in my models.py, which is set to timezone.now(). How can I change the date format that it is saved in? I appreciate that I can change it in the template easily enough, but this won't solve my particular problem. I have tried adding the below into my settings.py, but nothing has changed. USE_L1ON = True DATETIME_INPUT_FORMATS = ('d-m-Y') I would be very grateful for any help here. -
Turbolinks + Django: Page is requested multiple times when the "prevoius" button is pressed in the browser
I have finally got Turbolinks to work fine and dandy and handle all of the requests going through my application (PJAX). However, the main issue that arises is the fact that the "back/previous" button is broken. The normal page request when normally navigating through a turbolink should be as follows: Normal Network activity However, when pressing on the "previous" button all hell gets loose as follows: When clicking the previous button in the browser The page named "11" should load one time only. However, it loads multiple times for some reason. I know turbolinks is famous with the Rails framework so any answers are welcome. Also, I'm inexperienced with how caching works with Turbolinks, so if this is a cache issue please refer me on how to mitigate it. -
Form data is not transferring from views.py to html table in Django
I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API and it's working too. But I am facing an issue in transferring back the form data in the HTML table. It's not going back to the table at all. Without the fetch API form submission, the data are getting transferred back to the HTML table as it's supposed to. But I am not able to do the same after implementing fetch API in my app. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST.get['dropdown_val'] value=request.POST.get['val'] print(options_value,value) context={"options_value":options_value, "value" : value} return render(request, 'index.html',context) **index.html" <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" … -
how to pass file from local storage to html - django
so i want get my file from local storage to show in html using django. but i don't know how to get it. the file is audio mp3. i was using form NOT MODALS. i need reference of example code. if you need my code form.py here's : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) i was try using formset, but i don't know how to use it. here's my views.py code : def song(request): songmp3 = formset_factory(Audio_store) if request.method == 'POST': formset = songmp3(request.POST, request.FILES) if formset.is_valid(): # do something with the formset.cleaned_data pass else: formset = songmp3() return render(request, 'homepage.html', {'formset': formset}) -
How do I make text "bold" in email body in python?
How can I make text bold in the email body in python? I am using the following code to send mail : from django.core.mail import send_mail send_mail(subject, message, sender, [email], fail_silently=False) I want to make some important text bold. Using the following code I have received the whole string as a message. message = " Hi Customer,<br> Your OTP is <b>****</b>" But it works when I try \n as <br>. What can I do to make the text bold? -
Custom form in Django shows ids instead of string
guys! I'm struggling with django forms. Default ones represent models as expected (returning __ str __ values). However, my custom form (Event_form_for_Admin) shows ids instead of string in admin panel and on the site. What am I missing? models.py class Position(models.Model): name = models.CharField(max_length=800) level = models.CharField(max_length=50) def __str__(self) -> str: return f'{self.level} {self.name}' class Person(models.Model): name = models.CharField(max_length=300) def __str__(self) -> str: return self.name class Event(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) position = models.ForeignKey(Position, on_delete=models.RESTRICT) def __str__(self) -> str: return f'{self.action} {self.position}' forms.py class Event_form_for_Admin(forms.ModelForm): person = forms.CharField(widget=forms.TextInput, label='Name') position = forms.CharField(widget=forms.TextInput, label='Position') class Meta: model = Event fields = ['person','position'] output on site as well as in admin panel: -
Allow all ips in CSRF_TRUSTED_ORIGIN django
How to allows all/ any ips in CSRF_TRUSTED_ORIGIN of django Backend django restapi are running and frontend is on angular in one system and we are trying to access with system ip in another system, i am able to access frontend and while accessing backend POST method API's are not working it's showing not found in card trusted origins. In settings.py i made get dynamic ips. import socket def get_ipaddress(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) return "http://"+ip_address+":4200" ALLOWED_HOSTS=["*"] CSRF_TRUSTED_ORIGINS=[get_ipaddress()] Tried to use csrf_excempt , but it's not working. Version of django4.0.1, Angular 16 -
How do I access image URL from one django model to another? How do I put it on a template?
I am using two models Forum and User. User model.py: class User(models.Model): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) profile_img = models.ImageField(upload_to='images/', null=True, blank=True) I wanted to access the url of User's profile_img and display it to my template in Forum. How should I code this in my Forum's model.py? -
Cannot populate elasticsearch index using ```python manage.py search_index --rebuild``` in django using docker
I am using django, elasticsearch and postgresql from docker in separate containers. When I try to run python manage.py search_index --rebuild, I get the following error: Traceback (most recent call last): File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 22, in <module> main() File "C:\Users\ashut\Desktop\ramrobazar\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 166, in handle self._rebuild(models, options) File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 143, in _rebuild if not self._delete(models, options): File "C:\Users\ashut\Desktop\ramrobazar\venv\lib\site-packages\django_elasticsearch_dsl\management\commands\search_index.py", line 132, in _delete "the '{}' indexes? [y/N]: ".format(", ".join(index_names))) TypeError: sequence item 0: expected str instance, NoneType found Everything else works fine. When I run docker-compose up, all of my containers i.e. the postgresql database, web service and the elasticsearch containers start running without any problems. The website starts running on localhost:8000 and I can also create new users from the admin panel. So, the website and database are working fine. On localhost:9200, I can see the following JSON: { "name" : "4336b15c63fa", "cluster_name" : "docker-cluster", "cluster_uuid" : "a_long_string", "version" : { "number" : "7.14.2", "build_flavor" : "default", "build_type" : "docker", "build_hash" … -
'Access is denied' on wrong port select
could not open port 'COM#': PermissionError(13, 'Access is denied.', None, 5) actually this is not a mistake, I want to show window alert message when someone select wrong port if anyone knows please help def add_charger_view(request): if request.method == 'POST': port = request.POST['port'] port = port.split().pop(0) baud_rate = request.POST['baud_rate'] serial.Serial(port, baud_rate) return render(request, "charger.html", context) all things good, connection is ok but shows this error in not ok -
user registered but cannot login django
I tried to implement customized user login/ Registration in django. but only one user can be logged in but not anyother user are logged in. Registration area looks fine cause user can register easily. These are my codes I guess there is problem with CSRF token but i dont know where to update it In view Register def registerPage(request): form = UserForm() if request.method == 'POST': print(request.POST) form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.user_name = user.user_name.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'An error occured duing registration!!') return render(request, 'base/login_register.html', {'form': form}) My Views Login def loginPage(request): page = "login" if request.user.is_authenticated: return redirect('home') if request.method == "POST": email = request.POST.get('email').lower() password = request.POST.get('password') try: user = NewUser.objects.get(email=email) except: messages.error(request, 'User doesnot exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) print("mess going on here!") return redirect("home") else: messages.error(request, "Email or Password doesnot exit") context = {'page': page} return render(request, 'base/login_register.html', context) Forms.py from tkinter import Widget from django.forms import ModelForm from .models import NewUser class UserForm(ModelForm): class Meta: model = NewUser fields=['email','user_name','first_name','country','address','year_in_school','about','avatar'] def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update({'class': 'form-control'}) # self.fields['email','user_name','first_name','country','address','year_in_school','about'].widget.attrs.update({'class': 'form-control'}) self.fields['user_name'].widget.attrs.update({'class': 'form-control'}) self.fields['first_name'].widget.attrs.update({'class': 'form-control'}) self.fields['country'].widget.attrs.update({'class': 'form-control'}) self.fields['address'].widget.attrs.update({'class': 'form-control'}) … -
The directory 'D:\dj\staticfiles' in the STATICFILES_DIRS setting does not exist
This is my settings.py I already created a folder 'staticfiles' in the project folder. How can I solve the error -
'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)])
I am building a simple gallery image app and using django-rest-framework. I am saving two model instances, which I am rendering as nested response and also saving throughh nested json. But when I click on Post from api admin then it is showing 'Image' instance expected, got OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]) I think the problem is in the create() function. I have also tried modifying it but it is still not working and showing the same error. models.py class Gallery(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) class Image(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name="images") text = models.CharField(max_length=300) serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = "__all__" class GallerySerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = Gallery fields = "__all__" def create(self, validated_data): created = Gallery.objects.create(poll=1) created.images.set(validated_data['images']) return created my response which I am saving { title: "First Gallery", images : [ { "gallery": 1, "text": "First Image" } ] } And When i print validated_data like :-: print(validated_data['images']) then it is showing [OrderedDict([('text', 'First Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Second Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Third Image'), ('gallery', <Gallery: First Gallery>)]), OrderedDict([('text', 'Fourth Image'), ('gallery', <Gallery: First Gallery>)])] I have just started learning … -
How can i edit uploaded mp3 files by user
I want my django app to do. User Uploads mp3 file user inputs time range my app trims the mp3 file to the range given avail result mp3 to user -
Django: How to automatically update a model instance everytime another model instance is updated
In online shop projects, I have a model called Order (and this model stores order instances) and a model called Points. The model Points stores bonus points which are collected by the users when they make orders. But the order may be cancelled, so I would like to be able to monitor when an order is being cancelled (model Order instance's status being changed to "cancelled") in order to take the points away. How can I do that? -
Django Imagefield renaming works only every other time
I'm attempting to upload a profile picture to a django model which should always be named pic.jpg. Old pictures are deleted using django_cleanup. This works every other time. I upload an image and it's saved as pic.jpg, then upload a different one and it's saved as pic_{randomchars}.jpg (i.e pic_wCU5xwv.jpg). def rename_pic(instance, filename): return os.path.join("api/media/me/", filename) pic = models.ImageField(upload_to=rename_pic) def save(self, *args, **kwargs): try: # Opening the uploaded image img = Image.open(self.pic) output = BytesIO() img = img.convert('RGB') # after modifications, save it to the output img.save(output, format='JPEG') output.seek(0) # Set field to modified picture self.pic = InMemoryUploadedFile(output, 'ImageField', "pic.jpg", 'image/jpeg', sys.getsizeof(output), None) except Exception as e: print(e) print(self.pic.name) # Always prints pic.jpg super(MyData, self).save() # Error happens in this line print(self.pic.name) # Prints api/media/me/pic.jpg and api/media/me/pic_{randomchars}.jpg alternating The error happens somewhere in the super(MyData, self).save() line, as the file has the correct name before it's called. -
deleting a post in django
hi ive read some of similar posts but couldn't find same problem. i wrote a code to delete post and when i press delete it shows 404 error but when back to home post is still there views: def delete_music_view(request,music_id): #view for deleting music my_object = add_music.objects.get(id=music_id) if request.method == 'POST': my_object.delete() return redirect('pages:home') context = {'my_object':my_object} return render(request,'pages/delete_music.html',context) url: app_name = 'pages' urlpatterns = [ path('',views.home,name='home'), path('add_music/',views.add_music_view,name='add_music'), path('musics/<int:music_id>',views.musics_view,name='music_page'), path('musics/<int:music_id>/delete',views.delete_music_view,name='delete_music'), ] template: {% extends 'pages/base.html' %} {% block content %} <form action="." method='POST'> {% csrf_token %} <p><input type="submit" name="delete" value="yes"><a href="../../">cancel</a></p> </form> {% endblock %} can u pls tell me whats wrong? -
Django: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
I see this is a common problem and understand the idea is that you cannot add many to many unless it is created first. I have seen multiple solutions for this but unsure which one to use. Models.py class Concert(models.Model): venue = models.CharField(max_length=200, null=True) concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') date = models.DateField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=200, null=True) user = models.ManyToManyField(USER_MODEL, related_name="concerts", null=True) song = models.ManyToManyField("Song", blank=True, null=True) def __str__(self): return str(self.concertid) + " " + str(self.venue) + " " + str(self.date) Views.py def log_concert_and_song(request, concertdict): if request.method == "POST": Concert_save = Concert( concertid=concertdict['id'], date=concertdict['eventDate'], venue=concertdict['venue'], city=concertdict['city'], country=concertdict['country'], user = request.user ) Concert_save.save() Should I use the User model? -
modify the model to take the information from the another model
I have two models the first form is for users and the second is for candidates when I register an account that is done using the first form and when I enter to edit the account information as the name and date of birth I need to rewrite this information back knowing that I put it during the account registration, is there a way to modify the second model form to take the information from the first model the first models : from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField GENDER_CHOICES = ( ('M', "Male"), ('F', "Female"), ('O', "Other"), ) class User(AbstractUser): username=None email=models.EmailField( verbose_name='email address', max_length=255, unique=True ) date_of_birth = models.DateField(default='1990-01-01') gender=models.CharField(max_length=1,choices=GENDER_CHOICES,blank=True) picture=models.ImageField( upload_to='img/users',null=True,verbose_name="" ) phone = PhoneNumberField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email the secound models : from django.db import models from accounts.models import User from django.utils import timezone from autoslug import AutoSlugField from django_countries.fields import CountryField from recruiters.models import Job from django.utils import timezone CHOICES = ( ('Full Time', 'Full Time'), ('Part Time', 'Part Time'), ('Internship', 'Internship'), ('Remote', 'Remote'), ) class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name='profile') full_name = models.CharField(max_length=200, null=True, blank=True) country = CountryField(null=True, blank=True) … -
Django: key error after setting the key with AJAX from JAVASCRIPT
I am using django to manage my site. I have a JAVASCRIPT event that update's the server with this an AJAX call: **script_x.js** $.ajax({ type: "POST", url: "my_url_to_server", headers: {'X-CSRFToken': csrftoken}, data: {}, success: function(response){alert(response);} }); On the server in the views, I set the "SESSION variable" once the JQUERY function fires: **views.py** def set_session_now(request): if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) request.session['my_key'] = 0 return HttpResponse('ok') and in the urls.py: path('set_session_now', views.set_session_now, name='set_session_now'), But once the process finishes; I only get "ok" sent from the server; but the session is not set; the server returns "Key Error: 'my_key'". Any help would be appreciated. -
How to populate field from the view django?
I am trying to populate a field on a template form in Django. I have tried to do it on the view as well as a value on the form template but no luck. Here is my work The outcome would be to populate username and email field from the resource model, but I am getting an UNIQUE constraint failed: auth_user.username error. Thanks forms.py class AdminRegistrationForm(UserCreationForm): is_superuser = forms.BooleanField(), password1 = forms.CharField( label="Password", widget=forms.PasswordInput) password2 = forms.CharField( label="Password Confirmation", widget=forms.PasswordInput) class Meta: model = User fields = ['password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if not password1 or not password2: raise ValidationError("Please confirm your password") if password1 != password2: raise ValidationError("Passwords must match") return password2 view.py def admin_registration(request, username): resources = Resource.objects.get(username=username) if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": resources = Resource.objects.get(username=username) admin_registration_form = AdminRegistrationForm(request.POST) if admin_registration_form.is_valid(): obj = admin_registration_form.save(commit=False) obj.is_superuser = True obj.save() user = auth.authenticate(username=[resources.username], password=request.POST['password1']) if user: auth.login(user=user, request=request) messages.success(request, "You have successfully registered") return redirect(reverse('index')) else: messages.error(request, "Unable to register your account at this time") else: admin_registration_form = AdminRegistrationForm() return render(request, 'registration/registration.html', { "registration_form": admin_registration_form, 'email': resources.email }) models.py class Resource(models.Model): ROLE = [ ('Analyst', "Analyst"), ('Team Manager', "Team Manager"), ('Quality Auditor', … -
OMR BubbleSheet Test Recognization
I'm handling my last homework for the university in Spain (Business Adminstration), and I decided create a system that the Teacher insert the Exam correct answer, then download a model to give to the students do the exam, and after recieve the exams, he uploads it and the system compare the correct answers with the answers that the students did. The model is this one: answers sheet model The model with correct answers: answer sheet correct Wrong answer exam: wrong answer exam I could develop the backend in Django, they can do everything before the test corrector. Of course I tried multiple ways (Bubblesheet OMR on google and we have a lot of people doing the same test using the same example: https://pyimagesearch.com/2016/10/03/bubble-sheet-multiple-choice-scanner-and-test-grader-using-omr-python-and-opencv/ ), I found more examples, but the most closer one was : Detect All Circles in an image (Optical Mark Recognition) using Python OpenCV , but not worked in my example file. Can someone help me please? Here you have the three options. The Idea is that the teacher will upload all the PDF files, then is transformed into img (i did it using pdf2image), and then the corrector system loop in all the images/pdf correcting and … -
Why some fields are not created while making migrations?
I have this two models in models.py class Bid(models.Model): bid = models.IntegerField(default = 0) user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "bid") def __str__(self): return f"Bid of {self.bid} from {self.user}" class AuctionListings(models.Model): name_of_item = models.CharField(max_length=32) description = models.CharField(max_length=400) owner = models.ForeignKey(User, on_delete = models.CASCADE, related_name="auctionlistings", default = None)** bid = models.ForeignKey(Bid, on_delete = models.CASCADE, related_name = "auctionlistings", default = None)** is_closed = models.BooleanField(default=False, blank=True, null=True) url = models.CharField(max_length=800) watchlist = models.ManyToManyField(User, blank=True, related_name="watch_listings") category = models.CharField(max_length=50) When i makemigrations: operations = [ migrations.CreateModel( name='AuctionListings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name_of_item', models.CharField(max_length=32)), ('description', models.CharField(max_length=400)), ('is_closed', models.BooleanField(blank=True, default=False, null=True)), ('url', models.CharField(max_length=800)), ('category', models.CharField(max_length=50)), ], ), migrations.CreateModel( name='Bid', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bid', models.IntegerField(default=0)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bid', to=settings.AUTH_USER_MODEL)), ], ), My Question is: Why Django did not create the fields: "bid" and "user" specified in models.py. -
when there is no Overlapping i am getting overlapping validation error
With thins code i can check overlappig but the problem when overlapping is not happening i am getting overlapping validation error. How i can solve this error. form.py for i in range(count): start = self.data.get(f'applicationdefinition_set-{i}-start', []) end= self.data.get(f'applicationdefinition_set-{i}-end', []) if (start > end_bbch) or (start == start): raise ValidationError( 'Overlapping Not Allowed' ) -
How can I integrate a website functionality to a mobile app and share same database
I'm creating a website using Django as a back-end and next I will make a native mobile app using Flutter, so how can I bond these together (share same database and funcionality)? Making what is called PWA (progressive web app)