Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why STATIC_URL is working without STATIC_ROOT? [Python 3.9]
I'm pretty confused here, I am trying to retrieve my static files (for testing purposes) via url with STATIC_URL setting, the problem is that I dont have specified the STATIC_ROOT setting and yet the STATIC_URL setting is still working Why is this supposed to work? the documentation says of STATIC_URL: URL to use when referring to static files located in STATIC_ROOT. But again, STATIC_ROOT is not specified; so why is this working?, i.e, going to the following url: http://127.0.0.1:8000/static/js/main.js is working, dont know why -
COUNT field incorrect or syntax error in filter __in django
I am trying to fetch data in the below manner: ts= Tags.objects.filter(tagtype=2) ls= list(p.entity for p in ts) print(ls) print(len(ls)) users= Users.objects.filter(email__in=ls) print(users) When I checked in DB len(ls) is greater than the result count from Users Table. How do I filter data from Users when the list being passed has more values... like list has 4560 values but matching values in users table is only 4199. I am able to get the data on SQL side, but not able to fetch the data using django filter. -
How can i add a team member in multi tenancy schema
I'm working on a small project using Django with Multi-Tenancy Schema Package, I would like to know how can I add a team member (the first time I use Multi-Tenancy Philosophy ) -
elasticsearch returns RequestError 400
GET 31searchskurecord/_search { "query": { "match_all": {} } , "sort": [ { "sort_order": { "order": "desc" } } ] } returns RequestError(400, 'search_phase_execution_exception', 'No mapping found for [sort_order] in order to sort on') -
Django Admin upload new models to current
recently started programming on django, still trying to understand it. Anyway, i've been assigned to maintain a website/webapp (i don't know how to call it) made in django, as part of the work produce modifies as client needs. Everything was fine untill the modifies are about the current setup. I've made a lot of tries but can't understand why adding new models to the project is not working. The project Listings contains the following models: Listing(Immobili) Photo Owner(Proprietario) Zone(Zona) All the models are related to the Listing. Current Admin form Here a code example (admin.py): @admin.register(models.Photo) class PhotoInline(admin.TabularInline): .... @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): .... inlines=[PhotoInline,...] What i'm trying to achieve is to add the concept of Video, but easier than photo, so i've made a model Video as follow: models.py: class Video(models.Model): listing = models.ForeignKey(...) video_name = models.CharField(...) video_url = models.CharField(...) admin.py: class VideoInline(admin.TabularInline): model = models.Video extra = 1 @admin.register(models.Listing) class ListingAdmin(admin.ModelAdmin): .... inlines=[PhotoInline,VideoInline...] After those modifies i've launch the python manage.py makemigrations listings python manage.py migrate listings No output error, and the page was working as before. Any advice to upload this modify? Thanks to anyone that will just read the question. -
Django edit details for an existing post via a form
I am working on a job portal project and the recruiter can post an internship. After that, he has the option to edit his post as well. To do that, I display a form. (I am not using Django forms btw). I want to display the values as they are stored in the db in the form input fields. I am getting issues for radio, dropdown, ckeditor textfield and a dynamic input field for skills. Please guys, can you help? Here is my code snippet: <label>Internship Title</label> <input type="text" class="form-control" name="internship_title" value="{{ internship.internship_title }}" required> <input type="radio" id="customRadioInLine1" name="internship_mode" class="custom-control-input" value="Office" {% if '{{ internship.internship_mode }}' == 'Office' %} checked="checked" {% endif %}> <label class="custom-control-label" for="customRadioInLine1">Office</label> <input type="radio" id="customRadioInLine2" name="internship_mode" class="custom-control-input" value="Work From Home"> <label class="custom-control-label" for="customRadioInLine2">Work From Home</label> <label for="industry_type">Industry Type</label> <select class="form-control" id="industry_type" name="industry_type"> {% for ind_type in industry_types %} <option value="{{ind_type}}">{{ind_type}}</option> {% endfor %} </select> <label>Required Skills</label> <div class="input_skills_wrap"> <div> <input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-primary add-more-skill" type="button"><i class="glyphicon glyphicon- plus"></i></button> </div> </div> <label>Internship Description</label> <textarea name="internship_desc" required></textarea> <script> //EMPLOYMENT SKILLS $(".add-more-skill").click(function(e){ e.preventDefault(); $(".input_skills_wrap").append('<div><input type="text" class="form-control" name="internship_skills[]" required><button class="btn btn-danger remove-skill" type="button"><i class="glyphicon glyphicon-minus"></i></button></div>'); }); $(".input_skills_wrap").on("click", ".remove-skill", function(e){ e.preventDefault(); $(this).parent('div').remove(); }); CKEDITOR.replace('internship_desc'); -
how write custom view for page model in wagtail
i have page object as below in models.py: class PostPage(Page): template = 'Blog/post_page.html' # Database fields body = RichTextField() main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) promote_panels = [ InlinePanel('related_links', label="Related links"), MultiFieldPanel(Page.promote_panels, "Common page configuration"), ] .... and i want mix this page with other view as below in views.py: class PostPageView(PermissionMixin, PostPage): required_permission = 'special_user' or some views of django-role-permissions or generic-views how can i do that? after mixing them together how explain for context processor to using PostPageView instead of PostPage? -
Django: MultiSelect Field. How to store user checkbox's in database?
I am using Django MultiSelectField package, to allow tutors to choose what grade level they are comfortable teaching. However, I can't seem to find a way to store the user inputs in Django's db. Is this possible? This is the admin page for the field grade_level. Admin This is what the user sees. User. I can get a list of strings with Django's .getlist(). However, I cannot find a way to "check off" these values in the admin dashboard. Thank you! Template Model Form -
Ways to ban users in django
I want a kind of system to ban users. It could be in the admin, or it could be using code. If it's code, then it should allow me to ban certain users, for a certain period of time. It should redirect me to some page saying you are banned. If it's admin, then it's probably a package or module, with the same requirements. Please let me know how I can do this. Thanks! -
How to cache individual Django REST API POSTs for bulk_create?
I have a Django REST API endpoint. It receives a JSON payload eg. { "data" : [0,1,2,3] } This is decoded in a views.py function and generates a new database object like so (pseudo code): newobj = MyObj.(col0 = 0, col1= 1, col2 = 2, col3 = 3) newobj.save() In tests, it is 20x faster to create a list of x1000 newobjs, then do a bulk create: Myobj.objects.bulk_create(newobjs, 1000) So, the question is how to save individual POSTs somewhere in Django ready for batch writes when we have 1000 of them ? -
How can I make this code for getting objects for my list shorter?
I am retrieving database objects to add to a dict, but the keys can't be duplicates, so I've done it this way: carb1 = random.choice(carbs) protein1 = random.choice(proteins) carb2 = Food.objects.filter(category='Carbs').exclude(name=carb1.name)[0] protein2 = Food.objects.filter(category='Protein').exclude(name=protein1.name)[0] veg1 = random.choice(vegs) veg2 = Food.objects.filter(category='Vegetables').exclude(name=veg1.name)[0] meals = [carb1, protein1, carb2, protein2] exclude_these = [o.name for o in meals] carb3 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein3 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg3 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb3) meals.append(protein3) meals.append(veg3) exclude_these = [o.name for o in meals] carb4 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein4 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg4 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb4) meals.append(protein4) meals.append(veg4) exclude_these = [o.name for o in meals] carb5 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein5 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg5 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] meals.append(carb5) meals.append(protein5) meals.append(veg5) exclude_these = [o.name for o in meals] carb6 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0] protein6 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0] veg6 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0] But this just seems like a ridiculous amount of code to achieve what I want. Is there a way I can shorten this? -
Comment mettre à jour mon stock lorsque je modifie une vente
I am trying to update my inventory after modifying a sale. When I register a new sale, the code works perfectly but when I make a modification on the quantity sold, the stock update is not done Please help me immediately. Excuse me for my crooked English, I am French speaking lol. here is my code. Models.py class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Produit") client = models.ForeignKey( Customers, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Client") commercial = models.ForeignKey( CustomUser, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Commercial(e)") sale_quantity = models.PositiveIntegerField( default=None, blank=True, null=True, verbose_name="Quantité vendu") class Meta: verbose_name = 'Vente' verbose_name_plural = 'Ventes' ordering = ['-id'] def __str__(self): return self.product.item_name View.py # SALE CREATE @login_required(login_url="/login/") def sale_create(request): form = SaleCreateForm(request.POST or None) template_name = "moonvisions/add_sale.html" if form.is_valid(): sale = form.save() product = sale.product product.quantity -= sale.sale_quantity product.save() messages.success(request, 'Enregistré avec succès !') return redirect('/marketing/sale_list') context = { "form": form, } return render(request, template_name, context) # UPDATE SALE @login_required(login_url="/login/") def update_sale(request, id): # command = Stock.objects.all() sale = Sale.objects.get(pk=id) form = SaleCreateForm(instance=sale) template_name = 'moonvisions/add_sale.html' if request.method == 'POST': form = SaleCreateForm(request.POST, instance=sale) if form.is_valid(): instance = form.save(commit=False) instance.save( messages.info(request, 'Modifié avec succès !') return redirect('/marketing/sale_list') context = {'form': form} return render(request, template_name, context) -
Button in bootstrap form doesn't submit text from imput
I'm exercising an easy project in Django. I have a problem with the bootstrap button. The button generally works, because it gets over csrf_token to my home view in the request object but it doesn't submit data from my input, and here is my question. Why? My form: <form class="d-flex" action="{% url 'home' %}" method="post"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="your new task" aria-label="Search"> <button value="Send" type="submit" class="btn btn-outline-secondary" name="no_dalej">Add to list</button> </form> The request object looks like this: <QueryDict: {'csrfmiddlewaretoken': ['fJNmnuulcaNB7SETFNagSFfsfiynOCwyw0LMoALPSlEcYFnxqIFMxPm7VliUylwm'], 'no_dalej': ['']}> Any ideas? -
Postman POST request returning None in django
I'm trying to send POST requests using postman to an API in a django server. The API is an APIView : class LoginView(APIView): template_name = 'login.html' from_class = LoginForm def post(self, request, format=None): data = request.data username = data.get('username', None) password = data.get('password', None) print(username) and here is the postman request in the joint image The problem is I'm always getting None username and password. Please if you can spot the problem can you guide me. -
Django objection creation failing due to FOREIGN KEY constraint failure (IntegrityError )
My website has a comment section where user can leave comments on a product . The comments on the product page will be stored in a model called 'ProductReview'. Here is the code for the model : class ProductReview(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) name = models.CharField(blank=True,max_length=20) stars = models.IntegerField() content = models.TextField(blank=True) date_added = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, on_delete=models.CASCADE) Now the view associated with the model are as follows Note:The entire view isnt relevant to the error. The part relevant to the saving comment is the second 'request.POST' which I have denoted with a python comment using # : def product(request, category_slug, product_slug): cart = Cart(request) product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug) if request.method == 'POST': form = AddToCartForm(request.POST) if form.is_valid(): quantity = form.cleaned_data['quantity'] cart.add(product_id=product.id, quantity=quantity, update_quantity=False) messages.success(request, 'The product was added to the cart') return redirect('product', category_slug=category_slug, product_slug=product_slug) similar_products = list(product.category.products.exclude(id=product.id)) # this part is for saving of the user comments to productreview model if request.method == 'POST': stars = request.POST.get('stars', 3) content = request.POST.get('content', '') name = request.POST.get('name', '') created_by = request.user review = ProductReview.objects.create(product=product, name=name, stars=stars, content=content, created_by=created_by) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # this marks the end of the code relevant to saving the user comment if len(similar_products) >= … -
Passing Editable Fields as validated_data method of Django-Rest-Framework Serializer
I'm writing a contacts service in Django-REST-Framework. I have a Contact Model and a PhoneNumber Model which has a foreignKey field that shows which contact does it belong to. Here are my models: class ContactModel(models.Model): firstname = models.CharField(max_length=50, blank=False) lastname = models.CharField(max_length=50, blank=False) class PhoneNumber(BaseModel): country_code = models.CharField(max_length=VERY_SHORT_STRING_SIZE, blank=False) phone_number = models.CharField(max_length=SHORT_STRING_SIZE, blank=False, null=False) label = models.CharField(max_length=NORMAL_STRING_SIZE, blank=True, default='') related_contact = models.ForeignKey(to='ContactModel', on_delete=models.CASCADE) I want to make a CRUD api for my Contacts. I have a ModelViewSet and a ModelSerializer for that. serializer codes is as follows: class ContactSerializer(serializers.ModelSerializer): phonenumber_set = PhoneSerializer(many=True, required=False) class Meta: model = ContactModel fields = '__all__' class PhoneSerializer(serializers.ModelSerializer): class Meta: model = PhoneNumber fields = ['id', 'country_code', 'phone_number', 'label'] As it's been specified here I should override update and create methods in order to update and create PhoneNumbers of my Contact. The Problem is that if I override those functions I have to use them like this: class ContactSerializer(serializers.ModelSerializer): ... def create(self, validated_data): # some code for creating both PhoneNumber and Contact def update(self, instance, validated_data): # some code for updating both PhoneNumber and Contact and unfortunatly, 'validated_data' argument doesn't bring the 'id' of my PhoneNumber objects, beacause 'id' fields are AutoFields and AutoFields will … -
Data retrieve from database to template in Django as a popup window
I am developing a form that can retrieve all the lists of data from database to popup window in Django template. I want to select a specific record and display it in the html file that popup window is contained, and add a button to redirect to edit the values of that record. -
Django gets 'None' from POST-request
I sending info by fetch to my django server, but django gets None instead of values in the object POST-request GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; fetch(`http://127.0.0.1:8000/computerAnswer/`,{ method:'POST', body:JSON.stringify({value: 'value', deleted:[], answer:'computerAnswer'}) }).then((response) => { return response.json(); }) .then((json) => { console.log(json.msg); }).catch((error) => { console.log("now is " + error); }); Views.py @csrf_exempt def computer_answer(request): print(request.POST.get('value')) print(request.POST.get('deleted')) print(request.POST.get('answer')) data = {'msg': ''} value = 0 deleted_cities = 0 answer_of_computer = 0 if request.method == 'POST': value = request.POST.get('value') deleted_cities = request.POST.get('deleted') answer_of_computer = request.POST.get('answer') if value == '' or value is None: data['msg'] = '-1' return JsonResponse(data) data['msg'] = citiesGame.game(value, deleted_cities, answer_of_computer) return JsonResponse(data) when print is triggrerd, the None is printed. This request goes from app on React-native. The views.py works for sure if you make a request from host on which the real backend is located, but from the application it doesn't work(as in "about:blank" chrome) -
Why RelatedObjectDoesNotExist is thrown when trying to add an entery from the django admin?
In my models, I have the ImageAlbum model and Image model. In the Image model, I have a ForeignKey field to the ImageAlbum. This code is actually recommended from this article. class ImageAlbum(models.Model): def __str__(self): return str(self.pk) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=get_upload_path) default = models.BooleanField(default=False) thumbnail = models.ImageField(upload_to=get_thumbnail_path, default='default/default_thumbnail.jpg') album = models.ForeignKey(ImageAlbum, on_delete=models.CASCADE) I registered the models in the admin and the Image form looks like that: And after I hit save, the following exception occurs: -
Celery workers multiply infinitely with multiprocessing Billiard
Good day to you. I just recently started to delve into the celery and ran into a problem. I am trying to asynchronously check the proxy by running 8 threads inside one task, which is executed every 3 hours. I would like to use one worker with 8 child processes for this, or 8 workers with one process on each. But now I put a lot of workers after several iterations of the script and only one thing helps to kill all the processes of the select. How to properly configure the celery tasks or my script in this case? Logs file looks like: [2021-04-27 16:50:00,285: WARNING/ForkPoolWorker-6] Started at 2021-04-27 16:50:00.285149 [2021-04-27 16:50:00,289: WARNING/ForkPoolWorker-6] CREATE POOL 8 processes [2021-04-27 16:50:00,320: WARNING/ForkPoolWorker-6:1] START PROCESS NUMBER 0 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:2] START PROCESS NUMBER 1 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:3] START PROCESS NUMBER 2 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:4] START PROCESS NUMBER 3 [2021-04-27 16:50:00,322: WARNING/ForkPoolWorker-6:5] START PROCESS NUMBER 4 [2021-04-27 16:50:00,323: WARNING/ForkPoolWorker-6:6] START PROCESS NUMBER 5 [2021-04-27 16:50:00,324: WARNING/ForkPoolWorker-6:7] START PROCESS NUMBER 6 [2021-04-27 16:50:00,325: WARNING/ForkPoolWorker-6:8] START PROCESS NUMBER 7 [2021-04-27 16:50:00,468: WARNING/ForkPoolWorker-6:5] CON ERR: 94.154.158.234:12333, 407 [2021-04-27 16:50:00,720: WARNING/ForkPoolWorker-6:4] CON ERR: 173.254.206.36:80, 404 [2021-04-27 16:50:00,777: WARNING/ForkPoolWorker-6:1] CON ERR: 54.213.157.85:80, 404 [2021-04-27 16:50:00,794: WARNING/ForkPoolWorker-6:3] OK: 159.8.114.34:8123, … -
I am asking for help in my django rest framework project with addition features post like, unlike, user activity endpoint
What I need to achieve. *Post like, Post unlike, analytics how many likes were made from some specific day to day, API should return aggregated by day. User activity an endpoint that will show when user was login last time and when he made a last request to the server *. What I already achieve. Using two models User, Post, user login, register, and post creation. Implemented JWT token authentication My code in app 'api': models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) post_like = models.ManyToManyField(User) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Post class PostSerialization(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'url', 'content', 'title', 'date_posted', 'author'] views.py from rest_framework import viewsets, permissions from .models import Post from .serializations import PostSerialization class PostSetView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerialization permission_classes = [permissions.IsAuthenticated] urls.py from django.urls import path, include from rest_framework import routers from .views import PostSetView router = routers.DefaultRouter() router.register(r'posts/', PostSetView) urlpatterns = [ path('', include(router.urls)) ] In root directory 'network_api': settings.py """ Django settings for network_api project. Generated by 'django-admin startproject' using … -
query a manytomany realted field
I have a model like the following: GRN Model: class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): reference_no = models.CharField(max_length=500, default=0) inward_date = models.DateTimeField(blank=True, null=True) items = models.ManyToManyField(GrnItems) How can I query the GrnItems to get item_quantity which has product = 5 and connected to grn = 103? -
Why does not django send emails?
I have connected my website to database in sql server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'name', 'USER': 'user', 'PASSWORD': '', 'HOST': 'DESKTOP-\SQLEXPRESS', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } And copied the code for password reset EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'n@gmail.com' EMAIL_HOST_PASSWORD = '' Now every page is working, but I am not receiving any letters. However, when a had embeded django database everything was working(a month ago). May it be connected with the microsoft database or the problem is not in that? -
Write console log to a file in Django
I have following configuration for logging in my project. I don't have any clue where all the log is writing. I have to check authentication failure logs, But I don't know where to check. Event syslog is not updating anything. Please help me to push all console logs to a file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stream_to_console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django_auth_ldap': { 'handlers': ['stream_to_console'], 'level': 'DEBUG', 'propagate': True, }, } } -
Not able to access data of field ID with formControlName `ids` or `ID` in angular
I just started leaning Angular with Django as backend and i am facing this problem when i add formControlName="ID" or formControlName="ids" in mypage.component.html it din't send data to backend but when i change formControlName to other or anything it sends data is there any reserved keywords in angular? here is my mypage.component.html ID field code <div class="form-group row"> <label class="col-sm-3 col-form-label">ID</label> <div class="col-sm-8"> <input type="text" formControlName="material_id" class="form-control" id="Adtitle" placeholder="Round,Rectangle etc."> <small class="form-text text-muted"> Entering the ID if applicable </small> </div> </div> and this is in my mypage.component.ts this.createPostForm = new FormGroup({ material_id : new FormControl(''), }); my code is working fine when i put material_id or any other words but when i put ID or ids it din't get data from form.