Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I render a Django Formset with some data for update process?
I am using Dajngo formset with inlineformset_factory What I need it when the user click in the update like It should render formset with the value. This is the code I did but nothing works: This is how I create a formset OrderItemFormset = inlineformset_factory( Order, OrderItem, fields='__all__', extra=1, can_delete=False) And here how I tried to render the formset with the queryset=my_query_set. if 'id' in kwargs.keys(): order = Order.objects.get(id=kwargs.get('id')) order_items = OrderItem.objects.filter(order_id=kwargs.get('id')) else: order = None order_items = None order_form = OrderForm(instance=order) print(order_items) order_item_form = OrderItemFormset(queryset=order_items) When I click in the update link Django render the Parent form with the data I need, but this does not work with formset it just give me one row with empty data. -
TemplateDoesNotExist at /product/1/ productDetail.html
I am making an about page for every item. There is a problem that occurred when I am pressing 'View' on my store page: TemplateDoesNotExist at /product/1/ productDetail.html I have tried specifying the directory by putting {{% extends store/main.html %}}, it did not help. Please assist me. store/views.py from django.shortcuts import render, redirect from django.http import JsonResponse import json import datetime from django.urls import reverse from .forms import CommentForm from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action … -
Django admin login page redirects to same page on login credentials
i hosted Django app in AWS sever properly and there no error in server. after login from Django admin login page redirects to same page on correct login credentials. but it works on local server. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', # AxesMiddleware should be the last middleware in the MIDDLEWARE list. # It only formats user lockout messages and renders Axes lockout responses # on failed user authentication attempts from login views. # If you do not want Axes to override the authentication response # you can skip installing the middleware and use your own views. 'axes.middleware.AxesMiddleware', ] AUTHENTICATION_BACKENDS = [ # AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list. 'axes.backends.AxesBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', ] can anyone help me??? -
Deploy React and Django, same domain but different sub-domains, while on the same server
I am building a React js Application with the Django backend. with API integration I have one server and 1 Domain, and using nginx I suppose to do Run my React app on www.my-domain.com and Django backend on services-api.my-domain.com which scenario should I choose? Should I go with 2 Different Domains and Different servers? or I can do on this way what I discussed above & guide me how I can do this. How i can setup React and Django on the same server with same domain but in different sub-domain -
How to solve TypeError: Object of type HttpResponse is not JSON serializable?
I am trying to return a model.pkl file using postman from an API made in django rest framework. However the response I get is TypeError: Object of type HttpResponse is not JSON serializable. The following code is what I am using to return the file, but I cannot understand what is going wrong (this was inspired by this post). from rest_framework.status import HTTP_200_OK import pickle from django.http import HttpResponse from wsgiref.util import FileWrapper # views.py ... model_pickle_path = f'/path/model_state.pkl' #model_pickle_trained = pickle.load(open(model_pickle_path, 'rb')) model_pickle_trained = open(model_pickle_path, 'rb') response = HttpResponse(FileWrapper(model_pickle_trained), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % model_filename_defined return Response(data=response, status=HTTP_200_OK) Traceback: TypeError: Object of type HttpResponse is not JSON serializable -
Get MIME type of file that is in memory - Python Django
I have a form where users can upload files. I only want them to be able to upload images. I have added that in the HTML form but need to do a server side check. I would like to do this check before I save the file to AWS S3. Currently I have this: from .models import cropSession, cropSessionPhoto import magic def crop(request): if request.method == 'POST': data = request.POST images = request.FILES.getlist('photos') crop_style = data['style'] if len(images) <= 0: messages.error(request, "At least one photo must be uploaded.") return redirect(reverse('crop-form')) crop_session = cropSession(crop_style=crop_style) crop_session.save() for image in images: mime = magic.Magic(mime=True) mime.from_file(image.file) upload = cropSessionPhoto(crop_session=crop_session, photo_file_name=image, photo_file_location=image) upload.save() else: messages.error(request, "An error has occured.") return redirect(reverse('crop-form')) return render(request, 'crop/crop.html') However, I get this error: TypeError: expected str, bytes or os.PathLike object, not BytesIO How do I properly pass the image to magic? Thank you -
Why fetch does not include credentials everytime with option {credentials: "include"}?
I have been trying to fetch data from my djangorestframework api verifying through cookies. Before reaching to the main problem, My computer IP on LAN: 192.168.1.50 Running localhost at port 80: 127.0.0.1 Running django at port 8000: 192.168.1.50:8000 - (tried vice versa as well: 127.0.0.1:8000) Now, assuming my django is running on 192.168.1.50:8000, I figured out that if I send fetch request to djangorestframework from 192.168.1.50 the cookies are attached with the request. Django's settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', "corsheaders", 'users', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CORS_ALLOWED_ORIGINS = [ "http://192.168.1.50", "http://127.0.0.1", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] Fetch method from JS, fetch("http://192.168.1.50:8000/user/auth/", { method: "GET", credentials: "include", headers: { 'Content-Type': 'application/json', }, }).then(r => { console.log(r.json()); }) Sending request from 192.168.1.50, From 192.168.1.50's (from chrome browser), Response Header: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://192.168.1.50 Allow: OPTIONS, GET Content-Length: 5 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Wed, 15 Dec 2021 #:#:# GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.10 Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Request Header: … -
How to serialize json to sql?
I have a list of words and I should send requests to an API and get the information about the words. I want to convert the API data which is in JSON format to SQL(my DB is PostgreSQL) format in Django. How can I do that? Do you know any good source to learn to serialize json to sql? I have just started learning Django. It is the API's JSON data: [ { "word": "hello", "phonetics": [ { "text": "/həˈloʊ/", "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3" }, { "text": "/hɛˈloʊ/", "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3" } ], "meanings": [ { "partOfSpeech": "exclamation", "definitions": [ { "definition": "Used as a greeting or to begin a phone conversation.", "example": "hello there, Katie!" } ] }, { "partOfSpeech": "noun", "definitions": [ { "definition": "An utterance of “hello”; a greeting.", "example": "she was getting polite nods and hellos from people", "synonyms": [ "greeting", "welcome", "salutation", "saluting", "hailing", "address", "hello", "hallo" ] } ] }, { "partOfSpeech": "intransitive verb", "definitions": [ { "definition": "Say or shout “hello”; greet someone.", "example": "I pressed the phone button and helloed" } ] } ] } ] this is my models.py: class Words(models.Model): word = models.CharField(max_length=50) american_phonetic= models.CharField(max_length=50) american_audio= models.URLField(max_length = 200) british_phonetic= models.CharField(max_length=50) british_audio= models.URLField(max_length … -
Django resets user permissions
I am building a site using React for the frontend and Django for the backend. The login page sends a request to this view function when the login button is pressed. @api_view(['POST']) def api_authenticate_login_view(request): body = request.data username = body['username'] password = body['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) content = {"authenticated": True} return Response(content) else: content = {"authenticated": False} return Response(content) When trying to access any other page in the site, a request is first sent to this view function to make sure the user is logged in @api_view(['GET']) def api_is_authenticated_view(request): if request.user.is_authenticated: content = {"authenticated": True} return Response(content) else: content = {"authenticated": False} return Response(content) If it returns false they are redirected to the login page. The issue is that this works great for most of our users, but for a select few, their user permissions in the provided Django admin page are constantly reset. What I mean by that is, in the user section of the Django admin page, you can select a user and see their permissions. On our page this shows a tick box next to the tags Active, Staff status, Superuser, and others(see image link below) Django user … -
Django using Aws S3 bucket to get static files
url.com/:9 GET https://<AWS_STORAGE_BUCKET_NAME>.s3.amazonaws.com/static/user/main.css net::ERR_ABORTED 403 (Forbidden) url.com is the actual site and AWS_STORAGE_BUCKET_NAME is the bucket name When I try to retrieve my S3 file from my base.html I get a 403 forbidden error in the console. <link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css"> Settings.py # All of this is in my console.aws.amazon to configure aws s3 static files only # IAM Management Console AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) # For some reason I needed static root to collectstatistics # STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage ' -
ValueError at /login invalid salt
I am creating a django app and have run in to a problem with the login portion of it. Everything seems to be working fine but when I login in with the stored information I receive the ValueError with invalid salt. I've looked on here for solutions but nothing seems to be doing the trick. I tried using the encode('utf-8) solution but that doesn't work either. def login(request): if request.method != 'POST': return redirect('/') user = User.objects.filter(email = request.POST.get('email')).first() if user and bcrypt.checkpw(request.POST.get('password').encode(), user.password.encode()): request.session['user_id'] = user.id return redirect('/quotes') else: messages.add_message(request, messages.INFO, 'invalid credentials', extra_tags="login") return redirect('/') return redirect('/quotes') The issue seems to stem around the if user and bcrypt.checkpw() but I don't know what to do different? -
Django overriding filter() without change existing code logic
I have a table in production that is integrated everywhere in the system, now I need to make add a new column in the table with a default value, but don't want to change all the existing logic, what is the best to do that? class People(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=20) class = models.CharField(max_length=20) in the system, we have this kind of queries everywhere People.objects.filter(gender='male') People.objects.filter(gender='female', class="3rd") ... Now we need to add a new field: class People(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=20) class = models.CharField(max_length=20) graduated = models.BooleanField(default=False) Assume that all the existing data should have graduated is False, so all the existing should work if we can add graduated=False, but is there any way we can do so we don't need to change any of the existing code but they will assume graduated=False? -
Django - Admin - Defualt Add/Change Form
I am wondering what is the best method and how to add in an informational field to the built-in admin add/change forms. Here is my case: I have 3 models each one is tied to another by a foreign key investor --> investment distribution --> investment So with proper a query I can easily look up from the distribution table which investor received which distribution If I want to add a distribution using the built in Django admin forms - the selection option for "investment" field for the distribution add form the dropdown list will include all the investments. The issue I am having is, if I have the same investment name for 2 investors, I do not know which option to select. So I would want the form to lookup the Investor using Investment --> Investor while on the distribution add/change this way when I add a distribution to an Investment I can select which investor it applies to. i.e. Investor Paul has Investments AAPL, GME, BB Investor Alan has Investments TSLA, GME Adding distribution for Investment GME ---> that form would should 2 GME options but I would like to know which is Pauls and which is Alans … -
How to integrate ldap to saml2 in Django
I have a django app that initially used LDAP to authenticate. Because of changing times I had to move the app over to use django-saml2-auth-ai, which initially I thought was fully working. A month after getting saml to "work" I noticed that this part of the code no longer worked. groups_owners=register.user.user_ldap.groups_names And I keep getting the following error. 'User' object has no attribute 'ldap_user' I use the command above to find all the ldap groups the user using the system belonged to. So how do I integrate SAML to work with LDAP or what do I need to add to SAML to get the ldap groups from the SAML authentication. From my saml trace tool all groups come from login.com/names/groupNames. When I try to query the attributes from SAML_AUTH they are empty SAML2_AUTH = { # Required setting 'SAML_CLIENT_SETTINGS': { # Pysaml2 Saml client settings (https://pysaml2.readthedocs.io/en/latest/howto/config.html) 'entityid': 'https://reg-dev.com', # The optional entity ID string to be passed in the 'Issuer' element of authn request, if required by the IDP. 'metadata': { 'remote': [ { "url": 'https://idp.com/pf/federation_metadata.ping?PartnerSpId=https://reg-dev.com', # The auto(dynamic) metadata configuration URL of SAML2 }, ], }, }, # Optional settings below #'DEFAULT_NEXT_URL': '', # Custom target redirect URL after … -
Using User Model outside of Django Web App with Django Rest Framework
I have a model called File in my Django Web App. At the moment it looks like this: from django.db import models from django.conf import settings class File(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='files_owned', on_delete=models.CASCADE, default) file_name = models.CharField(max_length=20, default=None, blank=False, null=False) file_path = models.CharField(max_length = 50, default=None, blank=False, null=False) I have an endpoint using the Django REST Framework, where I can get a list of all Files and create a new File. Currently the endpoint looks like this: The POST request at the moment only allows for file_path and file_name to be entered, I want to be able to enter a user ID or a User model, but the script that uses the endpoint is outside of the django web app so cannot access the User model. What would be the best solution for this, while maintaining a foreign key relationship in my DB -
Python / Django / Postgres Get Sample of Database
Looking to utilize either python and psycopg2 or django ORM to get a sample of a postgres database. Seeing pg_dump as a way to get the entire database but I would only want about 10% of the data, centering around a particular table. There are foreign key relations between all objects. What is the best way to do this? -
how to use select2 with dynamic form
I'm trying to add select2 for a dynamic form which is a modelformset_factory, but it doesnt work as i expect, it only works after the first add new row button! and after the third forms it create an extra drop down field! here is what im tried const addNewRow = document.getElementById('add-more-invoice') const totalNewForms = document.getElementById('id_imei-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_imeiforms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-imeilists') const empty_form = document.getElementById('empty-imei-invoiceform').cloneNode(true); empty_form.setAttribute('class','child_imeiforms_row') empty_form.setAttribute('id',`form-${countForms}`) const rgx = new RegExp('__prefix__','g') empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countForms) totalNewForms.setAttribute('value',countForms + 1) formCopyTarget.append(empty_form) $('.choose').select2(); } $('.choose').select2(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> <label>customer name</label> {{ main_form.customer | add_class:'form-control' | append_attr:'onchange:currentBalance();' }} </div> </div> <div class="col-md-2"> <div class="form-group"> <i class="fas fa-box-usd"></i> <label>balance</label> <input type="number" disabled class="form-control" id="balance_cus"> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <i class="far fa-clock"></i> <label>date</label> {{main_form.created | add_class:'form-control text-center'}} </div> </div> </div> {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control choose' | append_attr:'onchange:imeiPlusInfo();'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | add_class:'price'}} </div> </div> <div class="col-md-1"> … -
Field 'id' expected a number but got '{{\r\n choice.id }}'
I am learning from Django documentation but in part 4 of the tutorial I am getting this error: ValueError at /polls/1/vote/ Field 'id' expected a number but got '{{\r\n choice.id }}'*. polls/views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) polls/urls.py path('/<int:question_id>/vote/', views.vote, name='vote'), detail.html <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> -
How to define the apscheduler to execute everyday?
This is my function: def start(): scheduler = BackgroundScheduler(timezone="America/Sao_Paulo") scheduler.add_job(send_daily_report, 'cron', hour='0') scheduler.start() It's worked at the first day, but didn't repeat itself. I'm executing this at the background of my principal Django application (and I'm not using django-apscheduler). May I forgot something? -
Django + MongoDB connection error after deployment to Heroku
I'm using Django(djongo) + MongoDB Altas(pymongo). So I developed this web app locally where I use Javascript's fetch method to read and write data to MongoDB. Example code: fetch("https://127.0.0.1:8000/api/fetchValues") .then(response => response.json()) .then(data => { //do something Everything works fine locally, but when I deployed it to Heroku (and hardcoded the 127.0.0.1:8000 part with <appname>.heroku.com) the same fetch method returned [ ] instead of the actual values stored in MongoDB, although I got 200 OK code from it. My settings.py file looks like this: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://<username>:<pass>@cluster0.74bck.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', 'authMechanism': 'SCRAM-SHA-1', } } } I've also used import django_heroku and django_heroku.settings(locals()) on top and bottom of my settings.py respectively. I've migrated both using python manage.py and heroku run python manage.py (makemigrations/migrate of course). I believe that it comes down to Heroku config vars and specifically DATABASE_URL which I cannot remove/edit. I've tried these steps: Destroying a Postgres DB on Heroku How to change DATABASE_URL for a heroku application but nothing worked. I've also made my own MONGODB_URI config var but at no use. A fun fact is that when I used the Javascript fetch method above after deploying to Heroku (but with 127.0.0.1:8000) it … -
Loading module from “https://app.herokuapp.com/assets/index.1ab7e925.js” was blocked because of a disallowed MIME type (“text/html”)
index.html <!DOCTYPE html> <html lang="en"> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <base href="./"> <title>PzCompare</title> <script type="module" crossorigin src="/assets/index.1ab7e925.js"></script> <link rel="modulepreload" type="text/javascript" href="/assets/vendor.d0b4acaa.js"> <link rel="stylesheet" href="/assets/index.e7475acf.css"> </head> <body> <div id="root"></div> </body> </html> All of the css and js files are not being loaded because of this error 'blocked because of a disallowed MIME type (“text/html”)', no idea how to fix this, any help is appreciated! -
IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id
I am working with a blog project where I am trying to add profile picture of the user. whenever I submit the picture It gives me UNIQUE constraint failed:authentication_userprofile.user_id. views.py from .forms import ProfilePic def add_pro_pic(request): form= ProfilePic() if request.method=='POST': form=ProfilePic(request.POST,request.FILES) if form.is_valid: user_obj=form.save(commit=False) user_obj.user=request.user user_obj.save() return redirect('profile') return render(request,'profilePic.html',{'form':form}) models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User,related_name='user_profile',on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics') forms.py from. models import UserProfile from django import forms class ProfilePic(forms.ModelForm): class Meta: model=UserProfile fields=['profile_pic'] here comes profilePic.html {% extends 'base.html' %} {% block content %} <h2>Add Profile Pic</h2> <form method="POST" enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button type="submit" name='button' class="btn btn-success btn-sm">Add</button> {% endblock %} But the server shows me this UNIQUE constraint failed: authentication_userprofile.user_id IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id Request Method: POST Request URL: http://localhost:8000/authentication/addProfilePic/ Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: authentication_userprofile.user_id Exception Location: C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\ITS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\ITS\\Desktop\\blog_project\\blogproject', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 14 Dec 2021 19:40:04 +0000 where is the problem? thanks in advance. -
Add model methods to Django model on a per-app basis? Model shared among apps
I am curious as to how best to handle this situation: I've got an app that has a User model (AbstractUser); it includes all the usual attributes (username, is_superuser, is_staff, etc.) This app is shared among multiple projects (which all have their own apps) The structure looks like something like this: Project X App A App B Project Y App A App C App D Project Z App A App E App F I'm at a point where I need to add a model method on that User model in Project Z to make life easier. It would do some business logic involving other models from the other related apps. Filtering stuff from App E and App F and what not. I can't add that method directly to the User model, because then the other projects would fail since they don't have access to those other projects. What is the best way to accomplish this in Django? -
Django - resource was not found on this server on production
I am trying to access these files used from the django-import-export-celery module: I am able to see my view on local: But its not showing on my production server: This is my urlpattern: urlpatterns = static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + [ # favicon path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/Dalmore-Group-16-16.png'))), # debug path('__debug__/', include(debug_toolbar.urls)), url(r'^', admin.site.urls), ] And my settings.py has: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to deal with circular relationship in Django models?
I'm trying to write a basic DB to offer my photographs. It seemed so simple, but I just can't wrap my head around this, despite thinking for a couple of weeks. I'm trying to combine multiple models that link to each other. Photo: Files with some stored dataPerson: Data about a person that appears in a photo / has mad a Quote Quote: Something a Person has said and needs to be attached to Photos (the quote does not belong to all photos of that person, but rather a specific set) Offer: An overview that has all the quotes with one Photo as a thumbnail and all the Photos (some photos might have the same quote, but it should only appear once) As a mockup and because people here really love to see some code first I made this: class Quote: person = models.ForeignKey("Person") photos = models.ManyToManyField("Photo") class Person: photo = models.ForeignKey("Photo") class Photo: pass class Offer: quotes = models.ManyToManyField("Quote") photos = models.ManyToManyField("Photo") Please take the code above as an illustration, because I already don't know how to tackle this. I tried multiple different versions, but there is always some case that doesn't get covered. In the above example the …