Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get an Error 404 in my Django App in app engine
I have deployed successfully my Django app in App Engine (standard environment) but I get this message: Not Found The requested resource was not found on this server. In the dashboard there are no Application and server errors but there are two clients errors whose URI are: /favicon.ico and /myapp/ In the Logs Explorer I can find a 404 error before the app starts working and it ends with a 301. -
'GenericApiView' object has no attribute 'update' in my views.py file
The .update function is not suppporting to this genericApiView in my view.py file it gives me an error message 'GenericApiView' object has no attribute 'update' . class GenericApiView(generics.GenericAPIView,mixins.ListModelMixin, mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin): serializer_class=ArticleSerializer queryset=Article.objects.all() lookup_field='id' authentication_classes=[SessionAuthentication,BaseAuthentication] permission_classes=[IsAuthenticated] def get(self,request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self,request,id): return self.create(request,id) # Error in this function def put(self,request,id): return self.update(request,id) def delete(self,request,id=None): return self.destroy(request,id) -
How to define optional query parameters in Django?
here i got one endpoint to receive multiple query parameters namely first_name, last_name. location and i need the endpoint to be able to handle following scenarios all the 3 param's 1 param 2 param's And i found this but still i got 404 when provide one query parameter, only works when all the parameters are given. urls.py re_path(r'^project_config/(?P<product>\w+|)/(?P<project_id>\w+|)/(?P<project_name>\w+|)/$', views.results, name='config') And view def results(request, product, project_id, project_name): response = "You're looking at the results of question %s." print(product) print(project_name) return HttpResponse(response % project_id) How can allow url to accept optional query parameters ? -
What is the optimal batch size in django
I'm wondering that the optimal batch size while making bulk create in Django. I don't know the exact number of data. It might be millions or thousands. How can I decide the optimal batch size? -
Django get field from m2m and foreign key
I am adding functionality to my django application to add models(Lot) linked to another(Job) with an M2M field. The problem: I am using Django autocomplete light to add this model(Lot) in the form and i want this field to also be filtered by the input and another autocomplete field(Contract), this field is an object called contract that is in the reverse of the M2M field: Relations: {Lot}--reverse on the M2M--{Job}--Foreign Key--{Contract} I am trying to filter lot in the autocomplete to only those where the contract key on the order matches a field in the form, i have looked through documentation and im unsure if there is anyway to do this, below is my latest attempt along with relevant code. models.py(only fields for the relationship) class Contract(Parent_model): contract_id = models.IntegerField(null=False, default=0000) class Job(Job_parent): contract = models.ForeignKey(Contract, on_delete=models.CASCADE) class Lot(Job_parent): CO = models.ManyToManyField(Job, related_name='Lot') autocomplete class based view(views.py) class lot_auto_complete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Lot.objects.all() contract_in = self.forwarded.get('contract', None) if contract: query_set = qs.filter(CO_set.first().contract=contract_in) if self.q: query_set = qs.filter(lot_number__icontains=self.q) return query_set -
installing GEOS on ubuntu
hi i am trying to install GEOS on ubuntu with wget https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2 but it gives --2021-03-10 10:48:18-- https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2 Resolving download.osgeo.org (download.osgeo.org)... 140.211.15.30 Connecting to download.osgeo.org (download.osgeo.org)|140.211.15.30|:443... connected. HTTP request sent, awaiting response... 404 Not Found 2021-03-10 10:48:19 ERROR 404: Not Found. judging from the HTTP reponse i dont think it actually downloaded so is there another way to download GEOS? -
How to convert factory boy instance as json
I have a model that relates to some others and I want to make an instance of model factory with factory boy package and send it as json to rest API in django rest framework. When I use: factory.build(dict, FACTORY_CLASS=UserFactory) it returns: {'first_name': "Agent 001", 'username': 'john_doe', 'language': <Language: Catalan>} where language is another model factory but I need it as json to post or patch test. How would I get something like this? {'first_name': "Agent 001", 'username': 'john_doe', 'language': [{'name': 'English'}, {'name': 'French'}]} -
Filefield is not displayed on foreign key popup fiel in django admin
File field from this model is not displayed on the popup form on a foreign key field in django admin. My model is: class NationalId(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) not_registered_user = models.OneToOneField(NotRegisteredUser, on_delete=models.CASCADE, null=True) national_id = models.CharField(max_length=9, blank=False) document_type = models.CharField(max_length=10, blank=False) is_verified = models.BooleanField(blank=False, default=False) date_verified = models.DateField(null=True, blank=True) date_expired = models.DateField(null=True, blank=True) image_file = models.FileField(null=True, blank=True, verbose_name=_(u'scanned image')) def __str__(self): return self.national_id And the popup shown is -
How to Embed Power BI dashboard into Web portal using Django?
Is it possible to embed dashboards/reports from Power BI and embed it into Web portal using Django framework? I just tried using 'Flask' and it was working fine. But I really wanted to do the same using Django. I'm new to this field and really confused about the code and all. -
Unresolved attribute reference 'objects' for class 'GeneralSettings'
Django 3.1.7 Python 3.8.5 class Branch(models.Model): def get_external_dir(self) -> str: """ Get the path to where all external files for this branch must be put. """ general_settings = generals_models.GeneralSettings.objects.get(key="general_settings") class GeneralSettings(models.Model): key = models.CharField(max_length=16, null=False, default="general_settings") ... Problem Pycharm shows me a warning: Unresolved attribute reference 'objects' for class 'GeneralSettings' I'm struggling for a stylish code. I don't want this warning as it irritates me. Could you tell me: Why is such a warning appear and how to cope with it? Should I just ignore it like this? -
AttributeError: 'ApplicantEducation' object has no attribute '_state'
This is how i constructed my model: Model.py class ApplicantEducation(models.Model): applicant_info = models.ForeignKey(ProfileInfo, on_delete=models.CASCADE) degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) marks_percentage = models.FloatField(max_length=5, default=0.0) institute_name = models.CharField(max_length=100) affilation_with = models.CharField(max_length= 50) date_completion = models.DateField(auto_now_add=False, blank=True) def __str__(self): return str(self.applicant_info) def __init__(self, applicant_info = None, degree_details = None): applicant_info = ProfileInfo.info_id degree_details = DegreeDetails.id Anybody, who can figure this out?? -
Making complex query with django models
I created a view in my database model with 6 joins and 10 columns, and at the moment it shows around 86.000 rows. I try to query all the rows by objects.all() and then filter according to user interaction (form data sent by POST and then choosing appropriate .filter(*args) querying) After that I tried to get the length of the queryset by using count() since this method doesnt evaluate the query. But since views don't have indexes on the columns, the count() method takes to long. I searched for the solution of materializing the view but that isn't possible in mysql. Then I searched for a solution that might be able to replace the initial .all() by just using the 6 joins and filtering arguments in django rather than creating a view, so the indexes would still be available. But I couldn't find a solution to that problem. Or maybe combining every row from the view with another table so I can use the index of the other table for faster querying?: SELECT * FROM View LEFT JOIN Table ON (View.id = Table.id) I appreciate every answer -
py.test completely ignores configured loggers. How to fix it?
I have a weird py.test behavior. If a logger is configured in settings.LOGGING then py.test won't show those logger messages captures on a failed test, won't show when running with -s nor having log_cli=true in conf file. Here is how my logging configuration looks like: LOGGING = { "version": 1, "handlers": { "stream": { "class": "logging.StreamHandler", } }, "loggers": { "app": {"handlers": ["stream"], "level": "WARNING", "propagate": False,}, }, } If I comment out the "app": line then logs appear. -
Is there anyone who can assist me to integrate domain registar in my dajngo project
I would like to add a domain registrar to my project like whmcs. I am able to build a project which works like WHMCS billing software but unable to add the domain registrar. I want when the user searches the domain it should give the result that whether it is available or not. if available it should reserve for that user. it is like whmcs domain registar -
display menu of each restaurant for different hotel in web app django?
if we have a web page that displays names of multiple restaurant .Then how do we display menu of each restaurant in Django(backend). I can't figure it out please help. -
How to create user friendly cronitor expression generator using Javascript?
User need to easily create a cronitor expression from UI. Example for the cron expression generator : https://www.freeformatter.com/cron-expression-generator-quartz.html -
How do I access user in Django Async view?
I'm trying to access user but getting an error when the view is async. Code: from django.http import JsonResponse async def archive(request): user = request.user return JsonResponse({'msg': 'success'}) error message: django.myproject.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. What I tried: from django.http import JsonResponse from asgiref.sync import sync_to_async async def archive(request): # user = sync_to_async(request.user) # user = sync_to_async(request.user)() # user = await sync_to_async(request.user) user = await sync_to_async(request.user)() return JsonResponse({'msg': 'success'}) Still getting the same error. I want to access the user to check he/she has permission to archive a file. -
How to restrict admin link/button in Django?
This is what I expect: if a user has position "1" (Admin) the nav menu in home.html must show "Admin" link to an admin page. If a user has position "2" (User) it won't show the link. But when I run server this code generate as many Admin links as there are registered users. I want only one link for currently logged-in user to be shown. How can I do that? I know that there's something wrong with "for user in position", but how to fix it for currently logged-in user? models.py class Profile(models.Model): positions = ( ('1', 'Admin'), ('2', 'User'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') position = models.CharField(max_length=50, default='Position', choices=positions) views.py def home(request): user_position = Profile.objects.all() return render(request, 'home.html', { 'position': user_position, }) home.html {% for user in position %} {% if user.position == '1' %} <a class="nav-link" aria-current="page" href="/admin">Admin</a> {% endif %} {% endfor %} -
Django: Dates don't change correctly when changing Timezone
When I change the timezone in my django project the dates do change correctly. When the timezone is set to 'UTC' the dates are displayed like this: This is correct. As you can see these are also the dates which are specified in my database: But when I change the settings to: LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True The dates inside my application now change to the image below. Only the first two dates are displayed in the correct way, even though nothing has changed except for the timezone. Does anyone know why this happens, and how I can solve this? -
drf: Add a non-model field in Serializer
If receiver==me then the name will be sender name, else name will be receiver name. I can do it in views.py, but is it possible in serializers.py? here is my code: models.py: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') body = models.TextField(max_length=1000) date = models.DateTimeField(auto_now_add=True) seen = models.BooleanField(default=False) class Meta: ordering = ('date',) serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') class GetMessageSerializer(serializers.ModelSerializer): sender = SimpleUserSerializer() receiver = SimpleUserSerializer() #name = ....???? class Meta: model = Message fields = ('sender','receiver','body','date','seen') -
How to fix Field 'id' expected a number but got 'description' in django admin panel
In django admin I am trying to pre populate values from model MetaTag to model ModelSeoMetadatum using model forms and django-autocomplete-light library dal library. my models: class MetaTag(models.Model): name = models.CharField(max_length=50, null=True, blank=True) property = models.CharField(max_length=50, null=True, blank=True) def __str__(self): if self.name !=None and self.property == None: return str(self.name) elif self.name == None and self.property != None: return str(self.property) else: 'name : ' + str(self.name) + ' , property : ' + str(self.property) class SeoMetadatum(models.Model): class Meta: verbose_name_plural = "SEO Metadata" path = models.CharField(max_length=100, null=True, blank=True) name = models.CharField(max_length=50, null=True, blank=True) property = models.CharField(max_length=50, null=True, blank=True) content = models.CharField(max_length=200, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.UUIDField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') class ModelSeoMetadatum(SeoMetadatum): class Meta: verbose_name_plural = "Model Metadata" proxy = True my form class ModelSeoMetadatumForm(forms.ModelForm): name = ModelChoiceField(required=False,queryset=MetaTag.objects.exclude(name__isnull=True).values_list('name' , flat = True).distinct(),widget=autocomplete.ModelSelect2(url='seo:name-autocomplete')) class Meta: model = ModelSeoMetadatum fields = ('content_type', 'object_id', 'name', 'content', 'property') my admin @admin.register(ModelSeoMetadatum) class ModelSeoMetadatumAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'content', 'property', 'content_object') fields = ('content_type', 'object_id', 'name', 'content', 'property') form = ModelSeoMetadatumForm my url urlpatterns = [ path('name-autocomplete/', NameAutocomplete.as_view(),name='name-autocomplete'), ] my view class NameAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return MetaTag.objects.none() qs = MetaTag.objects.all() if self.q: qs = qs.filter(Q(name__istartswith=self.q) | Q(name__icontains=self.q)) … -
Why does Django causes my materialize link to appear blue when I hover over them?
as you can see when I hover over the dropdown box the link becomes blue, what could be the cause of this?? I am using Django with this maybe that could be causing problems I tried it in a document with only the materialize header and it works just fine: Here is the code: <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <!-- Dropdown Structure --> <ul id="dropdown1" class="dropdown-content"> <li><a href="#!">one</a></li> <li><a href="#!">two</a></li> <li class="divider"></li> <li><a href="#!">three</a></li> </ul> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo">Logo</a> <ul class="right hide-on-med-and-down"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <!-- Dropdown Trigger --> <li><a href="#" class="dropdown-trigger" data-target="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script> M.AutoInit() $(".dropdown-trigger").dropdown(); </script> </body> When I combine it with my Django main page it messes up, what should I remove/add? Main page header: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Stock Trading Website</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{%static "/css/main.css"%}"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> … -
Approve application method in Django
Dear Django User how can I put an approve function in my project? My code is below: Model: class ApproveJob(models.Model): PENDING = 'pending' ACTIVE = 'approved' CHOICES_STATUS = ( (PENDING, 'Pending'), (ACTIVE, 'Approved'), ) approve = models.ForeignKey(Application, related_name='approved_job', on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PENDING) def __str__(self): return str(self.approve) -
How to update several objects with one form in Django?
I create a customer model and a function for assign a customer to a user. Assign function is update user field in Customer model. This Customer model has a country field. I want to assign the customers in the same country to a user with one form. For doing that I have listing all countries and a form for assign operation? How can I do that? models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) ... user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True) And this is my form for assigning customers one by one: views.py def customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) # Assign form = AssignForm(request.POST or None) if request.POST: customer_id = request.POST.get('customer_id', None) customer = Customer.objects.get(id=customer_id) user = UserProfile.objects.get(id=request.POST.get('user', None)) customer.user = user customer.save() form.save() return redirect('user:customer_list') context = { 'customer_list': customer_list, 'form': form } return render(request, 'customer_list.html', context) customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Customer Name</th> <th>Country</th> ... <th>Operations</th> </tr> </thead> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.customer_name}}</td> <td>{{customer.country}}</td> ... <td> ... {% if customer.user == null %} <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">&nbsp;Assign&nbsp;&nbsp;&nbsp;&nbsp;</button> {% else %} <button type="button" class="btn btn-success" data-toggle="collapse" … -
Get the user context in all views django?
Im using a template syntax to set the permissions for the topbar of the application like so Top bar permision {% if user.is_authenticated %} # Top bar html code {% endif %} but the problem is that when a user i authenticated they can accress the profile picture and name of another user if they have the correct url:uuid link. I managed to get this fixed by putting this syntax in the template {% if object == request.user %} {% if object.pk %} {% endif %} {% endif %} This fixed the issue on the pages where the request.user can be accressed from the profile view. How can i accress the request.user in all the views at once?