Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
composite key not displaying orrecyl on django admin
I have an intermediary model betwen "estados" e "listaflor", the flora2estado uses a composite key- and a primary key to trick django not to throw errors at me-. When i click in one object at django admin i get this error: MultipleObjectsReturned at /admin/accounts/flora2estado/99/change/ get() returned more than one Flora2Estado -- it returned 5! my models.py class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'estados' class Familia(models.Model): familia_id = models.AutoField(primary_key=True) familia_nome = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'familia' class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, ) especie_id = models.IntegerField() flora2estado_id = models.AutoField( primary_key=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) admin.py admin.site.register(Flora2Estado) -
How to make a variable number of fields in django models?
I want to make a model of Grades of students and this model has a variable number of fields that I can change from the admin page. -
django: FileField model - 404
This is my first Django project and I have one problem. file1 is saved to media folder\files however when I try to download the file I'm getting 404. Any help is appreciated! 127.0.0.1:8000/about/files/2021/01/22/pyqt_tutorial_EB2ZapN.pdf models.py class Links(models.Model): file1 = models.FileField(upload_to = 'files/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) html {% for link in links %} <div class="links1"> <h3><a href = "{{ link.file1 }}">Download Link</a></h3> <p>{{ link.publish_date }}</p> </div> {% endfor %} urls.py> urlpatterns = [ path('admin/', admin.site.urls), path('about/', about, name = 'about') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py> # Media Folder Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Update: from the admin panel if I click on the link I can see it. Maybe In the {{ link.file1 }} url something need to be changed? -
How do I import a model from another app in Django?
So in my project book_letter, I have an app named contents. Inside it, I have a model named Book. As below. class Book(models.Model): objects = models.Manager() title = models.CharField(max_length = 30) author = models.CharField(max_length = 20) def __str__(self): return self.title And I have another app named recommendation, with a model named Recommendation. As below. from book_letter.contents.models import Book class Recommendation(models.Model): objects = models.Manager() source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE) However, when I run python manage.py runserver, I get an error saying ModuleNotFoundError: No module named 'book_letter.contents' I don't see what I've done wrong. Any ideas? Thanks :) -
Django: Group by foreign key then get max id from group
I'm looking to grab the latest message in a conversation. My conversation model has attributes id (primary key) and user1 and user2, which are both foreign keys to a User model. My message model consists of a conversation(foreign key) and message primary key. These both just return only the very latest message. Message.objects.values('conversation').latest('id') Message.objects.order_by('conversation').latest('id') Any recommendations for getting this query? -
Django access pk id in class
I have this site, and I want to be able to have views. When you go to url /post/int:pk it shows the post in more detail. When the user goes here, I want to add one to an field in models.py. Here is models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) people_read = models.IntegerField(default=0) # Add one to this data user_liked = models.ManyToManyField(User, related_name='user_liked') user_disliked = models.ManyToManyField(User, related_name='user_disliked') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) And views.py: class PostDetailView(DetailView): model = Post post = get_object_or_404(Post, pk=pk) post.people_read = post.people_read + 1 post.save() The problem with this is that it won't get the pk id. So how do I get the posts pk in an class, or is there another way to add to a models field when going to a url? Thanks. -
Add additional fields to form after click - the node before which the new node is to be inserted is not a child of this node
I have a form in which I need to add a button that will allow the user to add a new field. I'm trying to do it with javascript, but since I don't know much this language I'm lost with some concepts. The form I use is one where the data is completed in steps, and the fields I want to add are the following <div class="job-form row mb-3"> {% for form in add_trabajo %} <div class="col-md-6"> <label for="ref" class="">Nombre</label> {% render_field form.trabajo class="form-control" type="text" placeholder="Ej: Reparación de envolvente delantero" %} </div> <div class="col-md-2"> <label for="ref" class="">Descuento</label> {% render_field form.descuento class="form-control" type="text" %} </div> <div class=" col-md-2"> <label for="ref" class="">Precio</label> {% render_field form.precio class="form-control" type="text" %} </div> <div class="col-md-2 d-flex align-items-end"> <button id="addButton" type="button" class="btn-icon btn-icon-only btn btn-success p-2"><i class="pe-7s-plus btn-icon-wrapper"> </i></button> </div> {% endfor %} </div> I'm trying to add these fields after existing ones that are identical I already have the button and some code in javascript but it indicates the following error Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at HTMLButtonElement.addForm This is my javascript code let jobForm … -
Django File upload in model
Considering that we`ve got the model below: class Project(models.Model): file1 = models.FileField(upload_to='projects/', blank =True) file2 = models.FileField(upload_to='projects/', blank =True) file3 = models.FileField(upload_to='projects/', blank =True) file4 = models.FileField(upload_to='projects/', blank =True) file5 = models.FileField(upload_to='projects/', blank =True) How many file1 can we create? If I want to create severals files, I usually write my code this way: class File1(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) file = models.FileField(upload_to='projects/', blank =True) Instead to create severals models File1, File2, File 3, Is there a way to upload several file1 in Django using only the model Project? I mean to not have to create a model for each file1, file2, file3 if we need to upload several of them. Many Thanks, -
django project not working with apache2, working ok with inbuilt web server
I have a django project and working with the in-built webserver. I am trying to move it to apahce and having trouble.Would anyone please be able to help. My project structure is: home/p/prjct |-- setest | `-- wsgi.py | |-- manage.py |-- penve | |-- hello | |-- tsts penve is the virtual environment hello and tsts are apps. I have made changes in my apache2.conf and it looks like: WSGIScriptAlias / /home/p/prjct/setest/wsgi.py WSGIPythonHome /home/p/prjct/penve WSGIPythonPath /home/p/prjct <Directory /home/p/prjct/setest> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> DocumentRoot /home/p/prjct Listen 80 AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent Am I missing something. Thanks in advance for help. sp -
Django Email Token Sending Blocked
For a user registration, I try and send a url that the user has to click in order to register. This url contains a uid, and token. However, gmail seems to block emails from the specified email in settings.py when I try and send them. I think it's because my local address is used as the website for now and which is seen as 'less secure' but I am not exactly sure why. I know it has to do with the token because when I send an email with just text in the body, it does not pose an error. The error is shown as below: Here is the email body (note that when I simply change this to text, the email is sent): email_body = render_to_string('mainapp/acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) -
how do you add an avatar profile to django inbuilt forms?
How can you add a field to add images on a inbuilt Django form? Here is the code of my form.py: class CreateUserForm(UserCreationForm): password1 = forms.CharField( label="Password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Password'}), ) password2 = forms.CharField( label="Confirm password", widget=forms.PasswordInput(attrs={'class':'form-control form-control-user', 'type':'password', 'align':'center', 'placeholder':'Confirm Password'}), ) class Meta(UserCreationForm.Meta): model = get_user_model() widgets = { 'username': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Username'}), 'first_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'First Name'}), 'last_name': TextInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Last Name'}), 'email': EmailInput(attrs={'class': 'form-control form-control-user', 'placeholder': 'Email Address'}), } fields = ['username', 'first_name', 'last_name', 'email'] -
VSCode pytest test discovery fails when debugging Django tests
I'm trying to debug my first django test, but VSCode is returning: Ran 0 tests in 0.000s. On the other hand, when I use an integrated git bash (I'm using a windows OS) in VSCode terminals or externally, it returns: Ran 1 test in 0.0014s. It also echoes FAILED and a traceback for a valid error within the test. My vscode launch.json: { ... "configurations": [ ... { "name": "Django Tests", "type": "python", "request": "launch", "program": "${workspaceFolder}\\testprojectname\\manage.py", "args": [ "test" ], "django": true, } ] } My vscode settings.json: { "python.pythonPath": "C:\\Users\\user\\.virtualenvs\\backend-Vg-KBKTA\\Scripts\\python.exe", "python.testing.pytestEnabled": true, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": false, "python.testing.pytestArgs": [ "testprojectname" ] } Note that C:\Users\user\.virtualenvs\backend-Vg-KBKTA\Scripts\python.exe is a valid path to the pipenv shell [(1) it is echoed when I type in the bash: pipenv --venv (2) it works when I launch the django debugger] So far, I've tried: Updating my pytest according to VSCode pytest test discovery fails Changing around the name of my tests.py file to test_example.py according to Pytest - no tests ran Changing the class of the tests to prefix with Test_ according to the same link in (2) This is what the test currently looks like class Test_Contacts(unittest.TestCase): def test_create_contact_message(self): """Create a new contact message.""" … -
Postgres - can't acces database, no acces
I am trying to acces my postgres database but I am having permission denied error. I created database + table(was created in python but it is there): sudo -u postgres psql postgres=# create user lukasz1 with encrypted password '<password>'; postgres=# create database mydatabase owner lukasz1; So far so good: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges ------------+----------+----------+-------------+-------------+----------------------- mydatabase | lukasz1 | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =Tc/lukasz1 + | | | | | lukasz1=CTc/lukasz1 postgres | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | template0 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | pl_PL.UTF-8 | pl_PL.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) and lukasz1 is an owner of mydatabase. But when I try to connect it I am having permission denied. I can't even select from my table to view it as permission is denied: mydatabase=> select article_id from articles; ERROR: permission denied for table articles I checked multiple anwers to simmilar questions and tried checking user valid_until and got an empty values in that column: mydatabase=> select usename, valuntil from … -
Django Image upload not POSTing
I am trying to let a user upload and change their picture. Currently the form displays the current picture for the user without any issues, but I seem to have messed something when it comes to the upload part since the upload is not working (no error messages). Also, is it possible to create a custom image form? Currently, this makes use of Djangos default one which is not that style-friendly. Views.py @login_required def edit(request): if request.method == "POST": FormImage= UserProfileForm(request.POST, request.FILES, instance=request.user) if FormImage.is_valid(): FormImage.account_id = request.user.id FormImage.save() return HttpResponseRedirect(request.path_info) else: imageForm = UserProfileForm(instance=request.user) return render(request, 'accounts/info.html', { "FormImage": FormImage, }) Forms.py class UserProfileForm(UserChangeForm): FRUIT_CHOICES = ( ('Banana', 'Banana'), ('Orange', 'Orange'), ('Apple', 'Apple'), ) fruits = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) class Meta: model = Account fields = ( 'fruits', 'profile_picture', ) Template <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <label class="col-lg-3 col-form-label form-coantrol-label">Change picture</label> <div class="col-lg-9"> {{ FormImage.profile_picture }} </div> <div class="form-group row"> <div class="container"><input class="btn btn-primary" type="submit" value="Save profile"></div> </div> </form> My model field for profile pic profile_picture = models.ImageField(default="default.png", null=True, blank=True) -
How register and login in django in same time with class based views?
I have a simple registration view, i want to create a view can register user and login him at same time. my code not working, what should do i do to do it? my views.py: class user_register(SuccessMessageMixin,CreateView,): model = User template_name = 'register.html' success_url = reverse_lazy("company:home") form_class = UserRegisterationForm success_message = "You registered successfully." def form_valid(self,form): user = authenticate(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password')) if user is not None: login(self.request,user) return redirect('company:home') return super().form_valid(form) -
How to pass the product id dynamically to the Django view?
How to change (id=3) automatically? When I click on a product to get a detailed view, the slug in the url is correct, but the displayed data doesn't match. views.py works fine: def product_detail_view(request, slug_text): obj = Product.objects.get(id=3) context = { 'object': obj } return render(request, 'store/product.html', context) urls.py works fine: urlpatterns = [ path('<slug:slug_text>/', views.product_detail_view, name ="product"), ] -
Duplicated querysets in each view - django
I have a few querysets that I need in each of my view. I'm wondering if there is a better way that duplicating those in every single view. Querysets results are the same for every view They look like this Company_user = Company.objects.get(User = request.user) User_info = User_info.objects.get(User = request.user) Groups_user = request.user.groups.values_list('name',flat = True) Sales_company = Sales.objects.filter(Company = Company_user) -
Django + https on localhost
I have files of TLS certificate(.crt) and key(.key) How can i add them in settings.py and run localhost with https( it is need to add them as text variables not path to these files)? Thanks in advance! -
python - django extra_context wont show
I have a form in ListView view using FormMixin that form takes a string lastname and querys to take a queryset of Account object, I want that Queryset on my template via extra_context. The form works and I have the queryset that I want, I pass it into self.extra_context and I can see it on console with print BUT it dosent show in my template. Im feeling stacked, please help me if tou can. def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): lastname = form.cleaned_data['lastname'] lastname = valuateLastname(lastname) self.extra_context['operators'] = Account.objects.filter(is_active=True, department=self.request.user.department, last_name__contains=lastname) print(self.extra_context['operators']) return super(DepartmentFilesListView, self).form_valid(form) In my template I can see anything else is in my self.extra_context but anything Im tried to pass in my form_valid function doesnt shown. It is like my extra_context cant update in this function. -
(Django - Javascript) Timer javascript and datetime python variable in html template
I've found a timer countdown in javascript online and it works fine... I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)... These are my piece of codes: views.py import datetime auction = Auction.objects.get(id=id) endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S") startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") template.html <script> // Set the date we're counting down to var countDownDate = new Date("{{endDateFormat}}").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date("{{startDateFormat}}").getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + … -
Django custom command to write a file without debug logging
I have a Django custom command to write csv file. In the code, I use writer = csv.writer(sys.stdout, lineterminator=os.linesep). When I run it with python manage.py write_csv>sample.file, it contains the file content and debug information, like CDLL(libgeos_c.so.1) Library path: 'libgeos_c.so.1' DLL: <CDLL 'libgeos_c.so.1', handle 5609f58baeb0 at 0x7f03df6b2c88> Trying CDLL(libc.so.6) Library path: 'libc.so.6' DLL: <CDLL 'libc.so.6', handle 7f03ea069450 at 0x7f03df6b2b70> System check identified some issues: and also the part of logging: logging.info('finish uploading') is in the file. Is there anything I can do to prevent those debug information write to file? -
Multiprocessing.Pool runs only one process
I have a Django project and I must fill/update the database with data from an external API. For every user, I must update the values for every minute of every day fetched by the external API. As you understand this is a time-consuming process if I pass multiple months. Please note that I make a call for each day, and process the data of the fetched json. After a specific number of requests, I must wait one hour. With all that in mind, I prepared a script that did all the work but it was taking ages to complete so I decided to proceed with multiprocessing. There is a method user_sync(day_list, user) that handles everything and works perfectly. and here are the lines of code that initiate multiprocessing. user_list = User.objects.filter(username__startswith='US') start_date = datetime.datetime(2020, 6, 28, 0, 0, tzinfo=pytz.UTC) end_date = datetime.datetime(2021, 1, 20, 0, 0, tzinfo=pytz.UTC) day_list = create_day_list(start_date, end_date) pool = multiprocessing.Pool() try: part = partial(user_sync, day_list) pool.map(part, user_list) pool.join() except Exception as e: print(e) pool.close() finally: pool.close() print('FINISHED') To my understanding, it should run multiple user_sync methods for every user in parallel but it doesn't Any help or point to the right direction would be much appreciated. -
Why doesn't HTML input type range work in Django
Am trying to play a song with the input type range in html. I made my own music player with HTML and javascript and when django return's a song, javascript handles it and plays it in the player. It loads the songs and even play it but the range doesn't work. I don't think i should use form widgets range since am not trying to submit a form. Am just playing a song. I did the same thing before in Flask and the range worked but in django it's not working. So am no sure if django support input type. I did alot of research i didn't get an answer so am stuck Here are the songs.(When the image is clicked the song plays) {% for song in playlist %} <div class="card" style="width: 17rem; border: none; margin-right: 20px;"> <img src="{{song.song_img.url}}" width="300" height="300" id="img" class="card-img-top" alt="..." onclick="add_data('{{song.id}}','{{song.song_name}}' ,'{{song.song_path.url}}')"> <div class="card-body"> <h5 class="card-text" id="song" ><a href="{{song.song_path.url}}" style="color: black; text-decoration: none; cursor: pointer;">{{song.song_name}}</a></h5> </div> </div> {% endfor %} Here is the html player <div class="own" id="own" style="display: none;"> <div class="buttons"> <div class="prev-track" onclick="prevPlay()"> <i class="fa fa-step-backward fa-2x"></i> </div> <div class="playpause-track" onclick="play()"> <i class="fa fa-play-circle fa-4x" id='pause'></i> </div> <div class="next-track" onclick="nextPlay()"> <i class="fa fa-step-forward … -
UserCreationForm don't return ValidationError
I don't understand why this form don't raise the ValidationError if the input don't contains only letters, what is wrong?, I tried to follow the steps in order to make a custom validation for these inputs but it seems that is not in the right way? class UserRegistrationForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(), help_text='Enter a help text ex: name@example.com') first_name = forms.CharField(widget=forms.TextInput(), help_text='Enter just letters') last_name = forms.CharField(widget=forms.TextInput()) marketing_email = forms.BooleanField(widget=forms.CheckboxInput(), required=False) accept_terms_and_conditions = forms.BooleanField(widget=forms.CheckboxInput()) class Meta: model = User fields = [ 'email', 'username', 'first_name', 'last_name', 'password1', 'password2', 'marketing_email', 'accept_terms_and_conditions' ] error_messages = { 'first_name' : _('First name can contain only letters'), 'last_name' : _('Last name can contain only letters') } def clean_first_name(self): first_name = self.cleaned_data.get('first_name') if not first_name.isalpha(): raise forms.ValidationError( self.error_messages['first_name'], code='first_name_invalid' ) return data def clean_last_name(self): last_name = self.cleaned_data.get('last_name') if not last_name.isalpha(): raise forms.ValidationError( self.error_messages['last_name'], code='last_name_invalid' ) return data template: <div class="form-row"> <div class="form-group col-md-6"> <label for="firstName">First name</label> {% render_field user_update_form.first_name class="form-control" placeholder="John" id="firstName" %} {% for error in user_update_form.first_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} </div> <div class="form-group col-md-6"> <label for="lastName">Last name</label> {% render_field user_update_form.last_name class="form-control" placeholder="Hanks" id="lastName" %} {% for error in user_update_form.last_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} … -
Docker + Django + Vue + Nginx configuration not reading CSS or JS files (Ioading wrong MIME type)
I have been working on a project that uses Django REST Framework for an API with an embedded Vue frontend. The Vue frontend is located within the Django project folder and uses Django templates for authentication. I have been trying to get this project working with Docker using Nginx as the server. I have it mostly working but have been struggling with getting the media and static folders to work properly. In my most recent version, Nginx is able to find them but the browser is giving a warning that they are being read as text/html and have the incorrect MIME type. I already have "include /etc/nginx/mime.types" included in my Nginx conf file, attempted to add a location function for css and js but nothing seems to work. My docker-compose file looks like this: version: '3' services: backend: build: context: ./django command: > sh -c "python3 manage.py wait_for_database && python3 manage.py collectstatic --no-input && python3 manage.py makemigrations && python3 manage.py migrate --no-input && gunicorn django.wsgi -b 0.0.0.0:8000" networks: - django-nginx volumes: - ./django:/app - django-static:/django/static - django-media:/django/media environment: - DB_HOST=db - DB_NAME=keeptrackdb - DB_USER=postgres - DB_PASS=postgres depends_on: - db db: image: postgres:10-alpine environment: - "POSTGRES_HOST_AUTH_METHOD=trust" - POSTGRES_DB=djangodb - POSTGRES_USER=postgres - …