Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.1 not closing postgres db connection after tests
The following method is called as part of a test (the test tries to find an external api call in the DB and if it can't find it it will do a real API call) def _ask_transliterate(self, content): found = APITransliteration.objects.filter( source_text=content, from_lang=self.from_lang, to_lang=self.to_lang ) if len(found) == 0: my_json = self._ask_actual_api(content, TRANSLIT_PATH, self.translit_params()) my = APITransliteration( source_text=content, response_json=my_json, from_lang=self.from_lang, to_lang=self.to_lang ) my.save() return my.response_json return found.first().response_json When I just call the class that inherits from TestCase it runs fine, which I believe is because it doesn't find the value in the DB so follows the inner if. If I do a full run of the tests, django refuses to destroy the test database due to an open connection, and SELECT * FROM pg_stat_activity; Reports that it is the query that corresponds to the first() call. This would make sense because the method gets called with the same parameters by two tests, so would find the value for the second run (which is the last test that gets executed). What doesn't make so much sense to me is why the connection is in ClientRead and Idle after my successful complete test run. Is it me that is doing something wrong … -
Subprocess.run not reading file contents from stdin in Django
I'm working on a University project where we are developing a competitive coding platform using Django. We're saving the user's code in a text file and comparing the generated user output with the ideal output all while reading ideal input from a text file. views.py def compileAndRun(request, username, qno,testcase, lang): defaultDir = os.getcwd() os.chdir("questions/") with open("standard/output/question{}/output{}.txt".format(qno,testcase), "r") as idealOutput, open("usersub/newuser/question{}/output.txt".format(qno), "r+") as userOutput, open( "standard/input/question{}/input{}.txt".format(qno,testcase), "r") as idealInput, open("usersub/newuser/question{}/error.txt".format(qno), "w+") as e: os.chdir("usersub/{}/question{}/".format(username, qno)) # CHANGE DIR BASED ON USERNAME AND QUESTION arg1 = arg2 = arg3 = arg4 = '' if lang == 'c': arg1 = 'gcc' arg2 = 'question{}.c'.format(qno) arg3 = './a.out' elif lang == 'cpp': arg1 = 'g++' arg2 = 'question{}.cpp'.format(qno) arg3 = './a.out' elif lang == 'py': arg3 = 'python3' arg4 = 'question{}.py'.format(qno) compileCode = [arg1, arg2] runCode = [arg3, arg4] compiled = True try: if lang != 'py': a = subprocess.run(compileCode, stderr=e) if a.returncode != 0: compiled = False if (compiled): userOutput.truncate(0) # EMPTY OUTPUT FILE TO PREVENT UNNECESSARY CONTENT FROM PREVIOUS RUNS. p = subprocess.run(runCode, stdin=idealInput, stdout=userOutput, stderr=e) userOutput.seek(0) o1 = userOutput.readlines() o2 = idealOutput.readlines() if (o1 == o2): os.chdir(defaultDir) return HttpResponse("SUCCESS") else: os.chdir(defaultDir) return HttpResponse("FAILED") os.chdir(defaultDir) return HttpResponse("FAILED") except: os.chdir(defaultDir) return HttpResponse("ERROR") question1.cpp … -
Django won’t let me query a table by any attribute bar ‘pk’
So I’m trying to query my ‘Profile’ table by the relation attribute ‘owner’, which links to another table ‘User’. However, when I attempt to query by this attribute, I get the following error: 'AssertionError: Expected view UserProfile to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.' To query the table I used: Profile.objects.filter(owner__username = username) Models.py: class User(models.Model): username = CharField(max_length = 80) class Profile(models.Model): owner = models.OneToOneField('User', related_name = 'profile', on_delete = models.CASCADE) Views.py: class UserProfile(generics.GenericAPIView, mixins.RetrieveModelMixin): def get_queryset(self): username = self.kwargs['username'] return Profile.objects.filter(owner__username=username) serializer_class = UserProfileSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) Urls.py: urlpatterns = [ path('user/<str:username>/profile/', views.UserProfile.as_view()), ] Why am I getting this error, how would I fix it? Any help would be much appreciated. Thanks, Grae. -
Django wont load static .css files error: 404 1689
Django was able to load a static .png file but not the static .css file, why? settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] css file h1{ color: red; } html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Django Guitar Page</title> <link rel="stylesheet" href="{% static "css/mysyle.css" %}"/> </head> <body> <<h1>Hi, this is text</h1> <img src="{% static "images/a_picture.png" %}" alt="Uh oh, didn't show"> </body> </html> file path first_app/static/css/mystyle.css first_app/static/css/images/a_picture.png -
How to make collapsible and non collapsible elements in navbar?
I want that in mobile view my search form shows but it collapsed please help. My Navbar with the search form inline 60. I want to make my search form non-collapsible in mobile view. Please improve my code for this purpose. please please please please please please please, please please please please please please please please, please please please please please please please please, please please please please please please please please, please please please please please please please please, please {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>EasyJournal</title> {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> </button> <a class="navbar-brand" href="{% url 'learning_logs:index' %}"> EasyJournal</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'blog:home' %}"> <span class="glyphicon glyphicon-home"></span> Home</a></li> <li> <a href="{% url 'blog:new_post' %}"> <span class="glyphicon glyphicon-pencil"></span> Create Post</a></li> <li><a href="{% url 'blog:my_post' %}"> <span class="glyphicon glyphicon-list-alt"></span> My Posts</a></li> <li> <a href="{% url 'learning_logs:topics' %}"> <span class="glyphicon glyphicon-file"></span> My Notes</a></li> <li><a href="{% url 'diary:diaries' %}" > <span class="glyphicon glyphicon-list"></span> My Diary</a></li> <li> <a href="{% url 'idea:ideas' %}"> <span class="glyphicon … -
If one form filled, the others is not required in Django
I have this model: from django.db import models class Summarizer(models.Model): url = models.URLField() text = models.TextField() and this form: class SummarizerForm(forms.ModelForm): class Meta: model = Summarizer fields = ['url', 'text'] labels = {'url':'', 'text':''} widgets = { 'url': Textarea(attrs={'cols': 80, 'rows': 1}), 'text': Textarea(attrs={'cols': 100, 'rows': 12}), } I want to make it if the url is filled, the text is not required. Vice versa. I've tried this and it requires both of them to be filled: class Summarizer(models.Model): url = models.URLField(blank=True) text = models.TextField(blank=True) if url: url = models.URLField() elif text: text = models.TextField() It should only require one of the forms, not both. What can I do? Thanks in advance -
Django - how to get all the users in team when using a costumised user model
I am new to django and have a question: I created a CustomUser model within a users app. I tried from users.models import CustomUser, Team team1= Team.objects.first() users_team1= team1.user.objects.all() and it doesnt get me the list of users in this Team class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) I want created a HTML page {% extends '_base.html' %} {% block title %}{{ object.title }}{% endblock title %} {% block content %} <div class="team-detail"> <h2><a href="">{{ team.title }}</a></h2> <p>Team tile : {{ team.title }}</p> <p>user: {{ team.user }}</p> </div> {% endblock content %} how can i show all the users in a specific Team? Thanks in advance. -
Django page not found, help would be appreciated
I was taking a youtube tutorial on making a basic website using django and I got this error when coding: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: app/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my code: For urls.py/mysite: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('app/', include('myapp.urls')), path('admin/', admin.site.urls), ] For views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world!") For urls.py/myapp: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Any help would be appreciated. -
Possible to run 10,000+ multiprocess, all running together in Python & Django
I have got a specific problem I need to run 10,000+ multiprocess and all should be running together as they communicate in run time. I tired Django with celery using the prefork method which limits me to use as per my CPU capacity that is 10-15 processes. Current Server Resource - 8 core with 8 GB RAM (Digital Ocean Droplet) I need guidance or direction on how to resolve this issue. Should I use any other technology like Redis Queue or merge any other technology with Celery. Thanks for your help. -
Jinja2 for PyCharm?
I am new to both python and django. I am following a tutorial where the teacher is using Jinja in Visual Studio. I tried to download it from plugins in PyCharm, but there is nothing called Jinja. Is there any way I can use Jinja in PyCharm? Is there any alternative? Thanks -
Celery sqs tries to connect to amqp: Cannot connect to amqp://guest:**@127.0.0.1:5672//
I want to use Celery with SQS. But, connection error is amqp://guest:**@127.0.0.1:5672// . What's wrong is my setting? celery[sqs] ==4.4.7 kombu ==4.6.11 billiard ==3.6.3.0 broker_url = 'sqs://%s:%s@' % (safequote(AWS_ACCESS_KEY_ID), safequote(AWS_SECRET_ACCESS_KEY)) broker_transport_options = { 'region': 'ap-northeast-1', 'visibility_timeout': 3600, 'polling_interval': 1, 'queue_name_prefix': 'pre-', } result_backend = None accept_content = ['pickle'] beat_schedule = { "add": { "task": "tests.tasks.insert_task", "schedule": crontab(minute=0, hour='*', day_of_week='0,5,6'), }, } -
Python Django Filefield 404
Got a interesting issue outside my capabilities. Have searched the whole interwebz but could not find anything suitable. Here we go. The issue: The GET image file returns 404. In this particular case the file is uploaded using the model filefield. The call made from the template differs from the physical location of the file which, well a 404. Due to the dynamic pattern of the app I am confused how to approach this. In short, I need some help ?!?! Python Django latest versions, good start. Project: MySite App: Main Model: class Product_images(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True) image = models.FileField(upload_to='productimages/', null=True) name = models.CharField(max_length=50,unique=False,blank=True) class Meta: verbose_name = 'Product Image' verbose_name_plural = 'Product Images' def __str__(self): return '{} - {} - {}'.format(self.pk, self.product, self.name) View: def products_view(request, *args, **kwargs): return render(request, "products.html") products.html: Includes tag {{ product_section }} context_processors.py: Lots of loops and coding here, the important bit is. html_value += u'<img class="d-block w-100" onclick="openModal();currentSlide(1)" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.image,productimages_obj.name) The productimages_obj is the queryset the html value is used within the products.html template url.py: urlpatterns = [ path('home/', views.home_view, name='home'), path('products/someproduct', views.products_view, name='some product'), ] Outcome: http://127.0.0.1:8000/products/someproduct [12/Sep/2020 01:02:37] "GET /products/productimages/Finance1.png HTTP/1.1" 404 3228 I understand why … -
How to change another field when i actualize one in ManytoMany relationship?
i have two models and i need to know how to change two values when i change one of this class Universidad(models.Model): nombre = models.CharField(max_length=64) carreras = models.ManyToManyField('Carrera', related_name="universidadesSelf", blank=True) class Carrera(models.Model): titulo = models.CharField(max_length=64) universidades = models.ManyToManyField('Universidad', related_name="carrerasSelf") The Universidad class can have many Carrera, and the Carrera class can be in differents Universidad, so what i want to know is if a actualize one Carrera in Universidad, it changes in Carrera too, where the Universidad value is. -
Django databases: problems with the test database
I am learning about Django testing. I wrote a simple App with a simple model and would like to run tests to check the validity of a model method, but I get an error message when I run the test: here's models.py from django.db import models class Trip(models.Model): origin = models.CharField(max_length=20) destination = models.CharField(max_length=20) def __str__(self): return self.origin def is_valid(self): return self.origin != self.destination Here's test.py from django.test import TestCase from .models import Trip # Create your tests here. class TripModelTests(TestCase): def test_trip(self): a = Trip.objects.create(origin='a', destination='a') self.assertIs(a.is_valid(), True) here is settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd57r9kcrhthdc7', 'USER': 'sdqxaruartlvrd', 'PASSWORD': 'e7b8f85611596ed125fe3ed4ea590f821f65e317c17ee7871be75b8130d72378', 'HOST': 'ec2-3-214-46-194.compute-1.amazonaws.com', 'PORT': '5432', 'TEST': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } } and here is the error message i get when I run python manage.py test transport Creating test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File … -
Sign up with email code verification with django
Can you guys tell me how to add a functionality in our website, when a user come to our site and fill sign up form and then click on sign up button than an email sent to his/her email account with a verification code. which he copy and paste on verification code template if code is same than let him log in otherwise send code again. If you know how to do this then tell me or If you know that if i can get help related to this than refer me. I shall be very thankful to you. Well I already made forget password with email verification and already made sign up and login for my website. -
Django form_valid error. Can anyone find the error?
I am trying to use the value from the URL on CreateView My models are like that: Categoria > Serie I have made a URL that path('nova-serie/<categoria>', NovaSerie.as_view(), name='nova_serie'), The URL to create a new Serie is like that: /nova-serie/3 I am trying to use form_valid but I am receiving this message: Cannot assign "'3'": "Serie.categoria" must be a "Categoria" instance. views.py class NovaSerie(CreateView): model = Serie form_class = SerieForm template_name = 'nova_serie.html' success_url = reverse_lazy('home') def form_valid(self, form): url = self.request.path_info parte_final_url = url.replace('/nova-serie/', '') form.instance.categoria = parte_final_url return super(NovaSerie).form_valid(form) forms.py class SerieForm(forms.ModelForm): class Meta: model = Serie fields = ( 'serie', ) widgets = { 'title': forms.TextInput(), # attrs={class="title"} } Can anyone here give me a help? -
Cannot read property 'value' of undefined when adding CSRF token to request headers plain JS
I am trying to add CSRF token to request headers, but it returns the error: TypeError: Cannot read property 'value' of undefined In my django template I have added {% csrf_token %} and my function looks like this: addFavorites (id) { return fetch(`/favorites`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.getElementsByName('csrfmiddlewaretoken')[0].value }, ... What did I miss? -
Data attribute fails to identify itself on Django
In my html file, I have something like this: {% if posts %} {% for post in posts %}' <div onclick="change_like('{{post.id}}')" <small data-id="{{post.id}}" id="laiks">{{post.liked_by.all | length}}</small> </div> {% endfor %} {% endif %} The change_like() function is this one (down here I show you the relevant part): elem = document.querySelector('small'); id = elem.getAttribute('data-id'); console.log(id) So now, in my html page I have a lot of posts and when I click that div The console.log(id) it shows only the first id, no matter in which post I click. I could click in the last one, but the log will be the id always of the first one. So when I want to change the number of likes on X post, it only changes on the first one. Any ideas? -
i'm getting a 429 status when making api request call in django production on DO server but no such error occurs when running from local host
i have wrote this code as TOMTOM doesn't have python SDK for it services this function is called multiple times for route calculation when calling it on django production mode it throws the status of 429 after some 10 to 15 requests to api service but this doesnt happen on when i run it on local host in debug False even if the api calls are made more than 20 to 50 times. def directions(request,geocodes): points = '' for p in geocodes: points += str(p['coordinates'][::-1]).replace('[','').replace(']','').replace(',','%2C').replace(' ','') points +='%3A' # try: req = f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}' r =requests.get(f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}') status = r.status_code print(r.status_code) if status == 200: results = r.json() return results elif status == 429: time.sleep(int(r.headers["Retry-After"])) r =requests.get(f'https://api.tomtom.com/routing/1/calculateRoute/{points}/json?computeTravelTimeFor=all&routeType=fastest&avoid=unpavedRoads&travelMode=car&key={tomtom_api}') results = r.json() return results if i can get help on why this is happening it will be very much appreciated.thankyou -
How can you integrate two programming languages in one enviroment?
I'm currently working on a health care project with multiple people that write code in different languages. The back-end is meant to be built using laravel framework in php, but a couple of my colleagues and i myself are more proficient in Nodejs and DJango framework. Is there a way we can all work on building this platform using multiple languages and frameworks? Thank you. -
Handle website layout when viewed by mobile-browser vs desktop-browser in Django html template?
I would like to handle the layout of my django site based on whether the user is viewing the site from a mobile or desktop browser. Based on the refs I show at the end of this post, I tried to add some css to the head based on the "is_mobile" filter. My site uses base_menu.html to show all of my pages with a menu bar, and that file extends base_bootstrap.html, which has a lot more of the styling as so on. I tried adding this to base_menu.html to insert this mobile based css if the user is on a mobile device. {% if request|is_mobile %} {% block extra-head %} <!-- test if request|is_mobile is working--> {% endblock %} {% endif %} I have two problems. This html commentline was just my test of the if statement, but it is included whether the device is really "mobile" or note, suggesting the if isn't working. I can see it in the header when I look in developer mode I don't what to actually include in the css when the I do detect that the user is using a mobile-browser. My fundamental question, though, is "is there an easy way optimize display … -
Query intermediary model in one line Django
I have two models. They are default django user model and another model which looks like following: class Recipe(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='recipes', blank=False, null=False ) ... And an intermediary one: class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='selecting', blank=False) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='selected', blank=False) Is it possible to retrieve all instances of Recipe model which have relation between them and request.user in one line? -
Django invalid literal for int() with base 10: b'11 20:11:22'
I want to copy an object from one model to another and I'm this ValueError "invalid literal for int() with base 10: b'11 20:11:22' " MODEL: class TempLog(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE, null=True,) start_date = models.DateTimeField(null=True, blank=True, auto_now=True) end_date = models.DateTimeField(null=True, blank=True) def save( self, *args, **kwargs ): employee = self.employee entry = TempLog.objects.filter(user=user) if entry.exists(): TempLog.objects.filter(user=user).update(end_date=Now()) All of these is fine, but if I do: queryset = TempLog.objects.filter(user=user).values('start_date', 'end_date', 'user') new_object = [PermanentLog(**values) for values in queryset] PermanentLog.objects.create(new_object) I need them in datetime format not in integer, how can I by pass this? -
How implement django multiple usertype with CustomUser model and class-based views?
everyone! I'm making a school site where there will be three user types: Principal, Staff and Student. I have managed to successfully(sort of) implement CustomUser model and associate new user to their respective model with receivers. Now my problem is, I have this form in the principal dashboard to add teacher. For that, I need a field in the form to give password as well which I want to store in CustomUser model. I want 'password' field in the form so that when I add Staff, it also automatically become a user. Now my question is, I don't know how to get this password and email from CustomUser model in StaffCreateView. I want save email and password in CustomUser model. In FBV, I could do it by creating an object of CustomUser model, user=CustomUser.objects.create_user( username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=2 ) In short, how do I do similar thing in CBV? My code below: CustomUser model.py from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class CustomUser(AbstractUser): user_type_data = ((1,"Principal"),(2,"Staff"),(3,"Student")) user_type = models.CharField(default=1,choices=user_type_data,max_length=10) class Principal(models.Model): principal = models.OneToOneField(CustomUser,on_delete=models.CASCADE) name = models.CharField(max_length=200) mobile_num_regex = RegexValidator(regex="^[0-9]{8,11}$", message="Entered … -
GET request does not send results to view
I am trying to make a GET request to bring a list of books, however when I render again I do not get any results, it should be clarified that when print by console I do get results. What am I doing wrong? views.py def search_book_basic(request): form_class = SearchBookBasicForm form = form_class(request.POST or None) if request.method == 'GET': string_search = request.GET.get('string_search','') books = Book.objects.filter(Q(title__icontains=string_search) | Q(author__name__icontains=string_search)) for book in books: print(book.title) render(request, 'products/searchProductBasic.html',{'form': form, 'books':books}) return render(request, 'products/searchProductBasic.html',{'form': form}) searchProductBasic.html <div class="row justify-content-center"> <div class="col-md-10"> <div class="card"> <div class="card-header">Search/div> <div class="card-body"> <form method="GET"> {% for field in form %} <div class="form-group row"> <label class="col-md-4 col-form-label text-md-right"> {{ field.label }}</label> <div class="col-md-6">{{ field }}</div> </div> {%endfor%} <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary">Search</button> </div> </form> <br/> <br/> {% for error in form.non_field_errors %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endfor %} </div> </div> </div> </div> </div> {% for book in books %} <h1>{{ book.title }}</h1> {%endfor%}