Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot send React POST request to django api error
I am attempting to send a post request containing the name of a genre of music from react to my django api so that this genre can be put into a query param to be searched using the spotify api. Genre.js // Fetch and map list of genres, when a genre is clicked it is saved to state, then sent in a post request to my endpoint. import React, { useState, useEffect } from "react"; function Genres() { const [genres, setGenres] = useState([]); const [clickedGenre, setClickedGenre] = useState(""); const [type, setType] = useState("") useEffect(() => { fetch("http://localhost:8000/api/genres/") .then((response) => response.json()) .then((data) => setGenres(data.genres)) .catch((error) => console.log(error)); }, []); function handleClick(genre) { setClickedGenre(genre); const query_params = { genre: genre, }; // const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; fetch("http://localhost:8000/api/search/", { method: "POST", headers: { "Content-Type": "application/json", // "X-CSRFToken": csrftoken, // Add the CSRF token to the headers }, body: JSON.stringify(query_params), }) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.log(error)); } return ( <div> <div className="genre-list-container"> <ul className="genre-list"> {genres.map((genre) => ( <li className="genre" onClick={() => handleClick(genre)} key={genre} > {genre} </li> ))} </ul> </div> </div> ); } export default Genres; views.py // Retrieve post request and put result into the "q" param. Then make spotify … -
How to know the size of my Django pages before deployment?
I am developing my very first website. I would like to know the page size before attempting to deploy it and whether I am doing something really silly/inefficient. Is there at least any tool similar to https://tools.pingdom.com/ while in development? -
Django Admin: Change status without updating the password
I am new to Django and I have a problem regarding Django custom user model. I am changing the status of the user to for example is_staff=True from admin panel but it requires password to made changes. I don't want to change or update the user password. So what's I am missing here. I also tried few things but didn't find anything. Thanks for your help in advance. -
Unit test in PyCharm fails if imported a class
With PyCharm, we are trying to create a unit test file tests/test_poc.py for a proof-of-concept class PocFunctional, and we have added DJANGO_SETTINGS_MODULE=applicationproject.settings into the "Python tests" section of the "Run/Debug Configurations". However, if we uncomment from app.poc import PocFunctional in the below sample source code to import the class under test, the unit test will get a run-time error saying django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. Although the file runs OK if not imported the PocFunctional class. We are new to the unit test of Python in PyCharm environment, so we highly appreciate any hints and suggestions. Technical Details: Partial unit test source code: from unittest import TestCase # from app.poc import PocFunctional class TestPocEav(TestCase): def test_get_transaction(self): # self. Fail() return # ... other test methods Exception: /data/app-py3/venv3.7/bin/python /var/lib/snapd/snap/pycharm-professional/316/plugins/python/helpers/pycharm/_jb_unittest_runner.py --target test_poc.TestPocFunctional Testing started at 5:03 PM ... Launching unittests with arguments python -m unittest test_poc.TestPocFunctional in /data/app-py3/APPLICATION/tests Traceback (most recent call last): File "/var/lib/snapd/snap/pycharm-professional/316/plugins/python/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "/usr/local/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/local/lib/python3.7/unittest/main.py", line 147, in parseArgs self.createTests() File "/usr/local/lib/python3.7/unittest/main.py", line 159, in createTests self.module) File "/usr/local/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/lib/python3.7/unittest/loader.py", line … -
Requests multiplying with each interaction with input
I'm having trouble with requests that multiply undesirably and I haven't found a solution so far. It turns out that, I have a select html that when an option is chosen, it makes a request to the backend and returns the values of the db in the input below the form, so far so good, the query is being executed and returned correctly, however every changing the option of this select without reloading the page, the requests are multiplied, ex: when I select for the first time, the request is made 1 time, when I select again the request is made 2 times in a row, and this escalates, I tested changing the select 9 times sequences and the same request is performed 9 times in sequence with the same parameters, with the same response, as if there were a variable that at each interaction adds 1 and multiplies the request. here a sample of the select changed 3 times [15/Mar/2023 23:46:29] "GET /propriedades/atualiza_propriedade/17/ HTTP/1.1" 200 102 [15/Mar/2023 23:46:32] "GET /propriedades/atualiza_propriedade/20/ HTTP/1.1" 200 108 [15/Mar/2023 23:46:32] "GET /propriedades/atualiza_propriedade/20/ HTTP/1.1" 200 108 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" 200 136 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" 200 136 [15/Mar/2023 23:46:35] "GET /propriedades/atualiza_propriedade/22/ HTTP/1.1" … -
Django query gives "SELECT DISTINCT ON expressions must match initial ORDER BY expressions" error even specified the same order
VirtualMachine.objects.order_by('pool__customer').distinct('pool__customer') Been thru this ticket already also tried asking ChatGPT (lol), the answer doesn't have .all() but gave the same error, wouldn't think it made a difference anyway cos .order_by('pool__customer') should overwrite it already -
Django signal creates UserProfile from listening to User, but it's empty?
I'm new to Django and trying to create a signal that listens to a custom User model I've built. My intention is that when a new User is created, that a profile for them will also be automatically created. To me it seems that my signal itself works, as when I use the /admin screen I can add a User and it automatically creates their profile. However, when I try to add a new User through the front end of the application, it appears that the signal does indeed detect a new User being created and creates a Profile for them. But when I go into the /admin screen to have a look at it, it's empty. When I say empty, I mean that the Profile record is created, but none of the fields are populated. This is then causing further errors in my app, because I can't use the User to pull up the User's Profile and render it, because it's empty and not connected to a User. What am I doing wrong? My hunch is that something is wrong with my view function. registerUserParticipant and registerUserSupervisor are called when creating a new user in the front end. editAccount … -
how can i put a user's information in his profile
I work on django project, with another front-end developer, so it's not django that handles a lot of things in html. I created a user model with Abstractuser, now I want to display the information of users and super users but it does not work how to make it work can you help me please My views file @login_required def admin_profil(request): message='' user= request.user if user.is_superuser: print('________________________________________________________________dream________________________________________________') user = get_user_model().objects.all() else: print('________________________________________________________________false________________________________________________________________') message= 'You are not a superuser' return render(request , 'admin_app/admin_profil.html',{'message': message,'user': user}) my html file <div class="card bg-white profile-content"> <div class="row"> <div class="col-lg-4 col-xl-3"> <div class="profile-content-left profile-left-spacing"> <div class="text-center widget-profile px-0 border-0"> <div class="card-img mx-auto rounded-circle"> <img src="/static/admin_app/assets/img/user/u1.jpg" alt="user image"> </div> </div> <hr class="w-100"> <center> <div class="contact-info pt-4"> <h5 class="text-dark">Informations</h5> {% if user.is_authenticated %} <p class="text-dark font-weight-medium pt-24px mb-2">Adresse Mail</p> <p>{{user.email}}</p> <p class="text-dark font-weight-medium pt-24px mb-2">Numéro De Téléphone</p> <p>{{ user.phone}}</p> <p class="text-dark font-weight-medium pt-24px mb-2">Social Profil</p> <p class="social-button"> <a href="#" class="mb-1 btn btn-outline btn-twitter rounded-circle"> <i class="mdi mdi-twitter"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-linkedin rounded-circle"> <i class="mdi mdi-linkedin"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-facebook rounded-circle"> <i class="mdi mdi-facebook"></i> </a> <a href="#" class="mb-1 btn btn-outline btn-skype rounded-circle"> <i class="mdi mdi-skype"></i> </a> my uls files path('ajout_produit/', views.add_product, name='add'), … -
NOT NULL constraint failed null=True blank=True
despite having null and blank true in my models I always get NOT NULL constraint failed: user_mgmt_profile.user_id I've deleted the database, deleted migrations, run commands again, and the error still persist. Where do you see the issue Basically Im automatically connecting user to new profile on post request models class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) gym = models.OneToOneField(Gym, null=True, blank=True, on_delete=models.DO_NOTHING) create function in viewset def create(self, request): request.data['user'] = request.user.id serializer = ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() data = serializer.data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = '__all__' class GymSerializer(serializers.ModelSerializer): place = LocationSerializer(read_only=True) class Meta: model = Gym fields = '__all__' class ProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): user = UserSerializer(read_only=True) gym = GymSerializer(read_only=True) class Meta: model = Profile fields = '__all__' depth = 1 edit I've printed out the request.data['user'] and i can see the UUID of the current user -
AppConfig.ready() is running before the migrations on manage.py test
I am trying to use Django's AppConfig.ready() method to run some some query on one of the models to retrieve some data. I have the following code: class NewsConfig(AppConfig): name = "apps.news" verbose_name = "News" def ready(self): NewsType = self.models.get("newstype") NewsType.names = NewsType.objects.values_list("name", flat=True) then, on urls.py I'm using them as follow: news_type_names_regex = generate_regex(NewsType.names) router = DefaultRouter() router.register(r'news/' + news_type_names_regex, NewsModelViewSet, basename='news') This works fine when the application runs (using uvicorn or runserver), but when running tests, the AppConfig.ready() gets executed before the migrations are run, which results in the following error: ... django.db.utils.OperationalError: no such table: news_newstype I've read the warning on the docs, but I don't think it is related to this issue. The reason why I'm doing this on the AppConfig.ready() is because it needs to be done somewhere after django.setup() but not in an async request context (as I'm using django channels and running the application ASGI). -
Failed To Fetch Error with Django Application
Working on a Django app and running in to a failed to fetch error intermittently from my JS code. You can see the network responses below - where the error is intermittent from the server (currently on localhost:8000) My django server logs are showing nothing - so 'connection refused' and 'empty response' are confusing. On the JS side I am using fetch(data.getAttribute('action'), { method: data.getAttribute('method'), body: new FormData(data), headers:{ "X-CSRFToken": csrf_token, "X-Requested-With": "XMLHttpRequest"}, }).then(res=>res.json()) .then(function (data) { console.log(data) document.getElementById('create-submit-button').style.border = "2px solid #ebebeb" if(data.status == 'success'){ //happy path will be to add photos on good response console.log('happy path') } else { Swal.fire({ icon: 'error', title: 'there was an issue with your request', text: data.message, }) } }) .catch(error => console.log('Error: ', error)) } My django view is as follows: @login_required(login_url='login') def create(request): if request.method == "POST": if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' and request.user.is_authenticated: print(request.POST) form = SpinForm(request.POST) if form.is_valid(): user = request.user spin = Spin() spin.prompt = form.cleaned_data['prompt'] spin.user = user spin.orientation = form.cleaned_data['orientation'] # save spin to get many to many relationship spin.save() spin.themes.add(*form.cleaned_data['themes']) # update users total spins user.current_spins += 1 user.save() # themes = request.POST.getlist('theme') computed_prompt = '' if len(spin.themes.all()) > 0: for theme in spin.themes.all(): computed_prompt += … -
Django router.register gets called for every request
I'm inheriting this project that has a urls.py which imports a set of urlpatterns as such: # myapp.rest router = routers.DefaultRouter(trailing_slash=True) router.register(r'campaigns', CampaignViewSet, 'campaigns') router.register(r'campaign-search', CampaignSearchViewSet, 'campaign-search') router.register(r'guestbook', GuestBookViewSet) router.register(r'updates', UpdateViewSet) router.register(r'albums', AlbumViewSet) urlpatterns = [ url(r'^api/', include(router.urls)), ] Now in another set of urls, i'm adding some new api endpoints: urlpatterns = [ url(r'^rest_1/campaigns/(?P<filter>\w+)$',views.RestCampaignView.as_view()), ] So my main urls.py looks like: from myapp.rest import urlpatterns as rest_urls # router.register calls urlpatterns = patterns( url(r'^v2/api/', include('hhl.apps.rest_1.urls')), ) urlpatterns += rest_urls Now whenever I call my new rest endpoints, v2/api..., I'm seeing that the myapp.rest urlpatters are re-registered, and it's actually calling each viewset before it's even getting to my new view. This is Django 1.8.9 so it's a bit dated. How can I fix this so that it's not calling every Viewset for every request? -
Run a subprocess and show output in realtime AND log stderr
Yo, I am using python to run a subprocess that takes a while to execute, and that may or may not succeed. My question: How can I keep realtime output of the process AND collect error lines? Thanks Here is my code so far: process = subprocess.Popen("my_cmd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) complete_err_message = '' while True: output = process.stdout.readline() error = process.stderr.readline() if output == b'' and error == b'' and process.poll() is not None: if complete_err_message != '': # handle err here print(complete_err_message) break if output: print(output.strip().decode('utf-8')) if error: complete_err_message = complete_err_message + '\n' + error.strip().decode('utf-8') That seems to run very well when the process fails. All the error lines are taken in and stored under complete_err_message. However, when the process doesn't fail, I lose the realtime output and the program seems to lock at the error = process.stderr.readline() step. I am guessing this is because the stderr PIPE is empty, but I am not sure and I don't know how to bypass that. -
How can I upload a django application with this libarys in a free server?
Hi I want to deploy one django app project that I did, but I can't, already tried heroku22, PythonEverywhere and more. I also use python-3.10 and the currently windows 11. heroku-22 - Tried as the tutorials said but always dropped error 404. pythoneverywhere - Was the closed one to upload but couldn't download some libarys. -
How to create two table columns (<td>) in html from one context using Django?
I am using dataTables to show my data, It's just names of some places which i want to put in two columns instead of one. I created two tags in table which allowed me to have two columns but i don't know how to effectively populate it and still have normal pagination. Places even_name odd_name even_name odd_name I tried splitting queryset in two (odd and even) and then used zip() on it. That kinda worked but it wouldn't show last set of items because some lists were uneven. If i tried to iterate over longer list with itertools i would get an error because that one pair has an empty element <table data-page-length='15' id="table" class="display" style="width:100%"> <thead> <div class="col-4"> <tr> <th class="text-end erlorefont col-6" style="color:orange">{{ title.0 }}</th> <th></th> </tr> </div> </thead> {% if lore_list|length > 29 %} <tbody> {% for odd, even in zipped_list %} <tr> <td class="erlorefont "><a style="text-decoration:none;" href="{% url 'lores:loreitems' odd.id %}">{{odd}}</a></td> <td class="erlorefont "><a style="text-decoration:none;" href="{% url 'lores:loreitems' even.id %}">{{even}}</a></td> </tr> {% endfor %} </tbody> {% endif %} </table> I expect something like this in case there is uneven number of elements in a zipped item. I want to have two columns per page with 15 … -
Issue: "Page not found (404)"
So when I'm trying to visit the products/add_to_wishlist/ URL, it gives me the error "Page not found 404". I've been in my URLs and it all seems to be fine, I can't find the issue. Here is my code: urls.py (Products app) from django.urls import path from . import views urlpatterns = [ path('', views.all_products, name='products'), path('<int:product_id>/', views.product_detail, name='product_detail'), path('add/', views.add_product, name='add_product'), path('edit/<int:product_id>/', views.edit_product, name='edit_product'), path('delete/<int:product_id>/', views.delete_product, name='delete_product'), path('wishlist/<int:product_id>/', views.add_to_wishlist, name='add_to_wishlist'), path('wishlist/remove/<int:product_id>/', views.remove_from_wishlist, name='remove_from_wishlist'), path('submit_review/<int:product_id>/', views.submit_review, name='submit_review'), ] urls.py (main app): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls')), path('products/', include('products.urls')), path('bag/', include('bag.urls')), path('checkout/', include('checkout.urls')), path('profile/', include('profiles.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: @login_required def add_to_wishlist(request, product_id): product = Product.objects.get(id=product_id) wishlist, created = Wishlist.objects.get_or_create(user=request.user) wishlist.products.add(product) return redirect('wishlist') @login_required def remove_from_wishlist(request, product_id): product = get_object_or_404(Product, pk=product_id) wishlist = Wishlist.objects.get(user=request.user) wishlist.products.remove(product) return HttpResponseRedirect(reverse('wishlist')) wishlist.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1>My Wishlist</h1> <div class="row"> {% if wishlist.products.all %} {% for product in wishlist.products.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-title">{{ product.name }}</h2> <p class="card-text">{{ product.description }}</p> <p class="card-text">$ {{ product.price }}</p> <form action="{% url 'remove_from_wishlist' … -
access-control-allow-headers doesn't change after setting corsheaders djang
This is my middleware settings about Corsheaders and other middleware, and i have installed django-cors-headers an put it into installed_app INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "main", "rest_framework", "rest_framework_simplejwt.token_blacklist", "django_filters", "drf_spectacular", "corsheaders", ] CORS_ALLOWED_ORIGINS = [ "http://hypeandplay.com", ] CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", # "hypeandplay.middleware.CustomCorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] i want to input other allow headers, ex: authorization, but i don't know why the response headers didn't change so i got stricted by cors setting Allow_Headers: CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] Response from browser: enter image description here i tried to add authentication, but after i add it in the production, it got error cause of cors enter image description here -
Populate readonly nested serializer
Im using ModelViewSets and I have nested serializer for those models class Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) place = models.OneToOneField(Place, on_delete=models.DO_NOTHING) bio = models.TextField(null=True) class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] def __str__(self): return self.email How can I autocomplete a newly created profile with 1:1 relation to User? class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'is_superuser', 'is_staff', 'groups', 'user_permissions') class ProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): user = UserSerializer(read_only=True) place = PlaceSerializer(read_only=True) class Meta: model = Profile fields = '__all__' depth = 1 As you can see I'm using 'drf-writable-nested' and it works okay but I can't figure it out how to automatically connect profile to user on new profile creation -
Saving changes in FormSet with related models
Business logic: Two employees. First employee create application with input 'type_car'. Second employee update application input 'reg_mark' and 'brand'. So, on first step i can create application. I have for this 'type_car' select input field with good view, because it get elements from model with str method. But, i can't update application on second step. If i select 'reg_mark' and try save my changes, i get initial application with empty field 'reg_mark'. And additional, for application i get object from model 'Car' with str method 'reg_mark' and it identically show in select fields 'brand' and 'reg_mark'. How i can fix it? Models: class Application(models.Model): reg_mark = models.ForeignKey(Car, ... ) brand = models.ForeignKey(Car, ... ) type_car = models.ForeignKey(TypeCar, ... ) class Car(models.Model): brand = models.CharField(max_length=50) reg_mark = models.CharField(max_length=10) type = models.ForeignKey('TypeCar', ... ) def __str__(self): return self.reg_mark class TypeCar(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title I' using two identically FormSets for input (Add and Close) class ApplicationCloseForm(forms.ModelForm): class Meta: model = Application fields = { 'reg_mark', 'brand', 'type_car', } ApplicationCloseFormSet = modelformset_factory( Application, form=ApplicationCloseForm, extra=0, can_delete=False, ) view for create application def application_add(request): if request.method == 'POST': formset = ApplicationAddFormSet(request.POST or None) if formset.is_valid(): form.save() else: formset = ApplicationAddFormSet(queryset=Application.objects.none()) return … -
Change Display Values for Cloudinary Field in Django Admin
So in my model I have: cloudinary_logo = CloudinaryField('image', blank=True, null=True) In the admin for this model, I list the field in fields. And it displays as such. I'd like to update the name to be "Logo Location" and the description to say something like "drag image file here to upload!" How would you go about doing this? TIA I'm considering a custom method that would allow me to write the html, but I don't want to screw up the functionality of the Cloudinary Field itself, so I'm not sure if this would be the best way. I've written a custom save_model that looks as such: def save_model( self, request: str, obj: Community, form: forms.ModelForm, change: str ) -> None: #check if cloudinary logo was changed super().save_model(request, obj, form, change) if 'cloudinary_logo' in form.changed_data: #move it, rename it moved_file_name = f"{ENV}/logos/{obj.id}-{obj.external_id}-{obj.name}" cloudinary.uploader.upload(obj.cloudinary_logo.build_url(), public_id=moved_file_name) obj.cloudinary_logo = moved_file_name obj.save() -
Body width changes on mobile devices. Footer width changes
When resizing the browsers window. Or when I use the responsive view in the dev tools, after about 600px the body gets smaller. Here is an image of my problem: Somehow the problem only exists in the chrome browser, in the Safari Browser it works. I created a JS Fiddle to show you the problem: https://jsfiddle.net/fpq6nyco/2/ I am pretty sure that the error sits in these lines: @media (max-width: 726px) { .toggle-button { display: inline; } .navbar-links { display: none; width: 100%; z-index: 10; background-color: var(--primary-color); } .navbar { flex-direction: column; align-items: flex-start; } .navbar-links ul { width: 100%; flex-direction: column; } .navbar-links.active { display: flex; } .logo { display: inline; } .navbar-controls { display: flex; flex-direction: row; align-items: center; justify-content: space-between; height: 100%; } .container{ display: flex; flex-direction: column; justify-content: space-around; align-items: center; width: 100%; } .item{ width: 100%; } .info-section{ margin-top: 200px; } .community-cont{ display: flex; flex-direction: column; align-items: center; justify-content: space-around; margin-top: 50px; margin-bottom: 50px; } footer { width: 100%; height: auto; background-color: var(--dark-color); display: flex; flex-direction: column; align-items: center; justify-content: space-around; padding-top: 20px; padding-bottom: 20px; } .item-container { display: flex; flex-direction: column; align-items: center; justify-content: space-around; height: 40vh; } .text-cont-footer { color: var(--primary-color); width: 100%; } … -
Apply an update to a queryset involving a foreign key
Lets say I have something like the code below, where I can nicely apply the update method to change the engine type of the cars contained in the query set vintage_cars. Is it possible to use update in a similar fashion for the code using the for loop, where a foreign key is involved? class Driver(Model): name = CharField() licence = CharField() class Car(Model): driver = models.ForeignKey(Owner) status = CharField() type = CharField() engine = CharField() vintage_cars = Car.objects.filter(type="vintage") vintage_cars.update(engine="gas") for c in vintage_cars: driver = c.driver if driver and driver.licence not in VALID_LICENCES: c.driver = None c.status = "IMPOUNDED" d.save() I'm thinking I need to apply a second filter involving this clause: if driver and driver.licence not in VALID_LICENCES: to vintage_cars, but I'm not sure if that makes sense in terms of efficiency. -
I can access Django server directly despite nginx reverse proxy
I have a Django Rest Framework server running with Gunicorn with this command : gunicorn --bind 0.0.0.0 --forwarded-allow-ips="*" partyapp.wsgi:application --access-logfile - --error-logfile - --log-level debug I have Nginx as a reverse proxy with the following configuration: server { listen 80; server_name 162.19.70.85; location /static/ { root /var/www; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } It is working well: I can access the service with http://{IP} but also with http://{IP}:8000 which hits Django server directly. I don't think it is a good behavior and I want people to be "forced" to go through the reverse proxy. How can I do that ? Thanks. -
Uneven and unfair fight against JavaScript
Hey i need a help in JS organization. I working on project in Django and now i have moment that i can't jump at all. I have a site where the form of inputs is on many sites one after another. For now i have some JS written in witch i can move on sites but the real problem IS: I need to take data ('Categories') from checkbox in first step and this decide what data will show on step three where should show up only Institutions which have the same categories. Then in step 4 i user give the adress etc. and in step 5 (Summary) data from steps before should shown on screen. In step 5 is a button confirm to send data back to Django Please help my mental health Models from django.db import models from django.contrib.auth.models import User FUNDATION_TYPE = ( (1, 'Fundacja'), (2, 'Organizacja pozarządowa'), (3, 'Zbiórka lokalna'), ) class Category(models.Model): name = models.CharField(max_length=64) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) type = models.IntegerField(choices=FUNDATION_TYPE, default=1) categories = models.ManyToManyField(Category) class Meta: verbose_name_plural = "Institutions" def __str__(self): return self.name class Donation(models.Model): quantity = models.IntegerField() categories = models.ManyToManyField(Category) … -
Django HTML Select not loading correct option
Im having some trouble at my first Django project. I have a ListView in which I have several comboboxes (select) to filter data in a table. Im using Foundation for my site The problem I´m having is that once I establish the "filters" for the queary in my comboboxes, data is presenting fine, but after loading the table, one of the selects is not loading the correct option(last lookup) This is my ListView code: class ListSales(LoginRequiredMixin, ListView): template_name = "sales/list.html" context_object_name = 'sales' login_url = reverse_lazy('users_app:user-login') paginate_by = 5 def get_queryset(self): client = self.request.GET.get("clientselect", "") payment_method = self.request.GET.get("paymentselect", "") date1 = self.request.GET.get("date1", '') date2 = self.request.GET.get("date2", '') product = self.request.GET.get("productselect", '') if date1 == '': date1 = datetime.date.today() if date2 == '': date2 = datetime.date.today() queryset = Sale.objects.get_sales_list( date1, date2, client, payment_method) qty_total_product = 0 if product != '0' and product != '': print(Product.objects.get(id=product).full_name) print(queryset) for querysale in queryset: print(querysale) for query_sale_detail in querysale.sale_details(): print(query_sale_detail.product.full_name + " " + str(query_sale_detail.count)) if str(query_sale_detail.product.id) == product: qty_total_product += query_sale_detail.count print(qty_total_product) obj_sales_list_filter, created_obj_sales_list_filter = SalesListFilters.objects.get_or_create( id=1, defaults={ 'datefrom': date1, 'dateTo': date2, 'client': Client.objects.search_id(client), 'payment_method': PaymentMethod.objects.search_id(payment_method) }) if not created_obj_sales_list_filter: obj_sales_list_filter.datefrom = date1 obj_sales_list_filter.dateTo = date2 obj_sales_list_filter.client = Client.objects.search_id(client) obj_sales_list_filter.payment_method = PaymentMethod.objects.search_id( payment_method) obj_sales_list_filter.save() …