Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework CRUD
I´m building an API with Django Rest Framework, and I’m wondering if it's enough to use only the ModelViewSet class to implement the CRUD. My worries is that it’s not enough for the frontend to consume and use the create, read, update and delete functionalities. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use creator.set() instead
I'm getting this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use creator.set() instead. New to django I believe there is an error with the assignment of my create method. Here are my files: Any advice helps // Views.py def createTrip(request): trip_creator = User.objects.get(id = request.session['loggedInID']) newTrip = Trip.objects.create( creator = trip_creator, description = request.POST['description'], city = request.POST['city'], country = request.POST['country'], photo = request.POST['photo'] ) print(newTrip) return redirect('/home') //models.py class Trip(models.Model): creator = models.ManyToManyField(User, related_name= "trips") description = models.CharField(max_length= 255) city = models.CharField(max_length= 255) country = models.CharField(max_length= 255) photo = models.ImageField(upload_to='static/img/trips') // html <div class="form-container"> <h4>Add a Trip</h4> <form action="/createTrip" method="post" class="reg-form"> {% csrf_token %} <p><input class="field" type="text" name="city" placeholder="City" id=""></p> <p><input class="field" type="text" name="country" placeholder="Country" id=""></p> <p><textarea name="description" id="" cols="30" rows="10"></textarea></p> <p><input class="field" type="file" name="photo" placeholder="Photo" id=""></p> <input class="form-btn" type="submit" value="submit"> </form> </div> //settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = 'static/img/trips/' MEDIA_URL = os.path.join(BASE_DIR, 'static/img/trips/') -
How to get multiple image files data in django
The simple portfolio page uploading multiple image fields and prints all images on the page also, save in DB -
Dynamically Loading Data Into Django Modal
I've been trying to implement a way to dynamically load information into a modal in order to do a quick preview for my ecommerce site. Any help would be appreciated, I'm not sure which direction I should head in. I tried to play with Javascript and creating an onclick function to refresh the div, but I have had no success so far. Please comment if any part of my question is unclear. attached is a screenshot as to what is rendering on my end to get an idea of what I am trying to do. https://gyazo.com/e0168c6d41a19071a95e8cecf84e37a9 store.html {% extends 'main.html' %} {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" href="{% static 'css/store.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> {% block content %} <div class="p-5 text-center bg-image mt-4 mb-4" style=" background-image: url('{% static 'images/ship.jpg' %}'); background-size: auto; height: 400px; box-shadow: 1px 2px 2px; "> <div class="mask" style="background-color: rgba(0, 0, 0, 0.6);"> <div class="d-flex justify-content-center align-items-center h-100"> <div class="text-white"> <h1 class="font-weight-bold mb-3" style="color: white;">Store</h1> <h2 class="font-weight-bold mb-3" style="color: white;"> Welcome to our online shop, where our shipping quotes are listed below</h1> <h3 class="mb-3" style="color: white;"> We ship a variety of items to fit your needs including cars, car parts, heavy … -
How do I filter querysets by a field chosen from template form in Django?
I'm learning Django. I have a listview and detailview for a queryset, all working properly. In the listview, I want the user to be able to search the model database choosing to look for given string in one, many, or all the model's fields. Since the filter() method gets field name as .filter(name__icontains='string') I don't know how to pass this name parameter from the form checkboxes. -
What is causing my django authentication backed to be so slow?
I have a custom authentication backend. def authenticate(self, request): start = time.time() auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: raise NoAuthToken("No auth token provided") id_token = auth_header.split(" ").pop() try: decoded_token = decode_verify_firebase(id_token) except Exception: raise InvalidAuthToken("Invalid auth token") if not id_token or not decoded_token: return None try: uid = decoded_token.get("user_id") email = decoded_token.get("email") except Exception: raise FirebaseError() q_start = time.time() user, created = User.objects.get_or_create(username=uid, email=email, firebase_user=True) logger.info(f'getting the user --- {time.time() - q_start}') logger.info(f'Total auth time --- {time.time() - start}') return user, None Note: I am custom decoding the firebase token, there is no outgoing request here. I put some time stamps in this function for profiling: getting the user --- 0.5818960666656494(s) Total auth time --- 0.5826520919799805(s) You can see that user query is taking the bulk of the time. This is also causing my authenticated endpoints to perform very poorly. However, when I log the queries it reports the query being very quick. Execution time: 0.089754s [Database: default] Any ideas what I could do to fix or improve this? -
ModuleNotFoundError received when using tinymce with Django
Problem I'm trying to add a 3rd party app to my project so that I can add it to an app called 'Plants' however when I follow the installation instructions I receive an error message. instructions followed: https://django-tinymce.readthedocs.io/en/latest/installation.html Troubleshooting I've tried Uninstalling and reinstalling tinymce with pip install django-tinymce and pip uninstall django-tinymce. Confirmed that I was in a virtualenv for installation and while running my server with python manage.py runserver. Fully installed the tinymce module then reset my terminal. Confirmed my requirements were created correctly with pip freeze > requirements.txt Reviewed all of my spelling in base.py, plants > models.py, and config > urls.py Confirmed my DJANGO_SETTINGS_MODULE was set correctly in config.wsgi.py and manage.py Read through every stackoverflow issue with the same traceback error. Adding path('tinymce/', include('tinymce.urls')), to plants > urls.py, that didn't make since so I removed it Traceback Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/mary/Projects/opensprouts-web/opensprouts/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute … -
The Cross Origin Opener Policy header has been ignored - DJANGO
Im making a Chatapp project in Django. I implemented channels and websockets to send and receive message and this worked when i tested using two differents windows in the same browser (one of them in incognito mode), but when i try to test it using another browser i get the following error: enter image description here I tried to solve implementing django corsheaders with the following configuration: enter image description here enter image description here enter image description here (I know that setting all origins to true its not recommendable but it's just for testing purpouses) -
Django Error: Profile matching query does not exist
I am working with an Open-Source Social Media Website. I have a normal Feed.html where Users can see the Post of their Followings. When I open the feed page it shows this error message. It never showed an Error Message before. I tried insted of p = Profile.objects.get(user=u) = p = Profile.objects.get(Profile, id=1) But then it just showed the first Account on the Website. Error Message Views.py from blog.models import Post from notification.models import Notification from django.core.checks import messages from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.urls import reverse_lazy, reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Comment, Post from .forms import CommentForm from django.http import HttpResponseRedirect, JsonResponse from users.models import Profile from itertools import chain from django.contrib.auth.decorators import login_required from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.template.loader import render_to_string import random """ Home page with all posts """ def first(request): context = { 'posts':Post.objects.all() } return render(request, 'blog/first.html', context) """ Posts of following user profiles """ @login_required def posts_of_following_profiles(request): profile = Profile.objects.get(user = request.user) users = [user for user in profile.following.all()] posts = [] qs = None for u in users: p … -
Trying to pass traffic through NGINX container to Django with Kubernetes
I'm stuck on something that I feel is rather simple for someone who may know kubernetes. I a django app I'm trying to deploy to production. Part of that will be adding an SSL cert so I believe to do that I need something like an nginx container for public traffic to hit first. I have this working in docker-compose but our production environment is a kubernetes cluster. I was able to get the kubernetes file to spin up the containers but traffic just goes straight to the django app. How would I configure this to pass traffic through nginx instead? apiVersion: apps/v1 kind: Deployment metadata: name: networkapp-deploy labels: name: networkapp spec: replicas: 1 selector: matchLabels: name: networkapp_pod template: metadata: labels: name: networkapp_pod spec: containers: - name: nginx image: nginx:alpine ports: - containerPort: 8000 - name: redis image: redis:alpine ports: - containerPort: 6379 - name: webapp image: localhost:5000/newweb/webapp:latest ports: - containerPort: 8001 --- kind: Service apiVersion: v1 metadata: name: networkapp-svc spec: selector: name: networkapp_pod ports: - protocol: TCP port: 80 targetPort: 8000 type: LoadBalancer Here is the docker compose file which seems to work if I run it locally off of that, I just need this to work in kubernetes … -
Django: Why im getting NameError in shall if I have correct import in admin.py
I don't really understand why i get NameError when i try run Post.objects.all() in shell.(by using django_extensions) I made migrations and i see posts_post table on db(work fine) and i can do CRUD operations in running applicationon local server. Below is my code and error message. posts app admin.py from django.contrib import admin from .models import Post admin.site.register(Post) settings.py INSTALLED_APPS = [ ... 'django_extensions', 'posts.apps.PostsConfig' ] shell Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 Post.objects.all() NameError: name 'Post' is not defined -
Django comparar mi dato con todos los datos de la base de datos
Estoy tratando de realizar un trabajo en django obtengo mis datos de mi formulario y quiero validar que mi usuario este en la base de datos pero a la hora de hacer la comprobacion solo me compara la primera fila esta es mi funcion enter code here...def Agregausuario(request): t = 'AgregarUsuarios.html' s = 'index.html' if request.method == 'GET': return render(request, t) elif request.method == 'POST': Usu = request.POST.get('user').strip() password = request.POST.get('pass').strip() DatosUsuarios = models.Usuariosss.objects.all() for i in DatosUsuarios: while i.usuario == Usu: messages.success(request, 'Usuario no agregado') return render(request, t) else: conn = pymysql.connect(host='localhost',user='Telefonia',password='170195',db='monitoreodb',) cursor = conn.cursor() sql = "INSERT INTO app_usuariosss(Usuario, password) VALUES('{}', '{}')".format(Usu, password) cursor.execute(sql) conn.commit() conn.close() messages.success(request, 'Usuario agregado') return render(request, t) -
is there way to make page open for logged in user only
I'm trying to make this page for logged in user only and when i write @login_required it don't do anything and page open for all user how to fix this views.py @login_required(login_url='accounts/login/') @register.inclusion_tag('survey/survey_details.html', takes_context=True) def survey_details(context, survey_id): survey = Survey.objects.get(id=survey_id) return {'survey': survey} -
Error running WSGI application ModuleNotFoundError: No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py"
**I have facing issues when i deploy a django project on pythonanywhere error below** Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" wsgi.py """ path = '/home/Fworld/f-worldshop/f_worldSHop' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'f_worldSHop.settings' ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() """ Inner project Path """ README.txt f-worldshop (myenv) 21:33 ~ $ cd f-worldshop/ (myenv) 21:33 ~/f-worldshop (master)$ ls db.sqlite3 f_Usershop f_shop f_worldSHop manage.py media requirements.txt (myenv) 21:33 ~/f-worldshop (master)$ pwd /home/Fworld/f-worldshop (myenv) 21:34 ~/f-worldshop (master)$ cd f_worldSHop/ (myenv) 21:34 ~/f-worldshop/f_worldSHop (master)$ pwd /home/Fworld/f-worldshop/f_worldSHop """ Kindly help me Thanks Regards: Umer Malik Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" -
Collect payments and pay out
I'm developing an iOS application (with a Django backend) with an internal currency system. Users will be able to purchase coins and redeem them for real money. I will not use the in-app purchase but a custom payment system (I'm allowed to do this and the question is not about Apple's guidelines). I'm searching for an API that allows me to collect payment and pay out users as fast as possible globally and without daily/weekly/monthly limitations. My problem is that I don't want to accumulate the earnings on a bank account/credit card since they have limitations in the number of transactions, so performing mass pay outs is not possible. Is there a way to receive payments with Stripe/PayPal/Braintree without transferring funds to a bank account and then pay users quickly with previously accumulated money? If it is possible would you direct me to related resources/documentation? -
Referenced Url works with static number but not with variable
So i'm trying to get product_id to work and every time it comes up with this error:NoReverseMatch at /playground/hello/ Reverse for 'information' with arguments '('',)' not found. 1 pattern(s) tried: ['playground/hello/(?P<product_id>[0-9]+)\Z'] It works perfectly fine if i pass a constant like the number 1 or 2(can go infinitely long based on how many objects are stored in the admin panel) instead of product_id inside the index.html file but the issue with that is that if i click on any link on the first page it redirects to the same thing no matter what i click. index.html {% extends 'base.html' %} {% block content %} <table class="table table-bordered table-hover"> <thead> <tr> <th>Work</th> <th>Type of Work</th> <th>Hours needed</th> </tr> </thead> <tbody> {% for context2 in context%} <tr> <td> <a href={% url 'product:information' product_id %}>{{context2.work}}</a> </td> <td>{{context2.genre}}</td> <td>{{context2.hoursWorked}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} Urls.py from django.urls import path from . import views app_name = 'product' urlpatterns = [ path('hello/', views.hello, name='hello'), path('hello/<int:product_id>', views.detail, name='information') ] Views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404, HttpResponse from .models import products, typeWork def hello(request): context = typeWork.objects.all() context2 = {'context':context} return render(request, 'products/index.html', context2) def detail(request, product_id): context = get_object_or_404(typeWork, … -
django allauth redirect to another page after email verification
I have this issue: I need to redirect to another page when email verification is confirmed and login for the first time after the email verification. I tried to configure this in setting.py, but didn't work. My settings.py: ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = os.getenv('schools/form-school') the url in urls.py is: path('form-school', views.school_list_view, name = 'schools' ), if you have any clue on how to resolve this please comment your ideas, thanks so much!! -
Djangochannelsrestframework hot to send image file?
How can I send image file by websocket using djangochannelsrestframework? Thanks! -
Django getting session 500 error on specific line
I'm trying to run the code here: https://github.com/TwilioDevEd/automated-survey-django. The problem I'm stuck on is in the below function, the first time a text is send, there is no session and request.session.get('answering_question_id') is false/null. The second text sent from the same number (where I can see there is a new row in the django_session table), returns a 500 error on this line request.session.get('answering_question_id'). I see a 500 error is a server error, but I'm stuck on what that could mean for this. I thought the result should just be false/null if 'answering_question_id' isn't available. Any thoughts? @require_http_methods(["GET", "POST"]) def redirects_twilio_request_to_proper_endpoint(request): print("HELLOOOO!") answering_question = request.session.get('answering_question_id') print("YEPPERS") if not answering_question: print('1') first_survey = Survey.objects.first() redirect_url = reverse('survey', kwargs={'survey_id': first_survey.id}) else: print('2') question = Question.objects.get(id=answering_question) redirect_url = reverse('save_response', kwargs={'survey_id': question.survey.id, 'question_id': question.id}) return HttpResponseRedirect(redirect_url) -
Django MultiTenant saas registeration
I have been coding my project using a single DB and tenant_ids for each entry I wanted to switch to django-tenant and have schema based app. My question is about the initial registration. Registration should be a shared app but do i need to create a tenant for "public" regardless so that everyone becomes that tenant when they are registering? And do you add this public tenant with a script onetime when you set up the project so that you have a "public" tenant. Creating a tenant for public feels a bit odd. Or what would be the registration sequence be like( Ideally registration should create the tenants) Ideally my flow should be : you register a tenant with an email so that when tenant registers it sends an email and when you activate that mail you create your first user (admin user) for that tenant. -
Unique PermissionError: [WinError 5] Access is denied IIS Issue
I am currently setting up a django site to run on IIS, however I am running into an issue with the USZipCodes python module, When it goes to call the USZipCodes module if gets an access denied error. I have confirmed all folders regarding this EXCEPT the systemprofile folder has proper permissions for the IIS_IUSRS profile. I would do the systemprofile as well but it just give me more errors and I would prefer not to This module works fine when not IIS, through CMD it works fine, it is only when using IIS to run the app does this occur. I suspect I may just have the cut the module out but I would prefer not too Error Log: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 286, in push json_client['street_name'], zco(json_client['zip']), json_client['state'], json_client['zip'], File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 15, in zco search = SearchEngine() File "C:\Python310\lib\site-packages\uszipcode\search.py", line 153, in __init__ self._download_db_file_if_not_exists() File "C:\Python310\lib\site-packages\uszipcode\search.py", line 173, in _download_db_file_if_not_exists download_db_file( File "C:\Python310\lib\site-packages\uszipcode\db.py", line 33, in download_db_file Path(db_file_path).parent.mkdir(parents=True, exist_ok=True) File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 1614, in mkdir _try_except_filenotfounderror(_try_func, _exc_func) File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 117, in _try_except_filenotfounderror … -
How can I fix AWS Security Key Error Django Project?
I have Greatkart but I can't build this project enter image description here -
Django Signals for User Profile (Customer and Employee)
So I am trying to create a signal to create a profile for a newly created user. However, I need to have two different types of profiles: A customer profile and an employee profile. The type of profile which will be created is decided inside my User model via the "user_type" field: user/models.py: class User(AbstractBaseUser): USER_TYPES = ( ('Employee', 'employee'), ('Customer', 'customer'), ('Vendor', 'vendor') ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) phone_number = models.CharField(max_length=20) user_type = models.CharField(max_length=8, choices=USER_TYPES) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' def __str__(self): return f'{self.first_name} {self.last_name} : {self.email}' def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin # if user.is_employee == True class EmployeeProfile(models.Model): EMPLOYEE_ROLES = ( ('Driver', 'driver'), ('Production', 'production'), ('Manager', 'manger') ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES) def __str__(self): return str(self.user) # if user.is_customer == True class … -
How to transfer django model field data to another field
I have a Django app in which I have videos. The description field for a video is set to CharField but I would like to change it to TextField. I don’t want to lose the data from my CharField but instead transfer it over to my TextField. How would I go about doing so? -
Css background url doesn't change django
I'm beginer and have realy dumb problem. In my Django project, i'm trying to make background picture for html page. CSS styels work right but pcture doesn't work. Here is css code in vscode: background: #9a8e77 url("image/intro-bg.jpg") center no-repeat; But in browser background have another url: browser If i change it to background: #9a8e77 url("image/intro-bg.jpg") center no-repeat; by my hands in browser it works. This problem only with background, another pictures have the right url "image/". Powersheel teling me this - ""GET /static/img/intro-bg.jpg HTTP/1.1" 404 1807" I check it 100 times, but don't get what's wrong.