Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: save history of all changes of a model to Splunk
I have the model Item. Whenever I update data in Item, I would like to send the data to Splunk (for tracking history of all changes). Would anyone suggest me how to deal with this? Thank you so much. -
How to assign a rule in django
I am working on a django project. where there's two table one is developer table and another one is Jira table. developer table and jira table are connected with m2m relation. here's my model.py class developer(models.Model): Developer_Name = models.CharField(max_length=100, unique=True) Role = models.CharField(max_length=500) Level = models.CharField(max_length=30) Expertise = models.CharField(max_length=200) Availability_Hours = models.CharField(max_length=500) def __str__(self): return self.Developer_Name class jira(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Developer = models.ManyToManyField(developer) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) def developer_assigned(self): return ",".join([str(p) for p in self.Developer.all()]) Now my query is how to set a rule where if Dx4c object is changing then automatically one developer will assign based on the rule? here's my view.py def dependency_management(request): jira_story = jira.objects.all() return render(request, 'hello/Dependency_Management.html', {'JIRA': jira_story}) I want to make that dynamic. I mean if everytime I add any new DX4C object then without the code change that particular developer will assign based on the rule -
Django static file not loading. Bad error message
I tried loading style.css in static file but it wouldn't work. I made sure to configure STATIC files in settings.py like this STATIC_URL = '/static/' STATICFILES_DIR = [str(BASE_DIR.joinpath('static'))] All my paths are correct and I loaded static. I cleared my cookies and the CSS still wouldn't work. -
How to resolve url to method or view in flask
Coming from django background I'm trying to get method for a specific url in flask. In django, from django.urls import resolve resolve("/hello_world/") # returns view asssociated /hello_world/ Is there is simlillar kind of functionality is available with flask that can return method against url? -
ImportError while importing models in a different file in same directory
I am new to Django and I am enjoying it a lot. But, yesterday I tried splitting views into different files, but importing the model in that new file shows ImportError: attempted relative import with no known parent package. I am using the same statement as in view from .models import Email And they are in the same directory. I even tried from models import Email but it says the same ImportError: attempted relative import with no known parent package -
why am I getting a 404 when looking for the id of an object django
I cannot get the liftview to work, the test page is working fine. Am I missing an import into the views? I have data in the database with an id of 1 (picture included to show). #polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('test', views.test, name='test'), path('<int:lift_id>/', views.liftview, name='liftview'), ] #views.py from django.http import HttpResponse def liftview(request, lift_id): return HttpResponse("lift id") def test(request): return HttpResponse("test") #models.py import datetime from django.db import models from django.utils import timezone class Lift(models.Model): lift_name = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') def __str__(self): return self.lift_name ==traceback== Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/liftview Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ polls/ [name='index'] polls/ test [name='test'] polls/ <int:lift_id>/ [name='liftview'] The current path, polls/1/liftview, 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. there is data w/an id of 1.. database contents -
How to add raw_id_fields in Content Type object model : Django
I want to add raw_id_fields in django admin for a ContentType object model.How to do it ? models.py class TestList(models.Model): title = models.CharField(max_length=20) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="content_type") object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') -
Django Moving Models
I have a django application I'm trying to refactor. There's a million and five ways it seems to migrate models from an existing django app to a new one however I wanted to run by what seems like the easiest solution. Let's say my current application is called 'main-app' in said application i have a model 'user'. This would create a table called 'main-app_user' or something similar. Let's say I want to move the user model to a new app 'core', some tutorials state this is as easy as pointing the new model to the old table like so class User(models.Model): ... class Meta: db_table = 'main-app_user' I was curious if there was any catch to this I suppose? Many tutorial make this way more complicated so I'm curious why this isn't just the de-facto solution or if there are any drawbacks to this vs others. Thank you in advance! -
I don't know what is wrong but my Django app isn't working I was studying a new course so any help please
this my view.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('hello world') this my sub-app URLs from . import views from django.urls import path urlpatterns = [ path ('', views.index,name='index'), ] This my Django-main App urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('food/',include('food.urls')), ] and browser is displaying this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/food Using the URLconf defined in firstapp.urls, Django tried these URL patterns, in this order: admin/ The current path, food, didn’t match any of these. I am using Django -- 3.2.4 but the course that I am studying is using the 2.2.2 version -
Error when modifying Django data from HTML
I have a small error when trying to modify data stored in Django Oracle, when trying to add the link that takes me to the function and modifies me the user throws me the following error: NoReverse Match at/administration Reverse for 'editar/' not found. 'editar/' is not a valid view function or pattern name. I leave you part of my code urls.py urlpatterns = [ path('', views.index, name = "index"), path('galery', views.galery, name = "galery"), path('toregister', views.toregister, name = "toregister"), path('register', views.register, name = "register"), path('administration', views.administration, name = "administration"), path('editar/<int:id>', views.editar, name = "editar") ] views.py: def administration(request): #Administracion usuarios = Usuario.objects.all() datos = { 'usuarios': usuarios } return render(request, 'store/administration.html', datos) def editar(request, id): usuario = Usuario.objects.get(id = id) if request.method == 'GET': form = UsuarioForm(instance = usuario) contexto = { 'form': form } return render(request, 'store/register.html', contexto) models.py: class Usuario(models.Model): nombre = models.CharField(max_length = 60, verbose_name = 'Nombre del Usuario') apellidos = models.CharField(max_length = 60, verbose_name = 'Apellidos del Usuario') email = models.CharField(max_length = 50, verbose_name = 'Email del Usuario') rut = models.CharField(max_length = 10, primary_key = True, verbose_name = 'Rut del Usuario', unique = True) contraseña = models.CharField(max_length = 15, verbose_name = 'Contraseña del Usuario') def … -
How to add a task from a celery task to the main process loop:django
I want to add a task to the asyncio loop of the main process from celery that runs periodically. I've looked into this to the point where it might be feasible with multiprocessing. However, in the end it looked like I would need to check periodically in the main process to see if the task was added. Is it possible to directly add a task from another process to the main process loop? loop.py import asyncio LOOP = None def run_loop(): global LOOP LOOP = asyncio.new_event_loop() LOOP.run_forever() init.py from celery import app as celery_app from project import loop import threading __all__ = ('celery_app',) threading.Thread(target=loop.run_loop).start() tasks.py from celery import shared_task from project.celery import app from app1 import task @shared_task def add_task(): asyncio.run_coroutine_threadsafe(task.task1(), loop.LOOP) app1/task.py import time def task1(): time.sleep(1) print("abcd") -
Trouble linking CSS stylesheet to HTML in Django
I've formatted my base page properly and I have used the correct tags in my HTML pages, yet my local css file (main.css) will not load. base.html <!DOCTYPE html> <html lang="en"> <head> {% block 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"> {% load static %} <link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/main.css' %}"/> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@300&display=swap" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% block script %} <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <script src="https://kit.fontawesome.com/07a07b3c8d.js" crossorigin="anonymous"></script> {% endblock %} <title>{% block title %}Edward's Portfolio{% endblock %}</title> <style> body { font-family: "Source Code Pro", monospace; } </style> {% endblock %} </head> <body> {% block content %} <h1>My Portfolio</h1> {% endblock %} </body> </html> I have set my STATIC_ROOT and STATIC_URL correctly in settings.py but I have still found no success. If I could get some assistance I would appreciate it. -
Best way to do user authentication with Django backend and React frontend?
I know this is a really general question but I really wanted advice on how to approach this. I have a Django backend running on AWS Elastic Beanstalk and a React frontend. I want to implement user authentication but I'm not sure on how to approach it. Should I do Django default user authentication by creating models and etc? Or should I instead use something else through the React frontend and JWT? I'm new to this and wanted to make sure what is the best approach for this. Thank you so much -
Entering URL in browser causes Python Django ReverseMatchError to be thrown
I am working on a python project while following a book to create an online shop website, I have created the models, views and urls for the app named 'Shop' the project overall is called 'My shop'. Whenever I try to type in the 'product list' url I am returned with the following error: Reverse for 'product_list_by_category' with arguments '(3, 'accessories')' not found. The expected result is the list.html page to be shown which includes all products because no category has been chosen in the URL. I have followed the code in the book exactly and have tried it multiple times yet the error still appears. I have two categories currently and two games, the games are Minecraft and GTA 5, the categories are Accessories and Games. Below is the code from all of the relevant files, if any more are needed let me know. Shop views.py from django.shortcuts import render, get_object_or_404 from .models import Category, Product # Create your views here. #Product List view def product_list(request, category_slug=None): #Setting current category to none category = None #Retrieiving categories categories = Category.objects.all() #Getting all unfiltered products that are available products = Product.objects.filter(available=True) #Filtering products based on category if category_slug: #Get category … -
How to create post request in DRF
I m working on this POST request in drf and I lost it somewhere please help. my models.py class TargetDefination(models.Model): targetName=models.CharField(max_length=50) displayName=models.CharField(max_length=100) def __str__(self): return self.targetName class Target(models.Model): targetDefn=models.ForeignKey(TargetDefination,on_delete=models.CASCADE) roleId=models.ForeignKey(Role,on_delete=models.CASCADE) empId=models.ForeignKey(Employee,on_delete=models.CASCADE) startDate= models.DateField(default=datetime.date.today) endDate= models.DateField(null=True,blank=True) value=models.PositiveIntegerField(default=0) def __str__(self): return str(self.empId) + ' ' +str(self.targetDefn) serializer.py class TargetSerializers(serializers.ModelSerializer): targetDefn=TargetDefinationSerializers() roleId=RoleSerializers() empId=OnlyEmployeeSerializers() class Meta: model = Target fields = ( 'id', 'targetDefn', 'roleId', 'empId', 'startDate', 'endDate', 'value' ) and this is what I have tried: views.py @api_view(['GET','POST']) def setTarget(request, *args, **kwargs): if request.method=='GET': setTrgt=Target.objects.all() serial=TargetSerializers(setTrgt,many=True) return JsonResponse(serial.data,safe=False) elif request.method == 'POST': data=JSONParser().parse(request) serial=TargetSerializers(data=data) if serial.is_valid(): print("working") target = serial.save() serializer = TargetSerializers(target) return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I need to create POST request and the formate will be: this is an example with just values in it. { "id": 6, "targetDefn": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" }, "roleId": { "id": 1, "roleName": "CEO", "description": "Chief executive officer", "roleReportsTo": null, "roleReportsToName": null }, "empId": { "id": 5, "empName": "Emp05", "startDate": "2021-05-04", "termDate": null }, "startDate": "2021-05-05", "endDate": null, "value": 123 } -
How do I append new data into a textField
I have a TextField on my page and I have multiple buttons representing different values, each time a button is clicked i want it to append the integer value and a ',' so that when multiple buttons are pressed it would create "1,2,3,4,5,6," but my current code only replaces the value and after multiple presses only "6," is displayed. <input type="text" id="cardRemove"> <button class="edit-Button" type="button" onclick="document.getElementById('cardRemove').setAttribute('value', value + '{{ forloop.revcounter }},')">append</button> the button is within a for loop that is how it retrieves each value, -
Docker behaves differently per server
Local environment: Arch linux Server a (digitalocean): Ubuntu latest Server b (digitalocean): Docker Ubuntu latest (one click app) My Django project which is running in a container can't run well only on the Server a. The error I get is "No module named main". I am using docker-compose. My project structure: web/ ├── Dockerfile ├── apps │ ├── __init__.py │ ├── api │ ├── seiko │ ├── tirami │ ├── users │ └── takao ├── main │ ├── __init__.py │ ├── asgi.py │ ├── celery.py │ ├── settings │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt The error seems directly related to Python but how could it be possible with Docker? I can't get overcome this issue. I checked every question asked on stackoverflow and contains similar error messages, but none of them helped. -
How should I upload a Django project to GitHub?
This is probably a very dumb question. But I have a little project in Django and I would like to upload it to GitHub to just have it there. I know how GitHub works and I know how to upload the project. But I'm wondering if just uploading the whole folder is the right way to do it. I mean. I have a data base with my project, that has some information. So is the database JUST in my computer right? It won't get uploaded next to the project to github? So basically I'm asking: Should I just simply upload the whole folder? And if I were to download my project from GitHub from another computer. Should I just have to run migrations to make it work locally? -
implement web push notification from my server to a third-party site through a javascript
i want to implement web push notification from my server to a third-party site through a javascript, I want to send notifications to the third-party website through a form on my website, I can already send notifications but only on my own website, I want to ask my customers to include a js on their website and I can send notifications for their website too, the project is in django. -
Django-channels permessage-deflate compression
I'd like to implement compression as the permessage-deflate rfc specifies in Django channels. Is there a way to add a middleware to achieve this? I've taken a look at a few different libraries like brotli-asgi, but that seems to only work for http protocol requests. -
What is the best way to integrate a react and django application?
I am making a full stack website using react and django. I came across various ways to integrate them both. Having them both as two separate projects and interacting using API, or putting react in the django folder and calling the backend. Which method would be better and much easier? And can you also mention the pros and cons of each method. -
IntegrityError a NOT NULL constraint failed : Submit a form through django
I'd like to make a POST REQUEST with an existing HTML FORM, to store it in a database, but everytime I tried to submit data through the form, it gives me the following error By the way I'm doing this following those post: Django form using HTML template MultiValueDictKeyError generated in Django after POST request on login page Registro.html {% extends "RegistrarProyecto/layout.html" %} {% block title %} {% endblock %} {% block content %} <h1>Crear Usuario</h1> <form class="CrearUsuario" action="{% url 'registro' %}" method="POST"> {% csrf_token %} <input type="text",name="NombreProyecto", placeholder="Nombre del Proyecto" > <br> <br> <input type ="text", name="ResponsableProyecto", placeholder ="Responsable del proyecto"> <br> <br> <textarea name="DescripcionProyecto", rows="4", cols="50"></textarea> <br> <br> <input type="submit" value="Registrar"> </form> <br> <a href="{% url 'index' %}">Ir a Bienvenido</a> {% endblock %} views.py def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto,ResponsableProyecto=ResponsableProyecto,DescripcionProyecto=DescripcionProyecto) return redirect("RegistrarProyecto/index.html") return render(request, 'RegistrarProyecto/Registro.html') models.py from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" class Evaluador(models.Model): NombreEvaluador = models.CharField(max_length=64) Proyecto = models.ManyToManyField(Proyecto, blank=True, related_name="Evaluador") def __str__(self): return f"{self.NombreEvaluador} {self.Proyecto}" urls.py from django.urls import path from . import … -
Celery how to create a task group in a for loop
I need to create a celery group task where I want to wait for until it has finished, but the docs are not clear to me how to achieve this: this is my current state: def import_media(request): keys = [] for obj in s3_resource.Bucket(env.str('S3_BUCKET')).objects.all(): if obj.key.endswith(('.m4v', '.mp4', '.m4a', '.mp3')): keys.append(obj.key) for key in keys: url = s3_client.generate_presigned_url( ClientMethod='get_object', Params={'Bucket': env.str('S3_BUCKET'), 'Key': key}, ExpiresIn=86400, ) if not Files.objects.filter(descriptor=strip_descriptor_url_scheme(url)).exists(): extract_descriptor.apply_async(kwargs={"descriptor": str(url)}) return None Now I need to create a new task inside the group for every URL I have, how can I do that? Thanks in advance -
django djongo DatabaseError
// serializers.py class PizzaSerializer(ModelSerializer): size_pizza = PizzaSizeSerializer(many=False) topping_pizza = PizzaToppingSerializer(many=False) class Meta: model = Pizza fields = ( 'name', 'type_pizza', 'size_pizza', 'topping_pizza', 'description' ) def get_size_pizza(self, obj): return obj.size_pizza.name def get_topping_pizza(self, obj): return obj.topping_pizza.name def create(self, validated_data): size_pizza = validated_data.pop('size_pizza') topping_pizza = validated_data.pop('topping_pizza') if size_pizza is not None: size_pizza_obj = PizzaSize.objects.get(**size_pizza) else: size_pizza_obj = PizzaSize.objects.first() if topping_pizza is not None: topping_pizza_obj = PizzaTopping.objects.get(**topping_pizza) else: topping_pizza_obj = PizzaTopping.objects.first() pizza = Pizza.objects.create( size_pizza=size_pizza_obj, topping_pizza=topping_pizza_obj, **validated_data ) pizza.save() return pizza // models.py class Pizza(models.Model): name = models.CharField(max_length=250, blank=False, null=False) PIZZA_TYPE = ( ('regular', 'REGULAR'), ('square', 'SQUARE'), ('pie', 'PIE'), ) type_pizza = models.CharField( max_length=20, choices=PIZZA_TYPE, default='regular', verbose_name='Type Of Pizza' ) size_pizza = models.OneToOneField( PizzaSize, related_name='pizza', verbose_name='Size Of Pizza', on_delete=models.CASCADE ) topping_pizza = models.OneToOneField( PizzaTopping, related_name='pizza', verbose_name='Topping For Pizza', on_delete=models.CASCADE ) description = models.TextField(blank=True, null=True) objects = models.DjongoManager() class Meta: verbose_name = "Pizza" verbose_name_plural = "Pizzas" def __str__(self): return str(self.name) // views.py class CreatePizzaView(CreateAPIView): serializer_class = PizzaSerializer // error File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 75, in _execute_with_wrappers return executor(sql, params, many, context) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 84, in _execute return self.cursor.execute(sql, params) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/utils.py, line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/django/db/backends/utils.py, line 84, in _execute return self.cursor.execute(sql, params) File /home/mr-zero/.local/share/virtualenvs/PizzaApi-BeFk5XgB/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute raise … -
Django i18n using translation.activate
I have configured Django i18n and it works just fine if you change the browser language using the browser configuration UI. I have tested both English and Spanish. However, when I try to let the user pick the language from the navigation bar and set a new LANGUAGE_SESSION_KEY based on the selection made by the user it would not work. The browser language will continue to be the selected language instead. Here follows my code: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... LANGUAGE_CODE = 'en' LANGUAGE_SESSION_KEY = 'en' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('en', _('English')), ('es', _('Spanish')), ('pt', _('Portuguese')) ) The view that is triggered by the navbar: def setLanguage(request, language_code): language = get_language() try: request.session[LANGUAGE_SESSION_KEY] = language_code translation.activate(language_code) request.LANGUAGE_CODE = translation.get_language() request.session[translation.LANGUAGE_SESSION_KEY] = language_code request.session.save() except Exception as e: print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ Oops!", e.__class__, "occurred.") translation.activate(language) return redirect('home_index') I have debugged that the language_code passed corresponds correctly to the selected language (e.g. es instead of en) but it is not activated. The browser language remains as the active language. I would appreciate any ideas. Thanks! Alberto