Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to send django formset data with ajax?
first I want get data from form and then send this data to server with ajax... <script> document.querySelector('form').addEventListener('submit', (e) => { const data = Object.formEntries(new FormData(e.target).entries()); console.log(data); SubmitButtonClicked(); }); </script> <script> function SubmitButtonClicked(){ $.ajax({ dataType:"json", type:"POST", url:"{% url 'meraj_public:new_rrr' %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}", data: data, }, success: function(response){ let success = response.success; if (succes === false){ alert('error'); }else{ alert('success') } } }) } </script> but here, data not diplay on console and there was an error: Uncaught ReferenceError SubmitButtonClicked is not defined -
AttributeError: 'QuerySet' object has no attribute 'url'
this code has this error and I am absolutely lost how to fix it. the code runs fine until it gets to the last object saved in the database and after that it throws this error. the code is a tool that checks the html of a website between 2 points in time to check if it has an error, even if the website is running well and giving a 200 response code This is the error: in check_html print(monitor.url) AttributeError: 'QuerySet' object has no attribute 'url' `def run_monitors(): delete_from_db() monitors = Monitor.objects.filter(is_active=True) monitors._fetch_all() asyncio.run(_run_monitors(monitors)) check_html(monitor=monitors)` `def check_html(monitor): start_time = time.time() print(monitor.url) # The URLs to compare old_html = monitor.html_compare new_url = monitor.url # Get the HTML of each URL try: old_html = old_html # html1.raise_for_status() except Exception as e: print(e) try: html2 = requests.get(new_url) html2.raise_for_status() except Exception as e: print(e) return None html2 = html2.text[:10000] # Create a SequenceMatcher object to compare the HTML of the two URLs matcher = difflib.SequenceMatcher(None, old_html, html2) similarity_ratio = matcher.ratio() * 100 response_time = time.time() - start_time monitor.html_compare = html2 html_failure = False counter = monitor.fault_counter if similarity_ratio <= 90 and counter == 0: print(f"The two HTMLs have {similarity_ratio:}% in common.") print("change detected") … -
Django FormModel fields not found
Currently, the template is only generating the Submit button without any input fields. Also, if I change fields = "all" to fields= ["email","name"] it tells me that these fields do not exist. class NewsletterSubscriber(models.Model): email = EmailField(required=True, label='Email') name = CharField(required=True, label='Name') class SubscribeForm(forms.ModelForm): class Meta: model = NewsletterSubscriber fields = "__all__" def subscribe(request): form = SubscribeForm() if request.method == 'POST': form = SubscribeForm(request.POST) if form.is_valid(): form.save() # redirect to a success page return render(request, 'subscribe.html', {'subscribeForm': form}) <form action="{% url 'subscribe' %}" method="post"> {% csrf_token %} {{ subscribeForm.as_p }} <input type="submit" value="Subscribe"> </form> -
Django Queryset filter datetimefield using time interval
I've got a field in one model like: class Sample(models.Model): created_at = models.DateTimeField(auto_now_add=True, blank=True) this is what it's looks like if saved: 2022-12-13 13:00:29.84166+08 2022-12-13 14:00:29.84166+08 2022-12-13 15:00:29.84166+08 Is it possible to filter that by range of time? maybe similar to this? Sample.objects.filter(created_at __range=["13:00", "15:00"]) I have tried this but it's not working Sample.objects.filter(created_at__time__range=["13:00", "15:00"]) I want to get all the data that ranged with "13:00", "15:00" in different dates -
How can I create a post with Django crispy forms?
I want to add a form so users can create a new post. So I added the following code: {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="boder-bottom mb-4">Inserat erstellen</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} But this is what it end up looking like. I followed the steps from a Youtube Tutorial and the result looks different than mine. What am I'm missing ? -
Mptt model does not return {{ children }}
I have Deviz model that inherits from MPTTmodel. I populated the database with data but can't get to show the children. The tree should be like : Chapter 1 -Subchapter 1 --SubSubchapter 1 ---Article 1 ---Article 2 ---Article 3 Chapter 2 -Subsubchapter1 --Article 1 --Article 2 In the template it only displays the Chapters. When change object_list to object_list.get_descendants, it does not display the first level tree (Chapters) models.py class Deviz(MPTTModel): lucrare = models.ForeignKey(Lucrare, on_delete=models.CASCADE,default='',null=True,related_name="deviz") parent = TreeForeignKey('self', on_delete=models.CASCADE,null=True,blank=True,related_name='children') cod = models.CharField(default='', max_length=20,verbose_name="Cod") norma = models.CharField(default='',max_length=20,verbose_name="Norma") denumire = models.TextField(default='',verbose_name="Denumire") um_articol = models.TextField(default='',verbose_name="Um") oferta = models.FloatField(default=0,verbose_name="Cant Oferta") buget = models.FloatField(default=0) cost = models.FloatField(default=0) def __str__(self): return self.denumire class Meta: verbose_name = 'Deviz' verbose_name_plural = 'Devize' views.py class DevizListview(LoginRequiredMixin, CoreListView): model = Deviz template.html {% recursetree object_list %} <li> {{ node.denumire }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} -
Display product images from a loop using django
I would like to display my images from a loop, my images are stored on static/images and in the database the image field is a CharField of image name. settings.py STATICFILES_DIRS = [ BASE_DIR / 'static', ] STATIC_URL = 'static/' LOGIN_REDIRECT_URL='account:profile' LOGIN_URL='account:login' models.py class Product(models.Model): name=models.CharField(max_length=70,blank=True,null=True) price=models.IntegerField() image=models.CharField(max_length=100,blank=True,null=True) views.py {% load static %} {% for product in products %} <div class="card"> <div class="card-image"> <img src="{% static 'images/{{product.image}}' %}"> </div> </div> {% endfor %} I can't display the image. How to do ?? -
Mock few lines of a function for Unit Tests
I have this below function for which I would like to write unit tests. def fetch_latest_topics(request): username = request.META['username'] try: client = create_discourse_connection(username) response = client.latest_topics() topic_list = response['topic_list']['topics'] filtered_topics_data = [] for topic in topic_list: filtered_topics_data.append( { "title": topic["title"], "created_at": topic["created_at"], "topic_id": topic["id"] } ) except Exception as e: return sendResponse(formatErrorResponse(badreq_err, str(e))) return sendResponse({"post_replies": filtered_topics_data}) I want to mock below lines client = create_discourse_connection(username) response = client.latest_topics() Basically In these lines, I will create a connection with external server and fetch some response. I don't want to do this in unit test (Since this is a library it will be tested beforehand and it's not my code responsibility to test this). I just have to pass a mock response json and validate the response formatting and keys in my unit test. I explored mock library for mocking functions but this is more of a library and it's method call rather than a plain function. It will be a great help if someone can show me the direction to test this. Thank you for giving time to this question. -
Replacing Nginx with Traefik caused Django to use admin files via HTTP instead of HTTPS, breaking functionality
I had a perfectly fine Django CMS 3.4.1 setup running behind Nginx as an edge-server with SSL termination. The complete chain was: nginx (SSL) → nginx (django server) → gunicorn → django All I did was to replace the first nginx reverse proxy with traefik, for a better integration of other services. Everything is run with docker (compose) The issue is, that Django now wants to redirect HTTPS calls to admin files (and ajax calls) to HTTP, breaking functionality because those files are blocked by the browser. I did not change anything with the django installation. In fact, it even is the same docker image as before. Because it did work with the old setup, I don't think that it is an issue with the Django CMS code using hardcoded http://. SSL was terminated before the django reverse proxy, as well. Does anyone see something I am missing? Here are some configuration files, from top to bottom: traefic.yml: global: sendAnonymousUsage: false api: dashboard: true insecure: true providers: docker: endpoint: "unix:///var/run/docker.sock" watch: true exposedByDefault: false log: level: INFO format: common entryPoints: http: address: ":80" http: redirections: entryPoint: to: https scheme: https https: address: ":443" certificatesResolvers: letsencrypt: acme: email: *** storage: /etc/acme/acme.json … -
javascript querySelectorAll is not working on all django objects in the template
I'm working on Auctions website using Javascript and Django. I want to make each user has the ability to view products that he has participated in whether by selling , competition by bids or won bids. So I created a page containing three buttons(won, selling , competiting). On clicking on each buttons , shows the related products(change the display on click). Until now it works. The problem that I want in each product card on mouse over it shows certain div and on mouse out it shows another div. I created the functionality using Javascript (by forEach card in query that selects all cards). the problem that this functionality works on certain cards but upon clicking on the buttons that shows won or competition products, it doesn't work on the related cards (not working on all cards). html: <div class="container"> <div id="userbidsbuttons"> <button class='userbidsbu'id="viewsell">Posted</button> <button class='userbidsbu'id="viewbuy">Won</button> <button class='userbidsbu'id="viewnow">In competition</button> </div> <div class="indexobj"> <div id="viewselluser"> {% if yy.0 is not None%} {% for obj in yy %} <div class="card {{obj.bidcategory}}" style="width: 18rem;" id="{{obj.id}}"> <img class="card-img-top" src="..{{obj.image.url}}" alt="Card image cap"> <div class="thecardcontent" id="co{{obj.id}}"> <div class="card-body"> <h5 class="card-title">{{obj.name}}</h5> <p class="card-text">{{obj.bidcategory.category}}</p> </div> <ul class="list-group list-group-flush"> <ul class="list-group-item"><li ><i class="fa-solid fa-car"></i> {{obj.model}}</li> <li ><i class="fa-solid … -
ChoiceField blank if none of the choices is selected
I'm making a ChoiceField dropdown, but i want to make sure it's empty until unless any of the given choices is selected input_type_mapping = forms.ChoiceField(choices=INPUT_CHOICES,required=False) currently it looks like this: i tried adding blank = true input_type_mapping = forms.ChoiceField(choices=INPUT_CHOICES,required=False, blank = True) but getting the error TypeError: init() got an unexpected keyword argument 'blank' Help me out with this -
Django url call in ajax success innerhtml
I have the below code, $.ajax({ url: '{% url "load" %}', type: 'GET', data: { }, success: function (response) { const data = response.fs content_container.innerHTML = "" data.map(full => { content_container.innerHTML += `<a href="{%url 'business_sale_cust' id=${full.id} btype=${full.interested %}}"> <div class="border border-success mt-2 pl-2"> <h3>${full.companyName}</h3> <p>${full.inputEmail}</p> </div></a>` }) but getting error with <a href="{%url 'business_sale_cust' id=${full.id} btype=${full.interested %}}. please let me know how to pass the parameter id and interested with url. Let me know how to pass the django url within ajax innerhtml. -
How to trigger an email on field change
I have a contact form that users can use to send complaints. However, I want a situation where the support team can indicate if a complaint is resolved or not and it will trigger an email when the status change to 'Resolved'. By default, the complaint is 'pending'. I am currently using a signal. Please, can someone help me because it's not sending email when the status change to 'Resolves'. what am I not doing right? This is what I did: @receiver(pre_save, sender=Contact) def send_email_on_status_change(sender, instance, **kwargs): # Check if the field that you want to watch has changed if instance.status == 'Resolved': # Construct and send the email subject = "Contact status changed" message = "the status of this complaint has changed to has changed to '{}'".format(instance) send_mail( subject, message, 'sender@example.com', ['recipient@example.com'], fail_silently=False, ) @receiver(pre_save, sender=Contact) def save_status(sender, instance, **kwargs): instance.status.save()@receiver(pre_save, sender=Contact) def send_email_on_status_change(sender, instance, **kwargs): # Check if the field that you want to watch has changed if instance.status == 'Resolved': # Construct and send the email subject = "Contact status changed" message = "the status of this complaint has changed to has changed to '{}'".format(instance) send_mail( subject, message, 'sender@example.com', ['recipient@example.com'], fail_silently=False, ) -
Can I create 2 dictionary from only one loop over queryset
This is my code right now : booking_data = {p: 0 for p in vehicle_category.types.all()} vehicle_type_mapping = {k.id: k for k in vehicle_category.types.all()} I wonder if there is a way i can create those 2 dict only with one loop. Or is there another way more efficiently that i can do. -
how to send django formset data to server with ajax?
I try send data to server after submit form, but my script not working. I have multiple forms. One of them used from django-formset. Forms: class UploadReceiptForm(forms.ModelForm): class Meta: model = Receipt fields = ('payment_type', 'payment_mandatory_code', 'payment_optional_code', 'payment_date', 'payment_amount', 'image', 'description') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['payment_type'].required = True self.fields['payment_mandatory_code'].required = True self.fields['payment_date'].required = True self.fields['payment_date'].input_formats += ['%Y/%m/%d'] self.fields['payment_amount'].required = True self.fields['image'].required = True def save(self, rrr): receipt: Receipt = super().save(commit=False) receipt.review_request = rrr receipt.save() return receipt def clean(self): cleaned_data = self.cleaned_data payment_type = cleaned_data['payment_type'] if payment_type == Receipt.PaymentTypes.LETTER_OF_ATTORNEY.value: cleaned_data['payment_amount'] = 0 return cleaned_data def clean_payment_date(self): j_date = self.cleaned_data['payment_date'] try: j_year, j_month, j_day = [int(x) for x in str(j_date).split('-')] except ValueError: raise ValidationError("تاریخ به فرمت صحیحی وارد نشده است") try: date = jdatetime.date(j_year, j_month, j_day).togregorian() except Exception as ex: raise ValidationError("تاریخ به فرمت صحیحی وارد نشده است") return date def clean_description(self): desc = self.cleaned_data['description'] if desc and len(desc) > 300: raise ValidationError("توضیحات باید کمتر از 300 حرف باشد") return desc UploadReceiptFormSet = formset_factory(UploadReceiptForm, extra=0, can_order=False, can_delete=False, max_num=20,validate_max=20, absolute_max=20, can_delete_extra=False) Class base view: class ReceiptReviewRequestView(PermissionRequireMixin, TemplateView): template_name: str = "gentelella/rrr_form.html" admin_view = False data = [] def get(self, request, *args, **kwargs): if not self.has_permission(): return self.redirect_to_login() context = self.get_context_data(**kwargs) context["form"] … -
django-dash: callback generated div id tag not found by other callback
I have been working with plotly dash and especially django-dash for a while, and I am now facing an issue that I am not able to resolve. I am confusedbecause I have successfully used the same structure in the past. Hopefully a pair of fresh eyes could help me see what I am messing up. Here is what I have: => first callback acquires data from a django session and that is used to create a dropdown menu that contains some dataframe extracted values: @app.expanded_callback( Output('output_two', 'children'), [Input('dummy', 'value')] ) def clean_data(file_path,**kwargs): file_path = file_path path = kwargs['request'] path = path.session.get('path') print("path", path) ifc_file = ifcopenshell.open(path) work_plans = ifc_file.by_type("IfcWorKPlan") work_plans_df = pd.DataFrame({ 'id': [schedule.id() for schedule in work_plans], 'StartTime': [schedule.StartTime for schedule in work_plans], 'FinishTime': [schedule.FinishTime for schedule in work_plans], }) work_plans_df['StartTime'] = pd.to_datetime(work_plans_df['StartTime']).dt.date work_plans_df['Status'] = "En cours" work_plan_id = work_plans_df['id'].unique() return html.Div(children=[html.Div( className='five columns', children=[ dcc.Dropdown( id="dropdown", options=list({'label': Id, 'value': Id} for Id in work_plan_id ), value='', ), ], ), ], ) Now, the second call should be using the submited dropdown value and use it to output something (I won't put the details of the calculations) @app.callback( Output('dd-output-container', 'children'), Input('submit-val', 'n_clicks') ,State('dropdown','value') ) def process_workplans(path, n_clicks,value,*args,**kwargs): if value … -
Duplicate Data Stored in django via celery task
I think celery task is calling twice Here is my code @task(run_every=crontab(minute="*/1"), queue="accountability") def analyse(): with transaction.atomic(): analyzed_record, _ = Model.objects.get_or_create( invoice_tag=invoice_tags, product_name="demo" ) analyzed_record.current = 0 analyzed_record.prev = 1 analyzed_record.invoiced = 2 analyzed_record.save() I am using this celery args celery worker --beat --app=demo --concurrency=10 --loglevel=INFO -Q calculate_cost,accountability,scriptQ,ScriptQ,defaultQ I am expecting that if i am using get_or_create then object data must be unique -
What is U0 in postgresql?
I have a django query: review_and_rating_objs = ReviewAndRating.objects.filter(rating__gte=4) products = Product.objects.distinct().filter(reviewandrating__in=review_and_rating_objs) The silmilar query in raw sql(when I print products.query): SELECT DISTINCT * FROM product_product INNER JOIN product_reviewandrating ON (product_product.id = product_reviewandrating.product_id) WHERE product_reviewandrating.id IN (SELECT U0.id FROM product_reviewandrating U0 WHERE U0.rating >= 4) I can't understand what U0 is doing here in the sql. What is meant by U0? I have searched in google and youtube. No explanation found on this question(may be I couldn't search properly). I'm a newbie in django and postgresql. Please experts help me understand this. Thanks in advance. -
How to test methods in models.py related to filters in django using pytest?
I have models which contains lots of classmethods for filtering different kinds of data. Now the problem is, these classmethods are called in views for several functionality. For example, I have Order table as shown below: class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) total = models.DecimalField(max_digits=12, decimal_places=2, default=0) order_date = models.DateTimeField(auto_now_add=True) cancelled = models.BooleanField(default=False) items = models.ManyToManyField(Items, through='OrderItems') status = models.CharField(max_length=30, choices=choice_status, default='waiting') restaurant = models.ForeignKey(Restaurant, on_delete=models.SET_NULL, related_name='orders', null=True) razorpay_payment_id = models.CharField(max_length=100, null=True, blank=True) razorpay_order_id = models.CharField(max_length=100, null=True, blank=True) mode = models.CharField(max_length=10, choices=choice_mode, default='COD', null=True, blank=True) paid = models.BooleanField(default=False, null=True, blank=True) delivery_charges = models.DecimalField(max_digits=12, decimal_places=2, default=0) user_address = models.TextField(max_length=500) user_address_lat = models.DecimalField(max_digits=9, decimal_places=6) user_address_long = models.DecimalField(max_digits=9, decimal_places=6) restaurant_address = models.TextField(max_length=500) restaurant_address_lat = models.DecimalField(max_digits=9, decimal_places=6) restaurant_address_long = models.DecimalField(max_digits=9, decimal_places=6) @classmethod def get_order_with_search_params(cls, params, queryset): search_order_id = None with contextlib.suppress(ValueError): search_order_id = int(params) return queryset.filter( Q(user__username__icontains=params) | Q(restaurant__name__icontains=params) | Q(id=search_order_id) ) @classmethod def get_order_from_status(cls, params, queryset): return queryset.filter(Q(status=params.lower())) @classmethod def get_order_from_restaurant_id(cls, params, queryset): restaurant_id = None with contextlib.suppress(ValueError): restaurant_id = int(params) return queryset.filter(Q(restaurant_id=restaurant_id)) @classmethod def get_object_from_pk(cls, pk): return get_object_or_404(cls, pk=pk) @classmethod def get_total_of_all_orders(cls, queryset=None): if not queryset: queryset = cls.objects.all() return queryset.filter(status='delivered').aggregate(total_sum=Sum('total'))['total_sum'] Now to test these functionality, I have to first have to do following: register user (restaurant type) activate this user … -
How to send smtp email using python django project in cpanel?
When tried to send email using smtp in cpanel but so error error: [Errno 111] Connection refused. Here is my code in django view.py subject = 'Requested For Application Form' message = f'Email successfully send' email_from = settings.EMAIL_HOST_USER recipient_list = ['bedag12032@fanneat.com'] send_mail(subject, message, email_from,recipient_list,fail_silently=False) return redirect('/home') setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'pematep658@lubde.com' EMAIL_HOST_PASSWORD = 'okoik9sa54as' Tried to send email using smtp in cpanel in python django but error [Errno 111] Connection refused. -
How can i achive atomicity just like django orm in fastapi with sqlalchmey orm
How can i achive atomicity just like django orm in fastapi with sqlalchmey orm. What i am trying to do is making a cron script which will delete data from s3 bucket and DB a lot of data. If some how s3 operation fails and it creates inconsistency or either case s3 pass and DB fails. So I want to achive atomicity like we have in django "with atomic transactions". What i am trying to do is making a cron script which will delete data from s3 bucket and DB a lot of data. -
How can I know whether the code is running under testing? Globally?
Now that we can know whether the code in running under DEBUG mode: https://stackoverflow.com/a/16648628/2544762 But at the same time, when we run the code in a unittest, we always got debug == False. https://docs.djangoproject.com/en/4.1/topics/testing/overview/#other-test-conditions In my own case, I just really want to make some code under debug condition, and want it to be tested with debug == True, how can I do? So, is there any way to detect whether the code is running with test? In any place. -
How to load static file of a model in a html templates
I have a static file structure like this -----> static/images/article_images/images.png here's my settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static", # '/css/', # 'images/article_image/', ] here's what I tried: {% extends "base.html" %} {% block content %} {% load static %} ---> i have this in my base.html <div class="article-block" method="GET"> {% for article in articles %} <!-- <img src="{{ article.image }}" alt="Article image"> --> <img src="{% static '{{article.image}}' %}" alt="Article image"> <h2>{{ article.title }}</h2> <p>{{ article.content }}</p> {% endfor %} </div> {% endblock %} -
How to run "SELECT FOR UPDATE" instead of "SELECT" when changing and deleting data in Django Admin?
I have the code below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, when changing data as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below: And, when clicking Delete button of Change person as shown below: Then clicking Yes, I'm sure button to delete data as shown below: SELECT is run instead of SELECT FOR UPDATE as shown below: Now, I want to run SELECT FOR UPDATE instead of SELECT for both cases as shown above. So, how can I do this? -
Get model from multiple apps at once using apps.get_model
I am creating an API that can access multiple apps in a single project and get model from from all of these apps for that I tried this: def get(self, request, **kwargs): m = request.GET['model'] depth = request.GET['depth'] print("model") model = apps.get_model('masters', str(m)) obj1 = model.objects.all() It is working fine when I wanna import model from a single app but in my project I have multiple apps linked together and for this I tried: model = apps.get_model(['masters','dockets'], str(m)) but got an error TypeError: unhashable type: 'list'. apps.get_model doesn't take list but is there any workaround to this?