Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a post call with Django where your models are many to many?
I am trying to understand how I should be structuring my post call when I want to do a many to many relationship. class School(models.Model): name = models.CharField(unique=True, max_length=30, blank=True) teachersAtSchool = models.ManyToManyField('Teacher', blank=True) class Teacher(models.Model): account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) schoolsTeachingAt = models.ManyToManyField('School', blank=True) I send in the following JSON: { "name": "school Name", "teachersAtSchool": 0 } and get the following result: { "id": 13, "name": "school Name", "teachersAtSchool": [] } I have checked there are indeed teachers in the database that I can get with my GET call. I even tried with different id's but I get the same result. Its possible this is something super simple I just don't understand. Please help me. Regards -
Django Admin Dashboard problem with user permissions
What can I do to prevent user w1 from selecting user q when creating the location? The uesr w1 has all the rights to create the models and has staff status. Is there a way that the user w1 is written directly into the field "user" without the user w1 having to do this manually? code: models.py and admin.py https://www.codepile.net/pile/QmA9awmV enter image description here -
Summernote Icons not showing using django-summernote
I am using django-summernote and its icons aren't loading. I have followed multiple suggestions on other stack posts (like this one), and tried suggestions on github, including hard-coding CDN links to summernote's CSS, and I have tried modifying the @font-face css with A) urls to local font files, and B) hard coded urls to the fonts in my static storage, none of which worked. I also tried pulling the CSS files (unminified) directly into my page in <script> tags, also with no luck. I'm using digital ocean spaces to serve static files (which follows the AWS S3 api standards, if relevant), and I can verify they're loading, as shown in the image. The directory and each asset are designated public. Furthermore, font-awesome is already used throughout my app (version 6). I've tried rolling back to previous versions of F-A, which also did not work. From other posts, it seems summernote gets F-A icons somehow, but I'm not sure how. If anyone has any insight into this issue, I'd appreciate it. Here's how it looks now, on Chrome and other browsers: Short of writing a script to replace summernote's icons with something that works, I'm not sure what to try next. -
Django - RelatedObjectDoesNotExist / User has no customer
I am creating an e-commerce website where people can choose to login or not but still the can order and checkout (even if you are an AnonymousUser or Guest user). Now, I am making a login and register form in my website. The login form works and looks good but the register form wasn't working and throwing an error that said "RelatedObjectDoesNotExist at / User has no customer." I think the reason is that when I register, it only makes a User in database but didn't register anything in the Customer table (which consists Name and Email). How can I register a Customer and User at the same time when I hit the "Submit" button? And how can I make that specific User have "Staff status" only and cannot make changes in the Admin site? Also, I want to add new fields in the Register form for Name and Email that will go directly to the Customer table. I tried to do this one but it doesn't work and throwed and error that says "django.core.exceptions.FieldError: Unknown field(s) (name) specified for User". Here's what I did: from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import … -
django filter fields + custom Q field
I am trying to use regular filter fields with multi search field. If I put just fields = [`q`] or fields = { 'model': ['icontains'], 'type' : ['icontains'], } then it works but if I try to use them together, it doesn't. How do I make this work? filter.py class CustomFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='custom_search_filter',label="Title & Tag Search") class Meta: model = CustomModel fields = { 'model': ['icontains'], 'type' : ['icontains'], ['q'] } def custom_search_filter(self, queryset, name, value): return queryset.filter( Q(title__icontains=value) | Q(tag__icontains=value) ) -
whats wrong this query in djagno
def get_available_working_hours(location_id, date, appointment_type): providers = get_availabe_providers(location_id, appointment_type.id).values_list('id', flat=True) _workinghours = WorkingHour.objects.filter( Q(week_days__contains=[date.weekday()]) | Q(date__lte=date) & Q(end_date__gte=date), location_id=location_id, provider_id__in=providers ).distinct().values( 'start_time', 'end_time', 'provider_id' ) workinghours = normalize_datetime(date, _workinghours) # print(workinghours) _blockhours = BlockHour.objects.filter( provider_id__in=providers, location_id=location_id, date=date ).values( 'start_time', 'end_time', 'provider_id' ) blockhours = normalize_datetime(date, _blockhours) -
Assign user input in charField as foreign key
I am trying to implement a registration key in the registration form which the user has to input to be able to create an account. In my users model, I have a key field which is the foreign key of the Key model. The relation looks like this class RegistrationKey(models.Model): key = models.CharField(max_length=30) class User(AbstractUser): ... key = models.ForeignKey(RegistrationKey, on_delete=models.CASCADE, null=True, blank=True) I have tried to validate the input like this in the view def registerPage(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) key_input = request.POST.get('key') ... if RegistrationKey.objects.filter(key_input=key).exists() and form.is_valid(): user = form.save(commit=False) user.key.add('key_input') ... user.save() In my form have I set the key field as a CharField as I can not display the keys for the user. This means that the user inputs a string but django needs an instance to be able to save it to the database. I don't know how to implement this. Is there any way to convert a string to an instance or is there a better way to query the the database, to check and see if the input is a valid key? -
Get related Model foreignkey (in addition to the ManyToMany) with prefetch_related(model_SET).all()
With prefetch_related, I retrieve the list of my different warehouses stock like this : Model Product [nothing special] Model Warehouse [nothing special] Model SstStock class SstStock(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) product = models.ManyToManyField(Produit) qty = models.IntegerField() last_update = models.DateTimeField(default=timezone.now) views.py class ProductListView(LoginRequiredMixin, ListView): queryset = Product.objects.prefetch_related('sststock_set').all() context_object_name = "produits" paginate_by = 10 template_name = 'products/produits.html' def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data( *args, **kwargs) context['title'] = 'Produits' return context Template {% for produit in produits %} {{ produit.sku}}<br> {% for sst in produit.sststock_set.all %} <span>{{ sst.warehouse.code }} - {{sst.qty}} - {{sst.qty}}</span> {% endfor %} {% endfor %} But when I get the information related to the warehouse eg. sst.warehouse.code in template, the number of queries explodes. (already 36 queries with a pagination of only 10 products) Is there a way to add warehouse in prefetch_related in the view ? -
How to process an uploaded file and notify the user later when the file is uploaded in django
I have a Django app that allows a user to upload file. I am processing this file on the server and it takes about 3 mins for the task to complete. I am assuming the browser won't wait that long for a response after POST request. So I want a way to respond to the post immediately after the file upload and start the heavy operation in a new thread and then 3 mins later notify the user. Is this possible in Django and how? please do guide me. Thanks -
When I save the data and upload multiple files nothing happens
I have a question, what happens is that I am making a form that accepts text and also has 2 input buttons to upload multiple images. I've been reviewing the documentation of the official django site and there are things where I get lost. For example, I already made the view as it comes in the documentation, but when I save, it does not save images or data in the database. Only one detail was missed in the view and it is that I did not understand how to do the iteration with the for. At first I put the fields of the model and the same fields I put them in the arguments where it says def post but I get a thousand errors. Can you help me to solve this problem? Thanks models.py class Carro(models.Model): placas=models.CharField(max_length=255) tipo=models.CharField(max_length=255) marca=models.CharField(max_length=255) modelo=models.CharField(max_length=255) año=models.IntegerField() vin=models.CharField(max_length=255) color=models.CharField(max_length=255) motor=models.CharField(max_length=255) agente_seguros=models.CharField(max_length=255, null=True) compañia_seguros=models.CharField(max_length=255, null=True) no_politica=models.CharField(max_length=255, null=True) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, upload_to="images/") garantia=models.ImageField(null=True, upload_to="images/") fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.año}{self.marca} {self.modelo} {self.tipo}{self.motor}{self.vin}{self.color}' \ f'{self.agente_seguros}{self.compañia_seguros}{self.no_politica}{self.cliente}' \ f'{self.fecha_registros}{self.fotosCarro}{self.garantia}' carros-form-add.html <div class="col-md-4"> <div class="mb-3"> <label>Policy No.</label> {{ form.no_politica }} </div> </div> </div> <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> … -
Django Server not starting because of RestFramework
[error message][1] Each time i include the Django Rest Framework in my installed apps in my settings.py file, I get an error while starting my server. Kindly help. I attached a screenshot of the error message and settings.py file for reference. Thank you. -
Having trouble saving django forms to sqlite
I am currently working on a program which is currently in development. Now I have never worked with Django before this and I am having some troubles. I am trying to save a few form fields to a sqlite database however I am getting errors. Here is the error that I get NameError at /recipes name 'form' is not defined Request Method: POST Request URL: http://localhost:8000/recipes Django Version: 4.0.2 Exception Type: NameError Exception Value: name 'form' is not defined Exception Location: C:\Users\Admin\Desktop\praktika\brew\brewery\views.py, line 24, in recipes Python Executable: C:\Program Files\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\\Users\\Admin\\Desktop\\praktika\\brew', 'C:\\Program Files\\Python310\\python310.zip', 'C:\\Program Files\\Python310\\DLLs', 'C:\\Program Files\\Python310\\lib', 'C:\\Program Files\\Python310', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python310\\site-packages', 'C:\\Program Files\\Python310\\lib\\site-packages', '/home/ponasniekas/wwwpi/brew', '/home/ponasniekas/wwwpi/brew/brew', '/home/ponasniekas/wwwpi/brew/brew/brewery', '/home/ponasniekas/.local/lib/python3.8/site-packages'] Here is my views file: from django.http import HttpResponse import json from django.http import StreamingHttpResponse from django.shortcuts import render from django.core.serializers import serialize from django.http import JsonResponse from django.template import RequestContext from .models import StockYeast, queryset_to_indexlist,queryset_to_array, Brew, Fermentable, Miscs, RecipeYeast, Recipes, Yeast,StockFermentables from .models import Hop,StockHop,StockMiscs from .forms import RecipeForm, RecipeFermentableForm, RecipeHopForm, RecipeMiscForm,RecipeWaterForm, RecipeYeastForm,RecipeMashForm, StockMiscForm from .forms import StockFermentableForm,StockHopForm,StockYeastForm, StockMiscForm from django.forms import formset_factory def index(request): return render(request, 'index.html') def recipes(request): if request.method == 'POST': recipes = RecipeForm(request.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Recipes(name=n) t.save() else: recipes … -
error: legacy-install-failure - When I try to install mysqlclient package for django
I get this error everytime i try to install mysqlclient for my django app. I need to transfer my db to a new one on mysql db. I try to install it by doing this command: python3 -m pip install mysqlclient I am using a macOS 11. Thank you. Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [43 lines of output] mysql_config --version ['8.0.28'] mysql_config --libs ['-L/usr/local/Cellar/mysql/8.0.28_1/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/usr/local/Cellar/mysql/8.0.28_1/include/mysql'] ext_options: library_dirs: ['/usr/local/Cellar/mysql/8.0.28_1/lib'] libraries: ['mysqlclient', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/local/Cellar/mysql/8.0.28_1/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,0,'final',0)"), ('version', '2.1.0')] running bdist_wheel running build running build_py creating build creating build/lib.macosx-11-x86_64-3.9 creating build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/exceptions.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb creating build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-11-x86_64-3.9/MySQLdb/constants running build_ext building 'MySQLdb.mysql' extension creating build/temp.macosx-11-x86_64-3.9 … -
Domain-maked Django app not working as expected
I am running a Django app alongside a basic html website using Apache2, by attaching the django app through my.site/myapp When I access it like my.site/myapp/some-location it works just fine, but if I access it through my domain with masking enabled such as domain.site/some-location it returns a 404. The domain points to my.site/myapp with masking enabled as mentioned. Site configuration: <VirtualHost *:80> Alias /static /var/www/myapp/static <Directory /var/www/myapp/static> Require all granted </Directory> <Directory /var/www/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myapp python-path=/var/www/myapp python-home=/var/www/djangoenv WSGIProcessGroup myapp WSGIScriptAlias /myapp /var/www/myapp/myapp/wsgi.py </VirtualHost> A specific example that doesn't work: domain.site/admin, which however works well on my.site/myapp/admin. -
Way to query internal data structure for running python program [closed]
Hi I a newbie to software development, I wanted to build a python application that will open TCP connection and listen to logs and do some action based on them. I am planning to use dictionary to store my datas. Just wondering is there a way or CLI package that I can use to query the internal data structure while program is running. I googled and found flask as an option but from what I understand its mainly for web-development. Does it make sense to use Flask for these kind of my application ? Am I going in right direction or is there any other resources that will point me in right direction ? -
New bid is not updating to show the Users input (amount) Django
Trying to create an e-bay like platform where users can select an item and bid on it, the bid amount should update to the latest valid bid inputted by a user. Currently, the amount is not updating to show that a user has made bid, it shows me the pop up message of messages.success(request, 'Successfully added your bid') Could you please give me an insight of what is causing this? MODELS.PY class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) image_url = models.URLField(verbose_name="URL", max_length=255, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, max_length=12, null=True, blank=True, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"(self.title)" def no_of_bids(self): return self.bidding.all().count() def current_price(self): if self.no_of_bids() > 0: return self.bidding.aggregate(Max('new_bid'))['new_bid__max'] else: return self.current_bid def current_winner(self): if self.no_of_bids() > 0: return self.bidding.get(new_bid=self.current_price()).user else: return None class Meta: ordering = ['-created_at'] class Bids(models.Model): auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name='bidding', null=True) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='bidding') new_bid = models.DecimalField(max_digits=8, decimal_places=2) done_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.new_bid) class Meta: ordering = ['auction', '-new_bid'] VIEWS.PY @login_required def make_bid(request, listing_id): if request.method == 'POST': auction = Auction.objects.get(pk=listing_id) bid_form = BidForm(request.POST) if bid_form.is_valid(): bid_form.instance.user = request.user bid_form.instance.item = auction if bid_form.instance.new_bid > auction.current_price(): bid_form.save() … -
How to assert that a class has a class exclusive property in Django/Python?
I have two models in Django, one that is the base and the other that is inherited. The base model has a database field (which in Python is an attribute of the class) and the inherited model has a property that is exclusive to the Class (not of every instance created). Both can yield different things. from django.db import models from django.utils.decorators import classproperty class Parent(models.Model): somefield = models.TextField() class Child(Parent): @classproperty def somefield(cls): return 'something' How can I create a test to ensure that all the child models created from the parent model have that class exclusive property? Because if I use hasattr() it will consider the field and the property. Something like this assertTrue(hasattr(Child, 'somefield')) assertFalse(hasattr(Parent, 'somefield')) -
UpdateView is not removing image when updating form - Django
I have a form that the user can upload the pictures into the post, this is working fine, but the problem is when the user wants to remove that current picture that the post has. It can be updated to another picture, but it can't be removed from the post to be "Blank". Models.py class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): form_class = PostEditForm model = Post def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False forms.py class PostEditForm(forms.ModelForm): thumb = forms.ImageField(required=False, widget=forms.FileInput) class Meta: fields = ['title', 'content', 'thumb', 'date_start', 'start_time', 'date_end', 'end_time', ] model = Post -
Django Query - How can do Prefetch filter with values based on root query?
For better performance, i use prefetch selected to get all in one single query like this profile = Profile.objects.only('id','series_following').prefetch_related( Prefetch('books_reading', queryset=Book.objects.only('id').filter( series_id=`series_following_id`), to_attr='books')).get(user=request.user_id) I want to get all books are reading with series_following, but i dont know how to put it to filter. Here are my models: class Profile(models.Model): user = models.OneToOneField(User) series_following = models.ForeignKey('Series') books_reading = models.ManyToManyField('Book', related_name="readers_reading_book", null=True, blank=True) ... class Series(models.Model): name = models.CharField() ... class Book(models.Model): name = models.CharField() series = models.ForeignKey(Series) ... -
Django Can't get ListView to reorder based on date
I am attempting so change the display order of a ListView to show the most recently added item. I have tried several methods in the view but so far none has had an effect on the output. The page still displays the oldest entry first. Here is an example of a view I have tried: class CompanyAnnouncementList(ListView): model = CompanyAnnouncement template_name = 'company_accounts/announcements.html' ordering = ['-date'] The model: from django.db import models from accounts.models import CustomUser from tinymce import models as tinymce_models class CompanyAnnouncement(models.Model): title = models.CharField(max_length= 200) author = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.title The template: {% extends 'base.html' %} {% block content %} <div class="section-container container"> {% for post in object_list %} <div class ="announcements-entry"> <h2><a href=" ">{{ post.title }}</a></h2> <h3>made on {{ post.date }}</h3> <p>{{ post.body | safe }}</p> </div> {% endfor %} </div> {% endblock content %} I know there are ways to change the order at the model but I would prefer to use the view. Any ideas about how to get this to work? -
How to override update method with nested serializer?
How can i update people field? class VisitsSerializer(serializers.Serializer): value = serializers.CharField(max_length=200) people = TrendingCardsPeopleListV3Serializer(many=True, read_only=True) def update(self, instance, validated_data): instance.value = validated_data.get('value', instance.value) # TODO: update people instance.save() return instance -
How to limit the input in DateTime picker?
I am making a django app which is going to collect data from a form. In the form I'm gonna put some normal fields and a DateTime field, but I wanna limit that DateTime field so the user can only select: For the Date: from today to lets say 1 year ahead For the Time: from the current local time(so if the date is today, they won't be able to pick a time before the current local time) afterwards every day from 10:00 until 21:00 Is there a way to do that? Thank You! -
how to check if the object is already created in Django rest framework serializer's to_present function
I need to check if the object is already created before adding some data to be viewed in the serializer's response. my code class AppUserSerializer(serializers.ModelSerializer): ''' Serializing App User model ''' main_user = MainUserSerializer(read_only=True) class Meta: ''' Defining main data for AppUserSerializer ''' model = AppUser # fields = "__all__" fields = [ "first_name", "last_name", "mobile", "email", "birthdate", "password", "confirm_password", "image", "main_user", "generated_code", "user_langauge", "dark_mode", ] def to_representation(self, instance): ''' Adds more data to be serialized back with AppUserSerializer ''' data = super().to_representation(instance) if AppUser.objects.filter().exists(): #need to check if object already there here, what to add inside filter() !! if instance.playerprofile_set.all().count() > 0: player_profile = instance.playerprofile_set.all()[0] data['player_profile'] = PlayerProfileSerializer( player_profile).data for item in Team.objects.all(): if player_profile in item.players.all(): data['team'] = TeamSerializer(item).data if item.cap.id == player_profile.id: data['team'] = TeamSerializer(item).data return data -
how can I get month from date in django models
I want to make a query and return only the month of the year of the date field from my models then compare the return result to the current month of the year. current_date = datetime.date.today() _history = PayrollModel.objects.filter(employee_id_id=employee_id) if(_history == None or _history.count() == 0): return True if(_history != None and _history.count() != 0): # entity = _history.get(month_year=current_date) for history in _history: print(history.employee_id_id) if(history.month_year__month != current_date.month and history.month_year.year == current_date.year): return True else: return False -
Django not recognised inside Container in Docker
I have Django on my computer and it works perfectly fine. However, when I am in a Docker container, it seems like Django doesn't work anymore (for exemple if I run import Django in the Python shell it won't recognise Django). Does anyone have an idea on how to use Django in Docker?