Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
WSGI application 'Uploading.wsgi.application' could not be loaded
while i am run my project after add this middleware social_auth.middleware.SocialAuthExceptionMiddleware i got this error raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: WSGI application 'Uploading.wsgi.application' could not be loaded; Error importing module. -
Why do i get the error " duplicate key value violates unique constraint "" DETAIL: Key (id_application)=(PR-1005576039) already exists
my models.py def document_id(): random_numbers = random.randint(1000000000, 1009999999) doc_id = "PR-" + str(random_numbers) return doc_id class Document(models.Model): id_application = models.CharField(default=document_id(), unique=True, editable=False) applicant_name = models.CharField(max_length=100) to_whom = models.CharField(max_length=255, blank=False) comment = models.TextField(blank=False) email = models.EmailField(blank=False) through_whom = models.CharField(max_length=255, blank=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default='Pending') is_private = models.BooleanField(default=False) stage = models.CharField(max_length=255, choices=STAGES, default='Departmental Review') uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) the problem happens every two times i create a document application, for some reasons it is using the last document application id. I am using a postgresql database. -
How to do an optional parameter to Dict in python like "?" in javascript [duplicate]
In javascript , we Have ==> objInner["roles"]?.forEach((roleInner) => {...} like Is there any alternate in python? to check optionally in the dictionary. -
Django - Models - Linking models to another and vice versa
I am trying to link venues to the products they supply. The products supplied are not unique to each venue. As a result, Venue 1 and 2 could both provide Product A. The outcome I am looking for is twofold: when a Product is added to the database, there is an option to link it to an existing Venue When looking at a venue in particular, I would like to have the list of all the product that can be supplied I tried using Foreign Keys and ManyToManyFields but this only seems to add all the products available to the database to all the venues without leaving a choice. The second problem is obviously referring to Product from the Venue model. If I input a foreign key or any form of relation in it, Django gets upset and tells me Product is not defined. I thought of creating a 3rd model, that could combine both Venue and Products, but it feels like there must be something more sophisticated that could done. class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) venue = models.ForeignKey(Venue, blank=True, related_name="venue", on_delete=models.CASCADE) -
Drf: Update or create a model instance
i have an attendance model that has a unique together constraint for date and user fk field, right now my implimentation of the createorupdate is an if else that doesn't look nice def create(self, validated_data): user = validated_data.get('user', None) date = validated_data.get('date', None) if date is not None: user = Attendance.objects.filter(user=user, date=date).first() if user is not None: instance = Attendance.objects.update( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], ) return instance else: instance = Attendance.objects.create( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], ) return instance this works the only issue is that the returned object from the update is null for all the fields and i need a better implimentation example the full serializer: class AttendanceSerializer(serializers.ModelSerializer): date = serializers.HiddenField(default=timezone.now) leave_reason = serializers.CharField(required=False, default="") class Meta: model = Attendance fields = ['user', 'presence', 'leave_reason', 'date'] #all the fields except pk extra_kwargs = { 'user': {'required': True}, 'presence': {'required': True}, 'leave_reason': {'required': False}, } # validators = [ # UniqueForYearValidator( # queryset=Attendance.objects.all(), # field='user', # date_field='date', # message=("You have already taken the attendance") # ) # ] def create(self, validated_data): user = validated_data.get('user', None) date = validated_data.get('date', None) if date is not None: user = Attendance.objects.filter(user=user, date=date).first() if user is not None: instance = Attendance.objects.update( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], … -
Django with Bootstrap Carousel
My code it's displaying image but not changing the image in the bootstrap carousel when I click the button to pass {% if variation.extravariationproductpicture_set.all %} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for picture in variation.extravariationproductpicture_set.all %} <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img class="d-block w-100" src="{{picture.image.url}}" alt="First slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endif %} -
Is there anyway i can play an audio and then make theHttpResponseRedirect in django?
Like i made this blog in Django where you can like and unlike posts etc..., but when you press unlike I would like to play a sound and then make the request to remove the like. Is it possible to do that? I tried to wrap my head in an if statement, but I'm kinda new to Django so I'm lost MY Postdetail view class PostDetailView(DetailView): model = Post template_name = "post_detail.html" context_object_name = 'detail' def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() total = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = total.total_likes() liked = False if total.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context My like function def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('detail-post', args=[str(pk)])) Where the function with the audio is called <button type="submit" onclick="play()" name="post_id" value="{{ object.id }} " class="btn mb-3 mx-2 btn-outline-danger">unlike </button> | {{ total_likes }} The audio function <script> function play() { var audio = document.getElementById("audio"); audio.play(); } </script> <audio id="audio" src="https://res.cloudinary.com/volendam/video/upload/v1664620564/memesong_dzacbp.mp3"></audio> -
django template is not showing python variables anymore
so I'm trying to build a website with Django (TAPP.GE), I'm getting texts for the website from the database, but after 39 variables, the 40th one and every variable after that is not showing up on the website. all the texts above (get endless possibilities, etc are exactly the same type of variables as others but others are not showing up below, with 4 different icons.) [1]: https://i.stack.imgur.com/uCTwK.png here, red ones work perfectly, but green ones do not show up [2]: https://i.stack.imgur.com/DU3qH.png Views.py [3]: https://i.stack.imgur.com/OjJrA.png also, if I try to put green variables above in HTML, then it works so I wonder does Django templates have any limit on variables or is there any other problem? -
Error connecting Django with MongoDB using Djongo
I am building a simple web app using django as my backend and mongodb as a database. I have set up the settings.py file correctly like so: Image of my settings.py The error i get when i try to migrate my data to database: Error Traceback (most recent call last): File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\djongo\database.py", line 10, in connect return clients[db] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Web\ToDo Projekat\ToDoList\Back\toDo\manage.py", line 22, in <module> main() File "C:\Web\ToDo Projekat\ToDoList\Back\toDo\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\dZoNi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 323, in … -
Fetching data from django restframewok using js fetch [closed]
index.html:401 POST http://127.0.0.1:8000/predict/ 415 (Unsupported Media Type) -
Unable to create migration in django
About issue There is no migration folder Unable to create migration of model Steps to replicate the issue Created the project using this command: django-admin startproject practice1 I did not create any app using command: python manage.py startapp app_name configured mysql in settings.py DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', "ENGINE": "django.db.backends.mysql", "NAME": "backend", "USER": "root", "PASSWORD": "", "HOST": "localhost", "PORT": "3306" #'NAME': BASE_DIR / 'db.sqlite3', } } Since there was no models.py file so I created it inside the directory where settings.py exists models.py contents from django.db import models class Roles(models.Model): role = CharField(max_length=10) is_active = BooleanField(default=False) now, in console, type python manage.py makemigrations it says - No changes detected -
why would I use django-rest-framework , when I can build APIs without it? [closed]
why do I have to use api_view (coming from the django-rest-framework) api_view(['POST']) def signUp(request): ip = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="test") except: print('error in connection ') when I can just do this ? (I am using csrf_exempt because the API that I am building will be called by a python script, and not by a web browser) @csrf_exempt def signUp(request): ip = request.META.get('REMOTE_ADDR') jned = json.loads(request.body) try: connection = psycopg2.connect(user="postgres", password="0000", host="127.0.0.1", port="5432", database="test") except: print('error in connection ') -
Media files showing 404 debug is false using Django development server
I have been trying to test my Django project before deploying it on a cpanel #settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] -
Django navigation as POST input for dynamcial view
I am building an django app that displays real estate data of different cities. The city info is saved in the django model. I have one view that displays all data of a particular city, I only need a way to get the user input of which city data he wants to see. In the navbar are the names of the cities, how do I save the user choice in the navigation in the session info and use it as input for the view? In a form of a POST? base.html <div class="navigation"> <ul> <li> <a href="#"> <span class="title">City 1</span> </option> </a> </li> <li> <a href="#"> <span class="title">City 2</span> </a> </li> <li> <a href="#"> <span class="title">City 3</span> </a> </li> <li> <a href="#"> <span class="title">City 4</span> </a> </li> </ul> </div> -
Django views.py function doesn't get called
I want the function login_user() to be called when the user clicks the Log In Button. But the function never gets called. I think I have setup all the URLConfs correctly. Can you spot my mistake? views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages # Create your views here. def login_user(request): if request.method == "POST": # if user goes to webpage and fills out form, do something email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') # Redirect to a success page. else: messages.success(request, "There was an Error Logging In, please try again.") return redirect('login') else: return render(request, 'registration/login.html', {}) urls.py (main config) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('loginForm.urls')), path('accounts/', include('django.contrib.auth.urls')), ] urls.py from django.urls import path from . import views urlpatterns = [ path('login', views.login_user, name='login'), ] login.html <h2>Log In</h2> <form method="POST"> {% csrf_token %} <div class="mb-3"> <label for="email" class="form-label">Email address</label> <input type="email" class="form-control" name="email" aria-describedby="emailHelp"> </div> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">Password</label> <input type="password" class="form-control" name="password"> </div> <input type="submit" value="Log In" class="btn btn-secondary"> </form> Note: Even if I print something … -
Show product page by category - send 2 var in url
You fetch products by category in this function Urls path('category/<str:slug>', views.categoryslug, name="categoryslug"), Views def categoryslug(request, slug): category = Category.objects.get(slug=slug) context = { 'category': category, 'products': category.product_set.all(), } #return render(request, 'pages/catpro.html', context) But I want to open a product through this link http://127.0.0.1:8000/category/phone/redmi-8-pro Template {% url 'catproslug' product.slug d.slug %} Urls path('category/<str:slug>/<str:proslug>', views.catproslug, name="catproslug") Views def catproslug(request, slug, proslug): d = Product.objects.get(slug=proslug) context = { 'd': d, 'category':category } return render(request, 'pages/catpro.html', context) -
django model to yeild specific HTML output without redundancy in the model
I have 3 models (supervisor, students, and allocation) I am building an allocation system where multiple students can be allocated to one supervisor Now I want my model to be able to yeld this output Example of how i want the output to come out Here are the structure of my model class StudentProfile(models.Model): stud_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.OneToOneField(User,blank=True, null=True, on_delete=models.CASCADE) programme_id = models.ForeignKey(Programme, on_delete=models.CASCADE) session_id = models.ForeignKey(Sessi`**enter code here**`on, on_delete=models.CASCADE) type_id = models.ForeignKey(StudentType, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class SupervisorProfile(models.Model): super_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) dept_id = models.ForeignKey(Department, on_delete=models.CASCADE) class Allocate(models.Model): allocate_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) stud_id = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) super_id = models.ForeignKey(SupervisorProfile, on_delete=models.CASCADE) now my main focus is the Allocate model where the allocation is made, and there is a lot of redundancy any suggestions on how to improve my model to remove redundancy in yielding the expected HTML output would be appreciated 🙏 -
How to solve No module named 'django.contrib.staticfilespages' in Django?
I was studying from the book "Django for Beginners" by William S. Vincent. Whenever I try to run the code from chapter 2, Hello World App, I get "No module named 'django.contrib.staticfilespages' " This question has already been asked by someone else on Django.fun but no answers there. I can't find anyone else having a similar problem on the internet. Also Pycharm is not showing any error to help me with this. File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> main() File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\rexze\PycharmProjects\djangoProject\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) mod = import_module(mod_path) File "C:\Users\rexze\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.contrib.staticfilespages' (venv) PS C:\Users\rexze\PycharmProjects\djangoProject> python manage.py startserver Traceback (most recent call last): File "C:\Users\rexze\PycharmProjects\djangoProject\manage.py", line 22, in <module> … -
Django form fields required and optional configuration
I am in a middle of a project. I have a model :- class CustomersModels(models.Model): def servChoices(servs): lst = [x.serv_name for x in servs] ch =() for a in lst: ch += (a,a), return ch customer_name = models.CharField(max_length=100) comp_name = models.CharField(max_length=100) ph_no = models.CharField(max_length=12) webs_name = models.URLField(max_length=200) service_insterested = models.OneToOneField(ServiceModel, on_delete = models.CASCADE) def __str__(self): return self.customer_name I have a corresponding form for this model. Now what i want is the fields customer_name, comp_name, webs_name to be optional in one page. And required in another page. Please guide me to establish the task in the most convenient manner -
Using Django model manager to return a queryset based on a complex class method
I have a model called Stockentry: class Stockentry(models.Model): id = models.AutoField(primary_key=True, unique=True) distributor = models.ForeignKey( Distributor, blank=True, null=True, on_delete=models.SET_NULL) ... def is_payment_overdue(self): days = self.daysdue() if self.paid == True: # Already paid return False # Not already paid try: if days >= self.distributor.credit_days: # Is overdue if has already exceeded the credit period extended by distributor to dealer return True else: # Is not overdue return False except: # TODO. Currently a temporary catchall return False I am using DRF. I wish to have a query like this to return a queryset where is_payment_overdue is True stockentries = Stockentry.objects.filter(store=store).is_overdue() I started like this: class StockentryManager(models.Manager): def get_queryset(self): return super().get_queryset() def is_overdue(self): myset = super().get_queryset() And went through the docs, but couldnt understand how to utilize this to my specific scenario. I also came across a SO post, which wasnt a minimal complete example, and lacked specifics of implementation. Kindly explain how to go about implementing this for my code. -
Unable to Deploy Django in Heroku
I am unable to deploy django in Heroku. I think the problem lies with Ajax because all of the pages seems to render in heroku. Error that I got is: InvalidCursorName at /incidentReport/general cursor "_django_curs_140297876031040_sync_1" does not exist During handling of the above exception (relation "incidentreport_accidentcausation" does not exist LINE 1: ...cidentreport_accidentcausation"."updated_at" FROM "incidentr... ^ ), another exception occurred: Thank you HTML <!-- Page Content --> <div class="container-fluid"> <!-- Page Title --> <div class="d-flex bd-highlight"> <div class="pg-title p-2 flex-grow-1 bd-highlight"> <h4>Incident Report</h4> </div> </div> <!-- User Report Table --> <div class="card shadow mb-5 d-flex "> <!-- Top Pagination --> <div class="card-header py-3"> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" href="{% url 'incident_report_general' %}">General</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_people' %}">People</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_vehicle' %}">Vehicle</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_media' %}">Media</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'incident_report_remarks' %}">Remarks</a> </li> </ul> </div> <div class="card-body"> <div class="table-responsive"> <table> <form id="form_incidentgeneral" action="{% url 'incident_report_general' %}" enctype="multipart/form-data" method="post" data-acc-url="{% url 'ajax_load_accident' %}"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Date</label> {{user_report_form.date}} </div> <div class="form-group col-md-6"> <label for="inputPassword4">Time</label> {{user_report_form.time}} </div> </div> <hr> <div class="form-row"> <div class="form-group col-md-12"> <label for="inputAddress">Street Address</label> {{user_report_form.location}} </div> </div> <hr> … -
Direct URL to a file in Django Template
I have a CSV file that users downloaded online and saved in a directory on my app. I am trying to create a link to this file so that the user can click the link and the file can be downloaded automatically to their computer. The code below keeps telling file not found. Please does anyone know how to solve this? {% extends 'base.html' %} {% block main %} <p> <a href="/kaggle_dataset/emmy/IRIS.csv" download> Download File </a> </p> {% endblock main %} -
What does a class followed by method does in Python
In Django urls there is this code: path("login/", Login.as_view(), name="loggps") Login is a class and as_view() is a method but is not in the Login class, probably is in a Parent class. What does Class.method does in Python? -
'NoneType' object has no attribute 'save' Django
I'm getting this error when I try to log in with a nonvalid user, I want to be redirected to the login page instead. It highlights the user.save() on muy views.py views.py def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): user = authenticate(request, **form.cleaned_data) user.save() if user: login(request, user) return redirect('home') else: return redirect(reverse('login')) else: form = LoginForm() return render(request, 'accountApp/login.html', {'form': form}) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput) login.html {% block content %} <form method="post"> {% csrf_token %} <h1>Login</h1> <fieldset class="form-group" style="width: 250px;"> {{ form|crispy }} </fieldset> <button type="submit">Log In</button> </form> {% endblock %} -
How can I define or customize my django user from a existintg user model table in SQLSERVER?
I have a database in SQLSERVER with an user table. it contains atributtes like id,email, password, name, lastname,verificationCode and this table is connected with other and it keep going. I know that django has an authentication method and it works with django user model. the question is. How can I define (or customize) my django user model from a existintg user table in SQLSERVER with the purpose to use django auth system and no be redundant with the datas?