Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App not loading error while executing commands
` dam 2022-11-15 18:05:49,686 - adam - INFO - Welcome to ADAM, Finquest's Application for Data Annotation Management! Traceback (most recent call last): File "/home/finq/miniconda3/envs/adam/bin/adam", line 33, in <module> sys.exit(load_entry_point('adam', 'console_scripts', 'adam')()) File "/home/finq/miniconda3/envs/adam/bin/adam", line 25, in importlib_load_entry_point return next(matches).load() File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/metadata/__init__.py", line 171, in load module = import_module(match.group('module')) File "/home/finq/miniconda3/envs/adam/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/finq/review/106_review/adam/adam/__main__.py", line 6, in <module> from adam.common.common import check_database_exists File "/home/finq/review/106_review/adam/adam/common/common.py", line 9, in <module> from adam.graphical_user_interface.db_graphical_user_interface.models import UserLogin File "/home/finq/review/106_review/adam/adam/graphical_user_interface/db_graphical_user_interface/models.py", line 5, in <module> class UserLogin(models.Model): File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/finq/miniconda3/envs/adam/lib/python3.10/site-packages/django/apps/registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. ` I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks I tried everything from path ,run migrtaions ,migrate but nothing helped . Please help to reoslve this . Thanks … -
Django | Only show foreign keys not already assigned in django form
Im making a booking system in django where the user picks a date and then is able to see what times are available on that date. Models.py class Slot(models.Model): title = models.CharField(max_length=50) def __str__(self): return f'There is a slot at {self.title}' class Booking(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slot = models.ForeignKey(Slot, on_delete=models.CASCADE, null=True, blank=True, related_name='all_times') booking_date = models.CharField(max_length=15, default='foo') def __str__(self): return f'{self.user} has booked a session at {self.slot.title} on {self.booking_date}' Where the Slot model is they times that are available to pick(e.g. 9-10, 1-2 etc.) Views.py def DateView(request): form = DateForm(request.POST or None) if form.is_valid(): request.session["dateSelected"] = str( form.cleaned_data["booking_date"]) return redirect('../create/') context = { 'form': form } return render(request, "bookingapp/date_form.html", context) def BookingView(request): instance = Booking(booking_date=request.session.get('dateSelected')) form = BookingForm(request.POST or None, instance=instance) if form.is_valid(): form.save() form = BookingForm context = { 'form': form } return render(request, "bookingapp/book_form.html", context) Forms.py class DateInput(forms.DateInput): input_type = 'date' class DateForm(forms.ModelForm): class Meta: model = Booking fields = [ 'booking_date', ] widgets = {'booking_date': DateInput()} class BookingForm(forms.ModelForm): class Meta: model = Booking fields = [ 'user', 'slot', 'booking_date', ] widgets = {'booking_date': forms.HiddenInput()} The first form lets the user select a date, which then brings them to the second form where they can choose what … -
In Linux, how to run Django custom management using crontab?
I have generated a bash script that activates virtaulenv and runs my custom management command in Django. I want to run the bash script every day at midnight. Bash Script : cd ~ cd path_to_virtualenv/ source virtualenv_name/bin/activate cd path_to_project/ python manage.py custom_command deactivate When I run this script using . or source it runs perfectly. I have configured crontab to run this bash script (For testing, I have set execution time per minute). But I am not getting desired output. crontab -e */1 * * * * source /path_to_bash_script/bash_script_filename -
Is django's SCRIPT_NAME applied to STATIC_URL?
I'm serving django with gunicorn and nginx. And I've observed a strange behavior, which looks like django is prefixing MEDIA_URL with SCRIPT_NAME but it is not prefixing the STATIC_URL. Am I handling it properly? My static's configuration: STATIC_URL = "backend/static/" # this looks odd but works STATIC_ROOT = "/var/www/static" STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = "media/" # this looks fine MEDIA_ROOT = "/var/www/media" gunicorn configuration: [Service] User=www-data Group=www-data Environment="DJANGO_SETTINGS_MODULE=backend.settings.production" WorkingDirectory=/var/www/backend ExecStart=/var/www/backend/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ backend.wsgi:application nginx configuration: location ^~ /backend { proxy_set_header SCRIPT_NAME /backend; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; location ^~ /backend/static { alias /var/www/static/; } location ^~ /backend/media { alias /var/www/media/; } } -
Django 'DetailView' object has no attribute '_meta'
This has floored me. I'm building a model with Django & REST API, and I'm having trouble rendering the DetailView for individual cars to the browser. The ListView works fine, but I'll include the code too since they are interlinked. In particular, I can't get the get_object() function to work properly. The first approach I tried used this approach: views.py class CarDetailView(generics.RetrieveUpdateDestroyAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id @action(detail=True, renderer_classes=[TemplateHTMLRenderer]) def get(self, request, *args, **kwargs): car = self.get_object() return Response({ 'car': car, }) While the page rendered properly with no errors, none of the template tags worked. Only {{ car.model }}, which returned None. So I changed the code to use a self.get_object() class CarDetailView(generics.GenericAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'car-detail.html' queryset = Car.objects.all() lookup_field = Car.id def get(self, request, id): serializer_class = CarSerializer car = self.get_object() id = Car.id return Response({ 'car': car, }) but that raises the Error: "AttributeError at /rentals/car/43c9b98d-9f2d-473f-9c34-7b2e25630278 'CarDetailView' object has no attribute '_meta'" Can you help with this? I've looked through most of the previous questions here (that's where I learned to pass the self into the get function etc...) but I'm still stuck. Here's the code: views.py … -
how to processing and loading data after rendering page in django
I have a dashboard page with some charts(image_link) For earning charts data, i'm using some queries but this queries are very heavy and take long time(for example 37 seconds!). Is exist a way for rendering page(with showing loading animation on charts) and after that start taking data process? -
Regarding BERT Arch during model deployment
I am begginer in NLP Transformers. I am facing this issue while deploying model using Django framework.Locally model is working fine but not when deployed. Here I am importing BERT model which was trained and saved using pytorch same procedure i follow to load the model but before I am defining the architecture which was defined during model training. But facing the issue after deploying the model. AttributeError: Can't get attribute 'BERT_Arch' on <module 'main' from '/home/ubuntu/kc_env/bin/gunicorn'> I tried couple of things: Like defining the BERT Architecture before model loading: ####Utils.py from django.apps import AppConfig # import torch import torch.nn as nn class BERT_Arch(nn.Module): def __init__(self): super(BERT_Arch, self).__init__() # dropout layer self.dropout = nn.Dropout(0.2) # relu activation function self.relu = nn.ReLU() # dense layer self.fc1 = nn.Linear(768,512) self.fc2 = nn.Linear(512,256) self.fc3 = nn.Linear(256,3) #softmax activation function self.softmax = nn.LogSoftmax(dim=1) #define the forward pass def forward(self, sent_id, mask): cls_hs = self.bert(sent_id, attention_mask=mask)[0][:,0] x = self.fc1(cls_hs) x = self.relu(x) x = self.dropout(x) x = self.fc2(x) x = self.relu(x) x = self.dropout(x) # output layer x = self.fc3(x) # apply softmax activation x = self.softmax(x) return x ###main.py from .utils import BERT_Arch model=BERT_Arch() def func(): model=torch.load('Path to load model.pt') -
How to Merge dictionaries in python from a for loop
I would like to merge two dictionaries this way below: dict1={ 'kl:'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ] } dict2={ 'kl':'mlk', 'schemas': [ { 'date':'14-12-2022', 'name':'maka' } ], } then I create a variable that will group the two dictionaries in this way all_dict={ 'kl':'ngt', 'schemas': [ { 'date':'14-12-2022', 'name':'kolo' } ], 'kl':'mlk', 'schemas': [ { 'date':'23-10-2022', 'name':'maka' } ] ...... } How to get this result. I'm stuck right now please help me if possible -
Mezzanine 6.0 shows unclear page history
I've been upgrading my application from python-2.7/django1.8/mezzanine4.2 to python3.8/django3.2/mezzanine6.0. Now I've met problem in page history; it user to show pretty page history in the original environment, but in the new environment it shows like in the attachment. I've repeated the problem in a small sample mezzanine project in git hub https://github.com/miettinj/mezzanine/tree/main/mezzanine_app, please let me know how to fix! -
Selenium doesn't show up my data after I submitted a form
The following test was written as a starting point for learning Selenium, the final test was added to ensure that the player's name appeared on the screen. While everything works great manually, the data I enter in Selenium doesn't show up on the screen. test.py from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys class PlayerFormTest(LiveServerTestCase): def testform(self): selenium = webdriver.Firefox() # choose the URL to visit selenium.get('http://127.0.0.1:8000/') # find the elements needed to submit form player_name = selenium.find_element('id', 'id_name') player_height = selenium.find_element('id', 'id_height') player_team = selenium.find_element('id', 'id_team') player_ppg = selenium.find_element('id', 'id_ppg') submit = selenium.find_element('id', 'submit_button') # populate the form with the data player_name.send_keys('Russel Westbrook') player_height.send_keys('6 feet 3 inches') player_team.send_keys('Los Angeles Lakers') player_ppg.send_keys('27.3') # submit form submit.send_keys(Keys.RETURN) # check if the player's name appears on the screen assert 'Russel Westbrook' in selenium.page_source Error: Traceback (most recent call last): File "/home/.../dj_selenium/main/tests.py", line 31, in testform assert 'Russel Westbrook' in selenium.page_source AssertionError Your help is much appreciated! -
what's the difference between Modelobject.id and Modelobject_id in django?
want to know the difference between Modelobject.id and Modelobject_id in Python django. Tried both and they both work the same. -
An issue while doing django orm
So here is my issue, instance.field_name or instance.save() not working on else condition. Below code: coupon = Coupon.objects.get(id=id) coupon_used = CouponUsedUser.objects.get(coupon=coupon, user=request.user, is_used=True) discount = coupon_used.coupon if coupon_used: coupon_price = total else: deduction = discount.discount_amount(total) coupon_price = total - deduction grand_total = coupon_price + delivery coupon_used.is_used = ---> #This won't work coupon_used.save() ---> #This won't work But if add those conditions inside if conditon it works. coupon = Coupon.objects.get(id=id) coupon_used = CouponUsedUser.objects.get(coupon=coupon, user=request.user, is_used=True) discount = coupon_used.coupon if coupon_used: coupon_price = total coupon_used.is_used = ---> #This works coupon_used.save() ---> #This works else: deduction = discount.discount_amount(total) coupon_price = total - deduction grand_total = coupon_price + delivery I exactly don't know why is this happening. Please explain it. -
Which version of Django rest framework for Django 2.1.5?
I am working with an old django version, and I can't identify which version of django rest framework I would need for a Django 2.1.5 I can't find this information in the official django-rest-framework documentation Thanks -
Form Validation passed but Model validation Failed and still the error is showing at form. Can anyone explain?
I have a model Books with one field 'name' and i have set max_length to 10. class Books(models.Model): name = models.CharField(max_length=10) However, in the modelform BookForm i have defined the max_length to 20. class BookForm(forms.ModelForm): name = forms.CharField(max_length=20) class Meta: fields = ['name'] model = Books Now while submitting the form with more than 10 length it gives me error saying that the field can at most 10 characters. def book(request): if request.method == 'POST': fm = BookForm(data=request.POST) print(fm.is_valid()) print(fm) if fm.is_valid(): fm.save() return render(request, 'enroll/books.html', {'form':fm}) fm = BookForm() return render(request, 'enroll/books.html', {'form':fm}) enter image description here Can anyone explain why this is happening and any specific article or link where i can read how the model form and models work with each other in terms of validation. -
Django how to make a basemodel admin general
Here I created a baseadmin model to use in all of my admin models: class BaseAdmin(admin.ModelAdmin): base_readonly_fields = ('created', 'updated','removed') def get_readonly_fields(self, request, obj=None): if self.readonly_fields: return tuple(self.readonly_fields) + self.base_readonly_fields else: return self.base_readonly_fields @admin.register(models.Example) class Example(BaseAdmin): list_display = ['id', 'name', 'sf_id', ] The problem with BaseAdmin is sometimes some models don't have the 'removed' or 'updated'. That's why I get an error. So I want to make the baseadmin general, if the field exits this will make it readonly like it is on the baseadmin, otherwise and if there is not such field this will just pass and won't rise any error. Any idea how to check this and make the baseadmin more flexable? -
How to find the elements inside the QuerySets
If i have two models: Model_1.objects.all() Model_2.objects.all() Model_1 contains all the elements, Model_2 contains a part of these elements. How can i find the elements contained in Model_1 but not in Model_2? I tried: Model_1.objects.exclude(pk=Model_2.objects.order_by('pk')) It doesn't work. -
Django template displaying nothing
I have a TextField(text area) form on my page where users can submit comments and have them displayed, i've left several comments and none of them is showing up. I can see tho everytime i add one the space where the comments are supposed to be grows, after inspecting the page with the dev tools, there's just a bunch of empty HTML tags for all the comments i left, cant figure what the issue is models.py: class Comments(models.Model): comment = models.TextField(max_length=250) user_commented = models.CharField(max_length=64) list_title = models.CharField(max_length=64) list_author = models.CharField(max_length=64) date_time = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return f"{self.user_commented}, {self.date_time}, {self.comment}" forms.py class CommentForm(ModelForm): class Meta: model = Comments fields = ['comment'] views.py commentform = CommentForm() comment = CommentForm(request.POST) if "comment" in request.POST: if comment.is_valid: comment_data = Comments.objects.create(list_title=title, user_commented=username, list_author=author, comment=comment) comment_data.save() comment_data = list(Comments.objects.all().filter(list_title=title)) return render(request, "auctions/listing.html", { "form": form, "listing": listing_object, "checkbox": checkbox, "commentform": commentform, "max_bid": max_bid, "comments": comment_data }) template <form action="{% url 'listing' listing.title %}" method="POST"> {% csrf_token %} {{ commentform }} <input type="submit" value="Comment" name="comment"> </form> <div class="comment"> <h5>Comments</h5> {% for comment in comments %} <p>{{ comments.user_commented }}</p><span>{{ comments.date_time }}</span> <p>{{ comments.comment }}</p> <br> {% endfor %} </div> -
How to add django custom disable button below is a code reference?
https://stackoverflow.com/a/69140267 how can u explain this. How can i add a custom button. not getting an idea of how to solve it. -
Django can i only pass "id" in POST request, despite displaying nested fields?
in my post requests to OrderProduct model, i want to only have to pass order.id and product.id and it works... untill i add a serializer to retrieve product.name. It might be because i didnt understand documentation about nested requests, but im unable to advance further into my project :( [ { "id": 2, "order": 1, "product": 1, } ] ^ here's how it looks without nested serializer, and thats the data that i wanna have to input [ { "id": 2, "order": 1, "product": { "id": 1, "name": "gloomhaven", }, }, ^ here's how it looks after i add an additional serializer. I pretty much want these nested fields to be read only, with me still being able to send simple post requests here are my serializers class OrderProductSerializer(serializers.ModelSerializer): product = Product() class Meta: model = OrderProduct fields = [ "id", "order", "product"] class Product(serializers.ModelSerializer): class Meta: model = Product fields = ( "id", "name") Is there any way for me to accomplish this? Thank you for trying to help! -
Django generic.edit CreateView and UpdateView
i am trying to set a condition for user that is not task.user himself will not be able to update the task by not showing the form .it success on the update part but while createtask the form is not showing.How can i fix it? views.py ` class TaskList(LoginRequiredMixin, ListView): model = Task #default name = {{object_list}} context_object_name = 'tasks' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count() search_input = self.request.GET.get('search-area') or '' if search_input : context['tasks'] = context['tasks'].filter(title__icontains=search_input) context['search_input'] = search_input return context class TaskCreate(LoginRequiredMixin, CreateView): model = Task context_object_name = 'task' fields = ['title','description','priority','complete'] success_url = reverse_lazy('tasklist') def form_valid(self, form): form.instance.user=self.request.user return super(TaskCreate,self).form_valid(form) #create a new form to exclude certain fields on model while updating class PostFormUpdate2(ModelForm): class Meta: model = Task exclude = ('user',) class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task form_class = PostFormUpdate2 success_url = reverse_lazy('tasklist') task_form.html {% extends 'base/main.html' %} {% block content %} <div class="header-bar"> <a href="{% url 'tasklist' %}">&#8592; Back</a> </div> {% if request.user == task.user %} <p>{{task.user}}</p> <div class="card-body"> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input class="button" type="submit" value="Update"> </form> {% endif %} </div> {% endblock content %} ` create and update is using the same form. -
Django ORM: Text aggregator on subquery
I banged my head on this one: I have 2 models, and I am trying to design a custom manager/queryset which will allow me to annotate to each Series the id of the linked puzzles satisfying certain conditions in the format '2,13,26'. The simplified models: class Series(models.Model): puzzles = models.ManyToManyField( Puzzle, through='SeriesElement', related_name='series') is_public = models.BooleanField(null=False, blank=False, default=False) class Puzzle(models.Model): pass my custom aggregator: from django.db.models.aggregates import Aggregate from django.db.models.functions import Coalesce from django.db.models.fields import CharField from django.db.models.expressions import Value class GroupConcat(Aggregate): """ according to https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django according to https://stackoverflow.com/a/55216659 would be compatible with MySQL and SQLite """ function = 'GROUP_CONCAT' def __init__(self, expression, distinct=False, ordering=None, **extra): super(GroupConcat, self).__init__(expression, distinct='DISTINCT ' if distinct else '', ordering=' ORDER BY %s' % ordering if ordering is not None else '', output_field=CharField(), **extra) def as_sqlite(self, compiler, connection, **extra): return super().as_sql(compiler, connection, template='%(function)s(%(distinct)s%(expressions)s%(ordering)s)', **extra) one tentative to achieve my goal: pzl_sub = apps.get_model('puzzles', 'Puzzle').objects.filter(series__id= OuterRef('id')) pzl_sub = pzl_sub.filter(series_elements__isnull=False).add_nb_public_series().filter(nb_public_series=5) pzl_ids= pzl_sub.order_by().values('id') qs = Series.objects.annotate(id_str_pzl = GroupConcat(pzl_ids)) I obtain only one puzzle.id that fit the specified conditions, instead of the concat of all of the puzzle.ids that fit the conditions Any clue on what I'm doing wrong? -
Convert template to dict
How to convert template to dict or json. with open(f"template.py") as t: template_id = Template(t.read()) new_json = eval(template_id) but I failed. -
How to calculate doeking km using property in model
I am stuck in problem ,here i want to calculate doeking km where: doeking km mean,suppose 1 day a vehicle travel 10km and 2nd day travel 20km and 3rd day travel 50km in first day it will so only 10 and second day it will sum 1st day(10)+2nd day(20) = 30km and for 3rd travel 1 day+2day+3day = 80km. here it my model .. class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date_time = models.DateTimeField( default=timezone.now, blank=True, null=True) @property def doeking_km(self): res = Logsheet.objects.filter(log=self,log__date_time__range=[self.date_time, self.date_time + datetime.timedelta(days = 1)]).aggregate(Sum("daily_km")).get("daily_km__sum") return res def __str__(self): return self.vehicle.vehicle_no + " " + str(self.date_time) and .. class Logsheet(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, related_name="logsheets") driver = models.ForeignKey( Driver, on_delete=models.CASCADE, blank=True, null=True) trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, ) distance_to = models.FloatField(blank=True, null=True, ) time_from = models.TimeField(blank=False, null=False, default=timezone.now) time_to = models.TimeField(blank=False, null=False, default=timezone.now) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) daily_km = models.FloatField(blank=True, null=True, ) Than you ! -
Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found
I'm currently rounding up a course in full stack development with python and django, and I've been asked to clone a blog. Anytime I try to save a new post, publish a new post, or see the details of a post I get the error: NoReverseMatch at /post/7 Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?Pd+)/publish/$'] I've checked stack overflow, django documentation and a lot of blogs I haven't been able to resolve it -
How to set the default vaue for ForeignKey
I have this field graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False) and GraduationYear class is. class GraduationYear(BaseModel): label = m.CharField(max_length=255) year = m.CharField(max_length=255,unique=True) def __str__(self): return self.label Now I want to set the GraduationYear object where year=2022 as the default value of graduation_year So, I am guessing I should embed sql to here below. graduation_year = m.ForeignKey('GraduationYear', on_delete=m.SET_NULL, null=False,blank=False,default='select GraduationYear where year=2022') Is it possible?