Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
virtual env problems while cloning projects from github in different os
i've been looking for answers in stackoverflow and over all the web but still don't get it, i started a new project and upload it to a repository in github, all this i did it from a MAC computer, everything fine until here, but... i tried cloning my project in an Windows computer and i can not activate my venv, to activate the venv in MAC there is a bin file, so i type the following commands in the terminal, 'source bin/activate' and it works fine, but i understand that in windows there is a Script folder which i dont have because i created and activated my project for the first time in MAC, there is a way which is deleting the venv directory everytime i clone my project in a different OS but i dont think that's a good pratice, so i would like to know which is the correct way of doing this, which are your recommendations? Thanks. -
Specific message error for template django
I'm currently working on message error for template that show if you user already liked but it show all the error to all my book Here's my template: <form action="/books/{{book.id}}/like/" method="post" class="like"> {% csrf_token %} <button type="submit" class="btn far fa-thumbs-up"></button> {% if messages %} <ul class="messages"> {% for message in messages %} {% if "like_error" in message.tags %} <li class="text-danger">{{ message }}</li> {% endif %} {% endfor %} </ul> {%endif%} </form> Here's my def: def like(request, id): book = Book.objects.get(id=id) user = User.objects.get(id=request.session["user_id"]) like = Like.objects.get_or_create(u_like=user, b_like=book) if not like[1]: messages.error(request, "Already added to favorite", extra_tags="like_error") return redirect("/books/") context = { 'book_user_like': User.objects.get(id=request.session["user_id"]).user_like.all(), 'book': Book.objects.get(id=id), } return redirect(f"/books/{book.id}", context) and here's my models: class Like(models.Model): u_like = models.ForeignKey( User, related_name="user_like", on_delete=models.CASCADE) b_like = models.ForeignKey( Book, related_name="book_like", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Multi-tenancy subdomains do not return anything
I had a single application running on AWS (NGINX + uWSGI) working normally, but I decided to use the Semi Isolated Approach strategy to create tenants. On my local server, I was able to create and access tenants (tenant01.localhost, tenant02.localhost), but I can't when I try to run on the AWS machine. In it, I don't have any type of error and my NGINX .conf file looks like this: upstream django { server unix:///home/ubuntu/folder_my_project/mysite.sock; # for a file socket } # configuration of the server server { listen 80; listen [::]:80; server_name ssh.18.xxx.xxx.xxx *.18.xxx.xxx.xxx; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/ubuntu/folder_my_project/media; } location /static { alias /home/ubuntu/folder_my_project/static; } location / { uwsgi_pass django; include /home/ubuntu/folder_my_project/uwsgi_params; } } # MY TENANCY server { listen 80; listen [::]:80; server_name ten01.18.xxx.xxx.xxx; charset utf-8; client_max_body_size 75M; location /media { alias /home/ubuntu/folder_my_project/media; } location /static { alias /home/ubuntu/folder_my_project/static; } location / { uwsgi_pass django; include /home/ubuntu/folder_my_project/uwsgi_params; } } Obs.: the journalctl doenst show me error. If anyone can show me what is missing from this file, I would be really grateful. -
Django printing into the browser console (something like console.log)
How to print a message in the visitor's browser console using Django? I know this makes a little sense from the production side, but I would like site visitors to be able to see what is going on "under the hood". I made a Django book recommending site to present my silks with Python and recommendation systems and in order to explain to the visitor how everything functions I need Django-Python equivalent of console.log in javascript. All the posts regarding Django logging are focused on logging information on the server side, but that is not what I am looking for. -
How to save django wizard form in step 1
My problem is I need to save the first form in the database so that I can use the data in the second form, is it possible to do that using django wizard ? any solution to this ?? views.py : lass ContactWizard(SessionWizardView): template_name = 'step1.html' def get_form(self, step=None, data=None, files=None): form = super(ContactWizard, self).get_form(step, data, files) # print self['forms']['0'].cleaned_data step = step or self.steps.current if step == '1': form.fields['Id_Achats'].initial = Achats.objects.latest('id') return form def done(self, form_list, **kwargs): for form in form_list: print(form.cleaned_data) form.save() return redirect('nadjib') forms.py : class AchatForm(ModelForm): class Meta: model = Achats fields = ('Date','Id_Fournis','Montant_HT','Montant_TVA','Montant_TTC') class AssociationForm(forms.ModelForm): class Meta: model = Association fields = ('Id_Achats', 'Id_Article', 'Prix_Unitaire', 'Quantite') -
How to make form on django base.html file
I am making a web application using Django. One of the features that i am trying to implement is a form that is located in the navbar. The form enables the user to enter how they are feeling,and is currently located in its own mood.html file. Is there a way to remove the form from its own file and add it to the base.html file so that it is accessible on all pages enabling the user to enter how they are feeling from any page? -
Running django script directly on server from command line throws error (Lost connection mysql)
I have a script I run from the command line on a server that works fine on my local computer but not on the server. if __name__=='__main__': # only those series titles that have 12 arima predictions selections_list=arima_predictions.objects.values('series_title').annotate(cnt=Count('id')).filter(cnt=12).values_list('series_title', flat=True).distinct() If I try to write the results of selections_list to a file I get an error that says django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') If I don't try to write the results of selections_list to a file, I don't get an error, but it seems to just hang -
pycharm http client send request to Django runserver "Connection reset by peer"
Pycharm 2020.1 & Python 3.7.2 both Django 2.2.12 & 3.0.5 has below issue in dev server when sending a request with Pycharm HTTP integrated client (*.http) ### GET {{url}}/order/ Accept: application/json Cookie: sessionid={{sessionid}} I got this error now and then. System check identified no issues (0 silenced). April 29, 2020 - 08:41:27 Django version 3.0.5, using settings 'proj.settings.dev' Starting development server at http://127.0.0.1:8001/ Quit the server with CONTROL-C. [29/Apr/2020 08:41:53] "GET /api/order/ HTTP/1.1" 200 5070 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 49554) Traceback (most recent call last): File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/CK/Git/QIF/inventory/proj/.venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/CK/Git/QIF/inventory/proj/.venv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Users/CK/.pyenv/versions/3.7.2/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- upgrade python to 3.8.2 doesn't work. -
Django - cascade on other condition
I'm using Django and a Postgres database and I have two tables (Authors, Books). I don't want to enable to deletion of any records, instead to change the boolean of an unseen field called 'active' - a field both tables have. What i'd like to happen is when a user changes an Author's 'active' field to False, all of the books with a FK to this author in the Books table have their 'active' field's also set to False. In Django, my only options it seems related to deletion, how would I set this up with the models.py file? -
AWS S3 Bucket returning 403 forbiden
I have an application in Django and I put it my static files in a bucket on AWS S3. However, when I try to connect in my application the bucket S3 return 403 forbidden for static files. My bucket has a public access configurated for it. If I try to access the file directly an XML error is returned like: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>2A64DBA5BD88AC1C</RequestId> <HostId> K7NHlv7xhPAL6626LCHLayoR4BauqARf6KaTtKUYKQsakNqQ1LL6RnuIwxUqjMP0q6UjMmiW7Yw= </HostId> </Error> My bucket has the files: I tried to change settings putting AWS_DEFAULT_ACL like 'public', 'private' and None, but the problem persists... Obs.: My app is in Heroku. How can I solve this problem? -
Why I am getting a filter error for my template tag?
I'm not sure why I am getting this filter error. I looked up other peoples similar issues with this, and I am definitely loading my template tag, I restarted the server, I have a template tags folder with an init.py file and the file that holds my tag, so , what am I doing wrong here? error is at {{ request.user|unread_messages }}, Invalid filter: 'unread_messages' unread_message_counter.py from django import template from dating_app import models register = template.Library() @register.simple_tag def unread_messages(user): return user.InstantMessage.filter(viewed=False).count() **base.htmnl ** {% load bootstrap4 %} {% load unread_messages_counter %} <!-- Navbar is located in this file --> <!doctype html> <html lang="en"> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% block head %} <title>Basee</title> {% endblock %} </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'dating_app:home' %}">Home <span class="sr-only">(current)</span></a> </li> </ul> <!-- Below is login/registration links and the logic--> {% if user.is_authenticated %} Hello, {{ user.username }} <ul class="mylinks"> <div> <li><a href="{% url 'dating_app:profile' user.id %}">My Profile</a></li> <li><a href="{% url 'dating_app:logout' %}">log out</a></li> <div> </ul> <li class="nav-item"> <a class="nav-link" … -
HttpResponseRedirect - How to apply the Python/Django concept to other languages/frameworks
I recently started a Django tutorial at their main site. I noticed that the framework uses HttpResponseRedirect: https://docs.djangoproject.com/en/3.0/intro/tutorial04/ to prevent people from doing two transactions when clicking the browser's back and forward buttons. How do I apply this concept to other frameworks like React. Much appreciated. -
Django renders wrong template
It's really strange issue, but Django renders wrong template. When i try to run my project, it doesn't render template from my template folder, but really old template, that i changed about 100 times now. I even tried to re-download my project from github and open it in PyCharm. Still the same issue. Has anyone ever encountered this? -
Django - automatically save a copy of an object ID to a second table
I want my Django application to also save the ID of a newly created Post object to my Post_Collection table as soon a actual Post object gets created therefor I tryd the following solution which sadly does nothing so far: models.py collectable_post_models = models.Q(app_label='App', model='post_model1') | models.Q(app_label='App', model='post_model2') | models.Q(app_label='App', model='post_model3') class Post_Collection(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=collectable_post_models, related_name='collections', related_query_name='collection', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=36, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: unique_together = ('content_type', 'object_id') verbose_name = "Post Collection - HELPER TABLE" verbose_name_plural = "Post Collections - HELPER TABLE" ordering = ['-date_added'] # currently not working @receiver(post_save, sender=Post) def ensure_post_exists(sender, **kwargs): if kwargs.get('published_date', False): Post_Collection.objects.get_or_create(post=kwargs.get('instance')) I would expect that each time I create a new Post element the ID gets saved to the Post_Collection table also. Thanks in advance -
Mac terminal: For Visual Studio Code, Django how to activate virtualenv without having to go into the folder
I have a bit of a messy set up and I'm trying to find an easier way to activate my virtualenv without having to navigate into the folder, whilst using terminal. Currently my virtualenv bin file is in: Desktop/Projects/test/ In order to activate my virtualenv I have to go into this file via terminal and then type: source bin/activate then cd . . and work my way back to: Desktop/Projects/challenge/task/ which is where the manage.py file is kept and where I work on the project. I have seen on Windows you can use bash and while, for example, in: Desktop/Projects/challenge/task/ you can type: workon test and that should activate the vitualenv (test), but this command doesn't seem to be working in terminal on Mac. Is there a Mac version of this command? So I don't have to be hopping in and out of folders to a) activate the virtualenv and b)then get to the main project folder. I'm new to this so any additional advice would also be much appreciated. -
Recieved an error while running python manage.py migrate and python manage.py runserver
form.py This is my form tab. from django.contrib.auth.models import User from security_app.models import UserProfileInfo from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('Username','email','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') models.py This is my models tab from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username urls.py This is my urls tab under my app "security_app" from django.conf.urls import url from security_app import views app_name = 'security_app' urlpatterns = [ url(r'^register/$',views.register,name='register') ] view.py This is view tab. from django.shortcuts import render from security_app.forms import UserForm, UserProfileInfoForm # Create your views here. def index(request): return render(request,'security_app/index.html') def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'security_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) base.html This is my base tab from which i inherit nav bar to other htmls tab <!DOCTYPE html> <html> <head> <meta … -
Subtract two DateTime fields in Django
How can I subtract two different formats for DateTime field to get the difference of days and time between them. My models: class TimeAnswerElement(models.Model): costumer_time = models.DateTimeField() my_time = models.DateTimeField(auto_now_add=True) time_compartment = models.DateTimeField(blank=True, null=True) My views: object = get_object_or_404(TimeAnswerElement, id=1) time_compartment = object.my_time - object.costumer_time #My data for fields #object.my_time = 2020-04-28 19:31:35.550655+00:00 #object.costumer_time = 2020-04-28 11:11:00 My solution returns an error: unsupported operand type(s) for -: 'datetime.datetime' and 'str' -
how to request data with the earliest date
trying to get the earliest date based on all the pins in the database but it would return a data with the date of value null. the date field is optional for the user. Trying to figure out a way to get the earliest date without returning one with null class MinPinDate(viewsets.ModelViewSet): queryset = pin.objects.all().order_by("Date").reverse()[:1] serializer_class = PinSerializer router = routers.DefaultRouter() router.register('api/minPinDate', MinPinDate, 'pin') urlpatterns = router.urls -
Inline form factory does not load all documents after POST in Django
I need some help with inline formset in Django. I am using the inline form set factory to upload documents to Document model which has foreign key reference to Department Table as follow: model.py: class Department(models.Model): DepId = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) ShortName = models.CharField (max_length=25) def __str__(self): return (str(self.DepId) + " "+ self.ShortName+ " is created!") class Meta: db_table = 'Department' # Table Name managed = True verbose_name = 'Departments' # Verbose Name of Table. class Document(models.Model): CATEGORY = (('Type1', 'Report Type 1'), ('Type2', 'Report Type 2'),) Id = models.AutoField(primary_key=True) Name = models.CharField(max_length=300) DocType = models.CharField(max_length=300, choices=CATEGORY) DocContent = models.FileField(upload_to='reports/') DepId = models.ForeignKey(Department, on_delete=models.CASCADE, db_column="DepId") UploadedDate = models.DateField(default=timezone.now, null=True) def __str__(self): return (str(self.Name)) class Meta: db_table = 'Document' managed = True verbose_name = 'Document' def delete(self, *args, **kwargs): self.DocContent.delete() super().delete(*args, **kwargs) view.py def doc_loading_view(request, pk, *args, **kwargs): DocumentFormSet = inlineformset_factory(Location, Document, fields=('Name', 'DocContent', 'DocType',), extra=1) department = Department.objects.get(DepId=pk) formset = DocumentFormSet(queryset=Document.objects.none(), instance=department) context = { 'department': department, 'form': formset, } if request.method == "POST": formset = PaymentDocumentFormSet(request.POST, request.FILES, instance=location) if formset.is_valid(): for form in formset: fileform = form.save(commit=False) print (fileform.Name) return redirect('getdoc', pk=department.DepId) else: messages.info(request, "Errors in Formset: "+formset.errors) return render(request, "getdoc", context) Template: {% extends 'base.html' %} {% … -
Prevent audio player from page refresh?
im working on a audio player page on Django. I have a bottom audio player and I have 4 pages in Navbar. When I change the page player stops. I want the player keep playing all the time. Please I need help guys. -
generating unique id in django
my models.py : class clients(models.Model): client_id = models.CharField(max_length=8,unique=True, null=False, blank=True,primary_key=True) client_identity_id = models.IntegerField(unique=True, null=False, blank=False) ' ' my serializer.py : class UserSerializer(serializers.ModelSerializer): class Meta: model = clients fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num') read_only_fields = ('money',) def create(self, validated_data, **kwargs): validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(8)) return clients.objects.create(**validated_data) my views.py : def post(self,request): data=request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when i make a post request it should make a unique client_id for the user , but it keep it Null , i tried too many ways to generate unique id , but no one of them did work ,please help me with making edit on my code to make it work (do not just tell me "do that and that") , and thanks -
I can't run a python file in a subfolder of a Django Project
import urllib.request, requests, time, random, datetime from os.path import basename from bs4 import BeautifulSoup from makale.models import Yazar, Makale, Gazete from django.shortcuts import render, redirect Views of makale App stored within gazete_views folder. I have imported above mentioned models and run the script by following command: python makale/gazete_views/birgun.py But above command reaches following error: Traceback (most recent call last): File "makale/gazete_views/birgun.py", line 4, in <module> from makale.models import Yazar, Makale, Gazete Below is __init__.py file located in gazete_views folder from .haberturk import * from .yenisafak import * from .sozcu import * from .birgun import * from .hurriyet import * from .turkiye import * from .artigercek import * from .dunya import * from .aksam import * __init__.py file located in makale App is empty. I need to run these views located in gazete_views folder. Because I need to run all of them with a cron job. -
How to retain selected option after submitting a form Django
I have a select tag with elements loaded from a DB. When I submit the form (search), I want to retain the selected value and show it in an . I am not using ajax and any django forms. I am just using plain html select tags inside form tag. My view is something like: def filter(request): qs = StrategicObjective.objects.all() strategicplans = StrategicPlan.objects.all() strategicplan = request.GET.get('strategicplan') if strategicplan != 'Choose...': qs = qs.filter(strategicplan__id=strategicplan) else: qs = [] return qs def HomeView(request): qs = filter(request) context = { 'queryset': qs, 'strategicplans': StrategicPlan.objects.all(), } return render(request, "home.html", context) My template: <div id="stratplan_search" class="container"> <form class="form-inline" method="GET"> <label class="my-1 mr-2" for="strategicplan">Strategic Plan</label> <select class="custom-select my-1 mr-sm-2" id="strategicplan" name="strategicplan"> <option selected>Choose...</option> {% for stratplan in strategicplans %} <option value="{{ stratplan.id }}">{{ stratplan }}</option> {% endfor %} </select> <button type="submit" class="btn btn-primary my-1">Submit</button> </form> </div> I would like to show the selected option inside an : <h1> {% for strategicplan in strategicplans %} {{strategicplan}} {% endfor %} </h1> Any help would be appreciated. The preference in simple terms because I am a Beginner in development. -
please help find free online resources on django
I am going to build a webapp that users can send and receive messages and files to each other can you please give me some free resources -
Django - Custom queryset to filter for a field in the models.py
In my model I want to filter out the ForeignKey in this case based off a value in that same model so anytime that field is used, in forms, views etc it shows the specific list instead of all objects. class PersonModel(models.Model): person_type = models.CharField(max_length=50, null=True, blank=True) person = models.ForeignKey( "self", related_name="person_model", on_delete=models.SET_NULL, null=True, blank=True, limit_choices_to={"person_type": "adult"}, ) This isn't working but it's the latest code I have. I'm hoping there is a simple way I can run a custom query against the "person" field such as the example below? class PersonModel(models.Model): person_type = models.CharField(max_length=50, null=True, blank=True) person = models.ForeignKey( "self", related_name="person_model", on_delete=models.SET_NULL, null=True, blank=True, queryset=PersonModel.objects.filter(person_type="adult"), )