Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper practice for URL structure with Django
I've already partially solved an issue I was struggling with but I would like some clarity on if this is the right way to do it in the first place. Ultimately, I wanted to my URL's to follow something like this: www.whatever.com/company/{company_id}/person/{patient_id} (i.e. whatever.com/company/4/patient/2) That's not actually perfect because what I really want is the name of the company and patient where the ID is, so www.whatever.com/company/ryan-corp/patient/jim-jones. I'll leave that for another day for now. What I ended up doing to get the result with the ID is this: my_project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.home), path('company/', include('scraper.urls', namespace="company")), ] my_app/urls.py app_name = "scraper" urlpatterns = [ path('', company), path('<int:pk>/', company_detail), path('<int:company>/patient/<int:pk>/', patient_detail), ] my_app/views.py def patient_detail(request, pk, company): patient = Patient.objects.get(id=pk) return render(request, 'scraper/patient_detail.html', {'patient':patient}) This doesn't feel like I am following a best practice and I feel like I literally guessed to get this working by reading the documentation found here: https://docs.djangoproject.com/en/3.1/topics/http/urls/ It esentially laid out how Django processes the URL's and I noticed that it basically grabs each part of the URL as kwargss. Which is why I passed the company variable in the patient_detail function in views. Then I took a guess and added <int:company> … -
Hide Fields with Django and GenericViews
I'm using Django with Generic views to create my api. From the image below, I would like to hide the field status process and only show the topic field. This is the code I'm using class ListCreateTopic(generics.ListCreateAPIView): queryset = models.Topics.objects.order_by('-time_stamp')[:5] serializer_class = serializers.TopicSerializer -
How to write dynamic (Django) URLs for serving images using Whitenoise on Heroku?
I followed this answer here and read the tips here about serving static images. But I'm baffled: The official Whitenoise docs said to write the URLs this way: <img src="{% static "images/hi.jpg" %}" alt="Hi!" /> And NOT this way: <!-- DON'T WRITE THIS --> <img src="/static/images/hi.jpg" alt="Hi!" /> But if I were to use a dynamic URL, such as src="{{recipe.image.url}}", how do I do it? -
Django ModelChoiceField with Dynamic Query Won't Validate
I'm trying to get this code to validate and it just keeps staying broken. I could use some help because not everything I've seen seems to match what I'm doing exactly. Model: class CardPreconDecklists(models.Model): deck_name = models.OneToOneField('CardPreconDecks', models.DO_NOTHING, db_column='deck_name', primary_key=True) card = models.ForeignKey(CardData, models.DO_NOTHING) class Meta: managed = False db_table = 'card_precon_decklists' unique_together = (('deck_name', 'card'),) app_label = 'edh_escalation' Form: class ChooseDecks(forms.ModelForm): class Meta: model = CardPreconDecks fields = ('deck_name',) deck_name = forms.ModelChoiceField( label='Deck Name', queryset= CardPreconDecks.objects.none()) def __init__(self, *args, **kwargs): qs = CardPreconDecks.objects.all().values_list('deck_name', flat=True).order_by('deck_name') super(ChooseDecks, self).__init__(*args, **kwargs) self.fields['deck_name'].queryset = qs View: @login_required() def ChooseDeck(request, game_id, player_id): # Add Validation to correct user access selectionform = ChooseDecks() if request.method == 'POST': form = ChooseDecks(request.POST) if form.is_valid(): cards = CardPreconDecklists.objects.filter(deck_name= form.cleaned_data.get('deck_name')) CardPool.objects.bulk_create([CardPool(player_id=player_id, card_id=card) for card in cards]) return redirect(reverse('ManageLeague', args=[game_id])) else: return HttpResponse('broke') context = {'form': selectionform, 'game_id': game_id, 'player_id': player_id} return render(request, "edh_escalation/ChooseDeck.html", context=context) -
Save a Value From an HTML Form in a Javascript File Without Page Refresh
So as the title describes I would like to essentially grab a value submitted in an HTML form and then save that to a Javascript file without resetting everything on the page. Also in case it's important I am using Django. I tried to use onsubmit to call a method in the Javascript file that would store the input elements value into a variable and then return false but that did not work. This is the code baseline I'm working on right now. <form onsubmit="return commandSubmission()"> <input class="play-button-style" type="hidden" id="send" value="Send" disabled="disabled"/> <input type="hidden" id="command" name="command" disabled="disabled"> </form> And the Javascript: function commandSubmission(){ //PREVENT HTML FORM SUBMIT return false; } -
How can I see my MySQL database in Django admin site?
I am developing a Django application and I have created a MySQL database (I am using Laragon to manage it) and connected it with the App. I am using the database for another Python script that inserts data in the database too. What I want it to see all the database data in my Django admin site, but for some reason, I can't manage to do it? Do I have to add the tables to the Django models? or what should I do? My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nlpwords', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } I am using that database that has some data in some of the tables, but when I enter localhost/admin in my Django app I can't manage to see all those tables. Help is much appreciated. -
How do I turn Json response into a dropdown option picker? [Django]
I am working with an API and there is a high likelihood that people will entre in wrong information, so what I can do is send their information to the API and it will give out its best guess of what they want and it gives out 10 packets of guesses, how do I turn that into like a dropdown box that people can pick from and when they click on an element it gives me some value at the backend. Think of it like google suggestions. Here is what I kinda want it to look like, in this example, if I entre in tata, it spits out these "suggestions" it might have and I am having trouble understanding what to do. -
i'm not able to understand why i have to restart the server to see the changes made by a Put request (django rest framework)
The put request is working, but if i want to see the post updated i have to restart the server. This is the view function: from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from blog.models import Post from .serializers import PostSerializer from django.contrib.auth.models import User @api_view(['PUT']) def api_update_post_view(request, Slug): try: blog_post = Post.objects.get(slug=Slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PostSerializer(blog_post, data=request.data, partial=True) data = {} if serializer.is_valid(): serializer.save() data['succes'] = 'update successful' return Response(data=data) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) -
I got 502 Bad Gateway after deploying django in aws. How to solve this?
502 Bad Gateway nginx/1.18.0 Is the problem with the port? if yes, how can i change the port then? I am following exactly this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-setup-venv -
django Mptt counter le nombre des produts classés dans une categorie données
j'ai les modeles suivants: class Extension(MPTTModel): STATUT = ( ('True', 'True'), ('False', 'False'), ) parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField() description = models.CharField(max_length=255) STATUT = models.CharField(max_length=100, choices=STATUT) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] def get_recursive_eglise_count(self): return Eglise.objects.filter(extension=self.get_descendants(include_self=True)).count def related_eglise_count(self, instance): return instance.eglise_count class Actualite(models.Model): title = models.CharField(max_length=255) content = RichTextUploadingField() status = models.BooleanField() keywords = models.CharField(max_length=255) lieu = models.TextField(max_length=255) extension = models.ForeignKey(Extension, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='images/', null=False) slug = models.SlugField(null=False, unique=True) tags = TaggableManager() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title je voudrais afficher la liste de toutes les extensions et le nombre d'actualités pour chaque extension enfant comme ceci RDC kinshasa (8) -Goma (12) comment résoudre ce problème svp? -
console_script not working in editable mode and giving ModuleNotFoundError
I am building a wheel package for my project and using setuptools for the same, my project tree structure is as follows: Note : I'm using a pyenv local based virtualenvironment named demo2 with python 3.7.5 $tree -L 3 . ├── Makefile ├── README.md ├── feedback_report.csv ├── pyproject.toml ├── setup.py ├── src │ ├── __init__.py │ └── mypkg │ ├── QuestionGeneration │ ├── README.md │ ├── api │ ├── data │ ├── fitb │ ├── login │ ├── manage.py │ ├── poetry.lock │ ├── pyproject.toml │ ├── requirements.txt │ ├── static │ └── templates ├── test_sample.py ├── tests │ └── context.py ├── tox.ini ├── zero1.sh └── zero_out.sh and my setup.py file is as follows: from setuptools import setup setup( name='fitbapp', version='1.0', packages=['mypkg'], package_dir = {'mypkg': 'src/mypkg'}, description='FITB app', long_description='App to generate fill in the blanks type questions from sentences', classifiers=['Programming Language :: Python'], py_modules= ['manage'], #install_requires = [ 'docutils', 'numpy' ], package_data={'mypkg': ['fitb/*','api/*', 'api/migrations/*.py','static/*.css', 'templates/*.html', 'templates/registration/*.html', 'login/*', 'QuestionGeneration/*', 'fitb/migrations/*.py', 'templatetags/*.py', 'data/pickles/nb-predictor.pkl'] }, entry_points = { 'console_scripts' : ['manage-server=mypkg.manage:main'], } #data_files = [("/", ['static/static.css', 'src/templates/*.html', 'src/templates/registration/login.html'])] ) And my entry_point is specified as manage-server, when I execute the build command using the build package using - python -m build and install … -
Crispy Forms - Icon in Input Field
I read mainly here and here but fail to achieve the correct result. I want to place a fontawesome icon in the input field of my crispy form. My code so far: class ProductForm(ModelForm): class Meta: model = Product fields = ("name", "price") def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) field_symbol = mark_safe("""<i class="fas fa-exclamation-circle"></i>""") self.helper = FormHelper() self.helper.field_class = 'mb-2' self.helper.form_method = 'POST' self.helper.form_show_errors = False self.helper.layout = Layout(Field(AppendedText("name", field_symbol)), Field(AppendedText("price", field_symbol))) Looks like: Should look like: [1]: https://stackoverflow.com/questions/58956947/django-crispy-forms-with-bootstrap4-not-showing-selected-result-in-browse-file-f [2]: https://stackoverflow.com/questions/41221880/prepend-or-append-icon-in-field-of-django-crispy-forms [3]: https://i.stack.imgur.com/CBtRO.png -
Django UUID field throwing IIntegrityError at /admin/books/book/add/
import uuid from django.db import models from django.urls import reverse class Book(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title def get_absolute_url(self): return reverse('book_detail', args=[str(self.id)]) -
(Django) Moving Queryset data to a different model with a button press
I am trying to make a web app for IT staffing similar to a dating app like tinder in which a hiring manager can search a database of candidates and accept or decline a candidate and save it to their profile. I thought a good way to do this would be using a carousel to either accept or decline candidate information. Right now the accept and decline buttons just move the slides but I want the accept button to save whatever data is in the slide to a model set up specific to the user so they can view the candidates they have liked so far. Is this even possible to do? I'm having a hard time conceptualizing it. Any help would be appreciated I am still new to web development. Carousel Code in Template: <div class="row"> <!-- Carousel to toggle through Candidates --> <div id="candidateCarousel" class="carousel slide" data-bs-interval="false" data-bs-ride="false" data-bs-keyboard="false" data-bs-wrap="false" data-bs-touch= "false"> <!-- Carousel inner: what gets displayed inside the carousel --> <div class="carousel-inner"> <!--Display data on website with for loop--> {% for candidate in queryset %} <!-- Carousel item tag. If else statement to make first active --> {% if forloop.first %} <div class="carousel-item active"> {% else … -
Django ORM + async views + non-blocking IO
Is it fundamentally wrong to use an async view with thread_sensitive=False performing an Django ORM call? For instance: def call_to_a_3rd_party_API(): something = requests.post(...) return something @sync_to_async(thread_sensitive=False) def do_something_to_a_product(request, id): product = Product.objects.get(pk=id) result = call_to_a_3rd_party_API() product.some_value = result product.update() return HttpResponse(status=200) The goal here is that I am migrating some of my Django 2.2 views due to blocking IO behaviour (from calling 3rd party APIs) to Django 3.1 async views. In my tests, the only way I could turn the 3rd party API call in non-blocking is using thread_sensitive=False. Reading the docs (https://docs.djangoproject.com/en/3.1/topics/async/) it feels like we should never use thread_sensitive=False with Django ORM. So the alternative I guessed would be: @sync_to_async(thread_sensitive=False) def call_to_a_3rd_party_API(): something = requests.post(...) return something async def do_something_to_a_product(request, id): product = await sync_to_async(Product.objects.get, thread_sensitive=True)(Product, pk=id) result = await call_to_a_3rd_party_API() product.some_value = result await sync_to_async(product.save, thread_sensitive=True) return HttpResponse(status=200) It feels like this way I can turn the call_to_a_3rd_party_API() into a non-blocking function, while keeping all the Django ORM in the main thread. But the code feels a lot more complex. Could someone help me with this? Extra question: I have two projects, one of them using wsgi and the other asgi. Does it make a difference … -
Docker django runs server but browser doesn't show landing page
I have successfully build docker and the server runs without error but when I browse the website it doesn't show anything. Here are the configuration files I'm using: .env.dev DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] Dockerfile FROM python:3.9.1-slim-buster # set working directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # add app COPY . . docker-compose.yml version: '3.8' services: movies: build: ./app command: python core/manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8009:8000 env_file: - ./app/.env.dev Any idea why it isn't browsing? -
TypeError: MyUser() got an unexpected keyword argument 'is_superuser - Django REST
I am using Django REST Framework for my REST API. I am creating a custom user model. Here is my code: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import UserManager from django.db import models import time # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password, **kwargs): if(not email): raise ValueError("No Email Provided!") email = self.normalize_email(email) user = self.model(email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, first_name, last_name, email, password, **kwargs ): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if(kwargs.get('is_staff') is not True): raise ValueError("Super User must be a staff in order to be in!") if(kwargs.get('is_superuser') is not True): raise ValueError("User must be a SuperUser!") if(kwargs.get('is_active') is not True): raise ValueError("Super User must be active!") return self.create_user(first_name, last_name, email, password, **kwargs) class MyUser(AbstractBaseUser): first_name = models.CharField(max_length= 200, blank= False) last_name = models.CharField(max_length= 200, blank= False) email = models.EmailField(unique= True, blank= False) phone_number = models.IntegerField() company_name = models.CharField(max_length= 200, blank= False) date_joined = models.DateTimeField(auto_now= True) last_login = models.DateTimeField(auto_now= True, null= False) is_staff = models.BooleanField(default= False) is_active = models.BooleanField(default= True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number', 'company_name'] objects = MyUserManager() Here is the Error that I am getting: File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File … -
How to make datetime callable in puthon module?
from datetime import datetime, timedelta start = datetime.now() if datetime.now() - start() > timedelta(seconds=5): 'datetime.datetime' object is not callable the problem in the 'if' string. Thanks if you can help me. -
i have a rest api that has a list of question categories and im trying to render it with vue
my model looks like this models.py and it works fine when i try something like {{question.category}} but i have an "add question" vue page that has question body to add and a submit button i wanna add a list of the available categories so it can be chosen with the question. i tried something like this : <select > <option v-for="(category, index) in question.category" :key="index" > {{category.name}} </option> </select> and tried a couple of more things idk how to import the list of categories or if what im trying is wrong, what is the best way to do something like this ? thanks in advance. -
docker-compose unable to connect mysql
I see multiple solutions for this question but still I am unable to make progress hence posting this question I have react+django+mysql app and I want to deploy that into docker, but when I am trying to do my sql image is not created, it says db uses and image, skipping. but I see there was no image created for mysql (it had one but I force deleted, so it can get create new one), I tried solution given here and tried to run below command docker run mysql -h 127.0.0.1 -P 3306 but it asked me give password, root password etc, what went wrong for me? below is my logs PFb my docker-compose.yaml version: '3.2' services: db: image: mysql:8.0 ports: - '3302:3306' environment: MYSQL_DATABASE: 'motor_vehicle_collision' MYSQL_USER: 'creditshelf_user' MYSQL_PASSWORD: '12345678' MYSQL_ROOT_PASSWORD: '12345678' networks: - db-net web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/motor_vehicle_crash ports: - "5000:8000" depends_on: - db frontend: restart: always command: npm start container_name: front build: context: ../../../react code/collision-UI/collision-info dockerfile: Dockerfile ports: - "3000:3000" stdin_open: true depends_on: - web networks: - db-net networks: db-net: driver: bridge below is my python project Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /collision_bike_info WORKDIR /collision_bike_info ADD requirements.txt /collision_bike_info/ … -
Django URL directing to wrong view
I am creating a Django application and have a couple URL'S path('survey/<url_id>/<token>/', views.take_questionnaire, name='take-survey'), path('survey/results/<url_id>/', views.view_results, name='view-results'), I am trying to access the 'view-results' url - http://127.0.0.1:8000/survey/results/lqH16jwM19Y6LLd/ - but for some reason this is triggering the 'take-survey' url. If i change the order of the urls they seem to work, but im curious as to what is causing this. I have never encountered this before, maybe i missed something when learning about django urls. Could someone explain why the first URL is getting triggered rather than the second? -
Django admin save bug
I am using Python 3.8, Django 3.1.2 with PostgreSQL 13.1 . I have a simple webapp using the django administration site for crud actions. Sometimes when i insert data with the django admin add form and click the "save" button django makes strange behaviour (i cannot see the patron that trigger this bug), adding two identical objects to database instead of one. I have been searching but cannot find the solution. This is the only code i have in save_model() function. def save_model(self, request, obj, form, change): if obj._state.adding is True: obj.username = request.user obj.date_input = datetime.datetime.now() super().save_model(request, obj, form, change) Example: If i have a simple model Book with title and author fields (django put id automatically), sometimes when i try to add a Book ('book1','author1') this bug behaviour result in: id title author 1 book1 author1 2 book1 author1 -
Django Model Formset very slow on POST
I am trying to allow users to modify multiple records in one screen, so Django Formsets seemed to be the best bet. Each form in the formset contains 9 foreign key fields which leads to running many many queries. I solved this on form rendering side by using Jquery Autocomplete for each of these, this reduced the render time from 30 or 40 seconds down to about 3 or 4 (reduced hundreds of queries down to 4). The performance problem I now have is on the POST side - it is still running hundreds of duplicate queries according to Django Debug Toolbar when the form is submitted. I have spent hours reading through formset documentation and suggestions on various blogs and here. The last thing I tried was to set the formset queryset to a custom query and with select_related() for each ForeignKey field. This does appear to make the main query include alot of joins according to DjDT but it does not eliminate the remaining hundreds of queries on POST. I've already pulled all my hair out, so maybe someone has a suggestion or can see what I've done wrong? My models: class Info(AbstractAddArchive): item= models.ForeignKey(ITEM, on_delete=models.PROTECT) rec= models.ForeignKey(Log, … -
Django API call not rendering in templates
i am making an API call to get weather, but i am not able to loop through the results in template also note that i am able to print the result in terminal Here is my code: def index(request): url = 'http://api.weatherapi.com/v1/current.json?key={}&q={}&aqi=no' api_key = 'MY_KEY' # print(response.text) cities = City.objects.all() weather_data = [] for city in cities: response = requests.get(url.format(api_key, city)).json() city_weather = { 'city': city.name, 'temperature': response['current']['temp_c'], 'description': response['current']['condition']['text'], 'icon': response['current']['condition']['icon'], } weather_data.append(city_weather) print(weather_data) context = { 'weather_data': city_weather } return render(request, 'weather_app/index.html', context) Here is my template: <!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.0"> <title>Document</title> </head> <body> {% for city_weather in weather_data %} {{city_weather.temperature}} {% endfor %} </body> </html> This is the result i get in terminal [{'city': 'Cairo', 'temperature': 19.0, 'description': 'Partly cloudy'}, {'city': 'Paris', 'temperature': 7.0, 'description': 'Partly cloudy'}, {'city': 'Tokyo', 'temperature': 13.8, 'description': 'Patchy rain possible'}] Not sure why i am not able to pass the result to template, is there something i am missing -
How to serve images added via user in Django in deployment
I have a Django E-commerce App on the cloud. I have configured to add products and images from admin. It was working fine in the development server but doesnt work in deployement. I cant find any good answers anywhere, google seems to be filled with resources about serving static files. Some answers are that apache would be required but i use nginx so how would that work. Help would be appreciated.. models.py class Product(models.Model): name = models.CharField(max_length=150) price = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) description = models.TextField(default='' , null=True , blank=True) image = models.ImageField(upload_to='uploads/products/') old_price = models.PositiveIntegerField(default=299) image2 = models.ImageField(upload_to='uploads/suits/', null=True, blank=True) image3 = models.ImageField(upload_to='uploads/suits/', null=True, blank=True) tags= ArrayField(models.CharField(max_length=20, blank=True, null=True)) settings.py config MEDIA_URL = "/image/download/" MEDIA_ROOT = BASE_DIR urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)