Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django: Send agency data in a context dictionary and use it to build markers on map
I have an agency app in my project with a model in which I save company's sale agenies' data including their name and contact info and their coordinates. My agency model: class Agency(models.Model): English = "En" Persian = "Fa" Arabic = "Ar" LANG_CHOICE = [ (English, "English"), (Persian, "Persian"), (Arabic, "Arabic"), ] language = models.CharField( max_length=2, choices=LANG_CHOICE, default=Persian, ) province = models.ForeignKey( Province, on_delete=models.SET_NULL, default=None, null=True, ) city = models.ForeignKey( City, on_delete=models.SET_NULL, default=None, null=True, ) title = models.CharField( max_length=100, blank=True, null=True, ) owner_name = models.CharField( max_length=200, blank=True, null=True, ) address = models.CharField( max_length=500, blank=True, null=True, ) telephone = models.BigIntegerField(blank=True, null=True) mobile = models.BigIntegerField(blank=True, null=True) fax = models.BigIntegerField(blank=True, null=True) latitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True ) longitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True ) def __str__(self): return self.title Now the goal is to write a view for this model in which I'll be sending agency model data in the context dic to the front, and there, use the data to create markers for each agency side by side with a list of agencies. I have no problem writing the view, context dictionary would be something like this: This example is for 1 agency: { "AgencyList": [ { "id": 1, "language": … -
Error while deploying django project to Railway
I am getting this error while opening the deployed site on railwayError. I looked for the solution and found that we need to change the host of mysql settings, so I changed them. These are my new database settings. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'root', 'PASSWORD': 'toor', 'HOST': '0.0.0.0', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I am still getting the error. What should I do? -
For running celery queues in docker, I want to specify multiple queues with different concurrency
Currently I am using docker compose in which I have specified celery as a service where q1,q2,q3 ,q4 and q5 are some different queues , and i want to assign each queue a different concurrency. celery: restart: always build: context: dockerfile: Dockerfile container_name: celery command: celery --app=celery:app worker --concurrency=8 --loglevel=DEBUG -Q q1,q2,q3,q4,q5 depends_on: - redis - web I read somewhere about celery multi , but dont know whether it fits my use case. -
Reading an excel file, extracting each cell value as a str and doing some action on each cell value, Python
I have uploaded an excel file, what I need to do is extract each cell value as str object from the uploaded file and run a query on the cell value. Unfortunately, nothing is working.Need urgent assistance. def read_agent_list(request): request.session.clear_expired() if request.is_ajax(): if request.method == "POST": userfile = request.FILES['userfile'].read() df = pd.read_excel(userfile,header=0) df=df.fillna('') df=df.astype(str) for index, row in df.iterrows(): agentcode=tuple(list(df['Agentcode']) ) agentlist=df.apply(lambda x: x.str.strip()) qry=getData(""" SELECT U.USER_ID AS AGENTCODE""".format() dff=getViaData(qry) -
400 error from loading fixtures onto aws s3 for django
I have a django project with aws s3 used to store images the website has. The website allows users to upload their own image, and that works just fine. When I add a model instance with a jpg, the file is uploaded to aws and can be viewed in the admin panel. The problem is, however, is that I also used fixtures to load in pre defined objects with images, but whenever I interact with the preloaded fixtures in the database, I get a 400 error. Screenshot of databse The first object named "Test" was manually added, and all of the other objects below that one were added from the fixture. Test opens normally but all of the other objects give a 400 error. I tried changing my region in the aws bucket but that did not help. Here is an example of a couple of fixtures { "model": "transfer.Workout", "fields":{ "title": "Lat Pull Downs", "notes": "dont move your back at all, pull towards chest, retract shoulder blades as you go down, let elbows go straight down", "sets": "5", "demonstration": "/demonstrations/back&bicep/back/latpulldowns.gif", "muscle": "back" } }, { "model": "transfer.Workout", "fields":{ "title": "Cable Rows", "notes": "keep shoulder neutral, pull towards abs, pull … -
Send csv file via email django
I want to attach a csv file to an email. i wrote a get method like this : def get(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) file_format = request.query_params.get("file_format", "csv") if file_format == "csv": data_file = export_to_csv( serializer.data, list(self.get_serializer().Meta.fields), "students"), ) return data_file this API generate a link to download the csv... but when I PDB the data_file I find out it is <HttpResponse status_code=200, "text/csv"> this the export_to_csv function : def export_to_csv(data, titles, file_name): #This function will export the data in the form of csv file response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename={}.csv".format(file_name) writer = csv.DictWriter( response, fieldnames=titles, extrasaction="ignore", ) # create dict from translation of headers headers = {title: _(title).replace("_", " ").title() for title in titles} # write translated headers writer.writerow(headers) # write data to csv file for row in data: writer.writerow(row) return response The question is how can I attach the generated csv to the email