Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using sendgrid domain authentication sends email to spam in Django
I am trying to send email from my Django application. For this, I have used Twilio SendGrid service. Though my application can send the email, it ends up in spam folder. So, I have followed this tutorial to authenticate my domain which I bought from AWS route 53. In sendgrid, the domain authentication status shows 'verified' but the emails are still sent to spam folder. I have not created any MX or TXT record in DNS setting as the tutorial says it was created automatically during domain authentication in sendgrid. One thing I have noticed that the email still shows, 'via.sendgrid.net' message (attached an image below) with the email. Whereas it should be my authenticated domain name. I have created sendgrid account with an outlook email and using that address to send email from Django app. Is this the reason my emails are going to spam? Or can anyone please help me to find a solution for this problem? Thanks in advance. FYI: I have done 'Single Sender Verification' in sendgrid during developing this app. But now I have deployed it in aws. I guess this feature is still working instead of 'Domain Authentication'. -
Python Preview Generator FileNotFoundError
I want to generate a thumbnail of attachment uploaded by user, I'm using Python Generator but for some reason I get the following error FileNotFoundError: [Errno 2] No such file or directory: '/media/tenant-2cadb939-306a-43f2-aa53-eb086a4f74b9/AssignedCampaign/2021-2/53676e7d-c95d-4348-a_581e4TM.png' if a.attachment: # get path of attachment without the attachment name cache_path = a.full_path.replace('/'+a.full_path.split('/')[-1], '') + '/preview_cache' log.info('>>>>>>>>>> %s', cache_path) preview_manager = PreviewManager(cache_path, create_folder=True) preview = preview_manager.get_jpeg_preview(a.full_path, width=100, height=200) -
How to refresh cart span or cart div after add product to cart AJAX / Django?
The product is successfully added to the cart but the div containing the cart value is not up to date. You will have to refresh the page so that the div is up to date. I tried the load() and html() methods. How to refresh cart container when I add the product to the cart ? I need a help please. Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: function(data){ $("cartval").load(); … -
Django-admin autocomplete of select-box doesn't work
When I send additional context data to admin.site.urls . Autocomplete in select box gives 500 internal server error. My project's urls.py: My select box in admin page: Error page: But whenever I remove context data from urls it works properly. -
How to design database for saving data into table [closed]
By using API calculating Distance between two Zip codes(post codes) But Here is my question. When user loading page always running API is not good coding so, I want to save that into one table and show that data into classifieds page( items listings). So, Here We are calculating distance between logged in user zip code and Ad posted by user Zip code. In classifieds page we have number of ads so, How can I achieve this Can any one help me to achieve this Thank you. -
Pip says it installs mysqlclient successfully, but cannot find it or uninstall it
I am running into the following issue trying to install mysqlclient as part of getting a Django project up and running on an AWS EC2 instance. In a python 3.8.5 virtual environment: (venv3)$ which pip ~/venv3/bin/pip (venv3)$ pip --version pip 21.0.1 from /home/ec2-user/venv3/local/lib/python3.8/dist-packages/pip (python 3.8) (venv3)$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3-cp38-cp38-linux_x86_64.whl Installing collected packages: mysqlclient Successfully installed mysqlclient-2.0.3 I try running the Django Shell: (venv3)$ python manage.py shell ...full trace stack truncated for brevity... django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? So I tried to find where pip installed it, and it seems to not actually be installed or be a trace of it anywhere: (venv3)$ pip show mysqlclient WARNING: Package(s) not found: mysqlclient (venv3)$ pip freeze | grep -i mysqlclient <nothing> (venv3)$ sudo find / -name mysqlclient <nothing> Then as a sanity check I apparently successfully install it but then pip can't find it to uninstall it: (venv3)$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3-cp38-cp38-linux_x86_64.whl Installing collected packages: mysqlclient Successfully installed mysqlclient-2.0.3 (venv3)$ pip uninstall mysqlclient WARNING: Package(s) not found: mysqlclient Other things I have tried/verified Making sure python is the 64-bit version Checking pip outside of the virtual environment Nuking the virtual … -
What does it mean attempted relative import beyond top-level package?
Traceback File "", line 5, in <module> from ..books.models import Commen ImportError: attempted relative import beyond top-level package forms.py from ..books.models import Comment Maybe problem in urls.py? There is the structure of my project enter image description here -
Update a model after deleting a row in another model in Django
I have two models UserProfile and ChatUser. ChatUser.models.py class ChatUser(models.Model): chat = models.ForeignKey(ChatRoom,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) UserProfile.models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone_number = models.IntegerField(default=0) image = models.ImageField(upload_to='profile_image',blank=True,default='prof1.jpeg') gender = models.CharField(max_length=10) joined = JSONField(null=True) ChatRoom.models class ChatRoom(models.Model): eid = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=100) location = models.CharField(max_length=50) vehicle = models.CharField(max_length=50) brand = models.CharField(max_length=50) max_limit = models.IntegerField() joined in UserProfile is an array consisting room ids of the chatrooms model. Now when I delete a ChatRoom row, it automatically deletes the Foreign Key referenced ChatUser object since I am using on_delete=models.CASCADE. But how to update the joined in UserProfile model. I want to remove the id of the deleted ChatRoom from UserProfile.joined -
Trying to iterate through a dict linked in another dict from a Python API
I am trying to figure out how to get data out of this API endpoint. It is the Sportsipy API. In the Boxscores endpoint it returns a dictionary of a list of games with basic info, one of the values in that dictionary is a list to 'boxscore' which has all the stats from that individual game. When I try dot notation it just returns an error saying the dict has no attribute boxscore. If I try a for loop it says its not iterable. Source Code 'Boxscores' endpoint which then links to the 'boxscore' endpoint. Boxscore Boxscores import requests from django.shortcuts import render from datetime import datetime from sportsipy.ncaab.boxscore import Boxscore from sportsipy.ncaab.boxscore import Boxscores def management(request): games = Boxscores(datetime(2021, 2, 13)) print(games.games) <--- Prints out the dictionary that shows boxscore is there print(games.games.boxscore) <--- Error: dict has no attribute 'boxscore' context = { 'games': games } return render(request, 'management/management.html', context) -
How to order and sort queryset with pagination
I have a bookshop where I would like users to filter the books by their category, and then order the filtered queryset in order of price/most recent etc. I would like to do all of this with pagination too. The issue I have is that whenever I order the filtered queryset, the initial filter is lost. I also lose the filter and ordering when I click the next paginated page, so there are really two issues here. views.py def bookshop_search(request): filter_form = FilterForm() bookresults = Book.objects.all() query_name = '' my_filter = Q() # CATEGORIES FORM if "category" in request.GET: form = CategoryForm(request.GET) if form.is_valid(): queries = form.cleaned_data queries = {k: v for k, v in queries.items() if v is not False} queries = dict.fromkeys(queries, True) query_name = '' for query in queries.keys(): query = '\'' + query.title().replace('_', ' ') + '\', ' query_name += query for query in queries: my_filter |= Q(**{query:queries[query]}) bookresults = Book.objects.filter(my_filter) else: form = CategoryForm() # FILTER FORM if "filter" in request.GET: filter_form = FilterForm(request.GET) if filter_form.is_valid(): if filter_form.cleaned_data['filter_method'] == 'low_to_high': bookresults = Book.objects.filter(my_filter).order_by('price') if filter_form.cleaned_data['filter_method'] == 'high_to_low': bookresults = Book.objects.filter(my_filter).order_by('-price') if filter_form.cleaned_data['filter_method'] == 'recent': bookresults = Book.objects.filter(my_filter).order_by('-pub_date') else: filter_form = FilterForm() # PAGINATION page = … -
headers not being added to aiohttp
Headers aren't being added to aiohttp get/post/put, and I'm very confused The code is like this @classmethod async def http_request(cls, url, message: Message, method, headers={}, **kwargs): headers.update(cls.header) cls.__update_headers(headers, message) async with method(url=url, headers=headers, **kwargs) as response: print(headers) resp = json.loads(await response.text()) resp['status_code'] = response.status if response.status >= 300 and message: await Messages.fail_reply(message, fields=[cls.__handle_errors(resp)]) return None return resp headers being printed is like this {'HTTP_DISCORD_API_KEY': 'token', 'Command_Guild': 'guild', 'Command_User': 'user'} none of the headers are being added and I am very confused.. method is session.get/post/put Django middleware uses the headers with request.headers (I tried adding HTTP_ prefix, and without prefix, both didn't show up on pycharm debug for the headers) PasswordHasher().verify(settings.DISCORD_BOT_HASH, request.headers["DISCORD_API_KEY"]) -
How to invoke table-valued function defined in django
I have created table-valued function instead of stored procedure on database for fetching data on certain condition. How will I invoke that function in django? -
Multiple choice of instances of another model
I have a Car model where one of the properties is horsepower. I also have a Horsepower model. I want my car model to choose from a list of Horsepower instances. class Horsepower(models.Model): title = models.CharField(max_length=255) ... class Car(models.Model): ... horsepower = models.ManyToManyField(Horsepower) I don't want to use ManytoManyField because there should only be one selection. -
How to add related table column in sql to_tsvector?
I am working on a django API in which I need to implement a search-as-you-type feature. At first I wanted to use Django SearchVector and SearchQuery but they seem to perform poorly when query terms are incomplete (which is not ideal for the "as-you-type" part) so I went for the SQL approach. I need to be able to search on first_name and last_name of a contact as well as on the email of the user related to that contact. I used the following to create a search_vector on contact and to add an index on this column. This works great to search on first and last name. ALTER TABLE contact_contact ADD COLUMN search_vector tsvector; UPDATE contact_contact SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '')); CREATE INDEX mc_idx2 ON contact_contact USING GIN (search_vector); I would like to add the user email to this search_vector, something like: ... SET search_vector = to_tsvector('english', coalesce(first_name, '') || ' ' || coalesce(last_name, '') || coalesce(user.email::text, ''); ... I cannnot figure out the correct syntax or process to do that. Any help is greatly appreciated! -
When i create usercreationform in django the username field is auto selected and how can i fix it
Greeting, I am new in django. Username is auto selected when i reload the page why is this and how can i fix it. -
update_or_create django admin imports
I have an app contains these models class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = .. income_period = .. property_market_rent =.. number_of_family_group = .. cruser = .. prop_id = .. state = .. group =.. class FamilyGroup(models.Model): name = models.CharField(.. transaction =models.ForeignKey(Transaction,.. ... class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, .. family_group = models.ForeignKey(FamilyGroup.. name = models.CharField.. date_of_birth = models.DateField.. .... Im trying to make Imports app that will accept xlsx files with some certain format. after i imported the models from the other apps, therefore i've created a model that have a field for each field i n the above models , i removed a lot so it look readable. im trying to make it update_or_create since i think its the best approach to do, since maybe in future maybe i want to update some fields. I have created the first update_or_create for Transaction but since family_group and family_member are childs of Transaction and Inlines i cant figure out how to apply this. the main idea is i have a transaction contains family_groups and family_members inside it . class Batch(models.Model): batch = models.CharField(max_length=50) transaction_chp_reference = models.CharField(unique=True) transaction_rent_effective_date = models.DateField(.. transaction_property_market_rent = models.DecimalField(.. transaction_number_of_family_group = models.PositiveSmallIntegerField(.. family_group_name = models.CharField(.. family_group_family_type = models.CharField(.. … -
How to set default values in Forms
I am Building a BlogApp and i am stuck on a Problem. What i am trying to do :- I am trying to set the Default Value in forms.py for a Form. views.py def new_topic(request,user_id): profiles = get_object_or_404(Profile,user_id=user_id) if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) new_topic = form.save(commit=False) new_topic.owner = profile new_topic.save() return redirect('mains:topics',user_id=user_id) #Display a blank or invalid form. context = {'form':form} return render(request, 'mains/new_topic.html', context) forms.py class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['topic_no','topic_title'] What have i tried :- I also did by using initial , BUT this didn't work for me. form = DairyForm(request.POST,request.FILES,initial={'topic_title': 'Hello World'}) The Problem Default value is not showing when i open form in browser. I don't know what to do Any help would be appreciated. Thank You in Advance -
Django Duplicate Values in ChoiceField
I am new to Django and am having issues with the forms.py. I am pulling values from a database via Models.Py and then using those objects as a dropdown list on my Django page. For example, I have Car Data stored in a database: Honda | Accord | Black | 2016 Toyota | Camry | Red | 2014 Ford | Fusion | White | 2018 Honda | Civic | Silver | 2020 Toyota | Corolla | Black | 2010 And so on. In models.py, I have: class MyCars(models.Model): make_name = models.CharField(max_length=50, blank=True, null=True) model_name = models.CharField(max_length=50, blank=True, null=True) color = models.CharField(max_length=15, blank=True, null=True) year = models.CharField(max_length=15, blank=True, null=True) def __str__(self): all_cars = [] return self.make_name class Meta: managed = False db_table = 'my_cars' Then in my form.py I do something along the line of: all_cars = forms.ModelChoiceField(queryset=MyCars.objects.all()) The problem is I will then have duplicate values for Honda, Toyota etc, when I only need Honda to appear once on the dropdown. Any suggestions/ideas to filter through this? -
Is there a mutlinomial function that allows for floats?
I have been searching around for functions similar to numpy function multinomial For my current use case it was working, although in an update I require to allow for floating points such as 1.5 etc. I am working with data to display on a table over 24 hours (00:00-23:00), which is 24 entries. I have a block called "time period" which is pulled from a database. Example of how this looks now and performs now: v = int(period.volume_for_period) n = int(round((float(period.period_time)*1))) x = [1/n]*n volume = multinomial(v, x) volume_ls = [x/3600 for x in volume] Assuming period.period_time is inside of a loop to loop over database entries. There is 6 entries with period_time as follows 8, 8, 3, 1.5, 2, 1.5 Sample data for volume_for_period would look like 5330880.0, 3902400.0, 1171800.0, 971460.0, 1332720.0, 971460.0 The output is giving me samples to show on a graph. I am thinking of a multinomial function that allows for a floating point to give for example 1.5 of a result instead of rounding up to 2 as I need 24 results not 25. Is it possible or would there be a better way? I would appreciate any help if anyone is willing to even … -
No Reverse Match when using Slugify
Model field: url_slug = models.SlugField(default='', max_length=200, null=False) Model methods: def get_absolute_url(self): new_kwargs = { 'pk': self.pk, 'url_slug': self.url_slug } return reverse('post-detail', kwargs=new_kwargs) def save(self, *args, **kwargs): value = self.title self.url_slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) urls.py: path('blogs/<str:url_slug>-<int:pk>/', BlogDetailView.as_view(), name='post-detail'), template url: "{% url 'post-detail' blog.url_slug|slugify blog.pk %}" Error: Reverse for 'post-detail' with arguments '(56,)' not found. 1 pattern(s) tried: ['blogs\\/(?P<url_slug>[^/]+)\\-(?P<pk>[0-9]+)\\/$'] Can't figure out what the issue is here? Edit: It may be worth noting that I created the slugify method after several model objects were already created, however I went back and added url_slug fields for all of them. -
mail chimp subscription not working with django
Hi everyone I integrate my Django Web app with mail chimp . in my admin panel when I open marketing preference it give me error . and it do not subscribe my users when I click on subscribe my user remain unsubscribe when i hit save .the error I got is {'type': 'https://mailchimp.com/developer/marketing/docs/errors/', 'title': 'Invalid Resource', 'status': 400, 'detail': "The resource submitted could not be validated. For field-specific details, see the 'errors' array.", 'instance': '2b647b4f-6e58-439f-8c91-31a3223600a9', 'errors': [{'field': 'email_address', 'message': 'This value should not be blank.'}]} my models.py file is: class MarketingPreference(models.Model): user =models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) subscribed =models.BooleanField(default=True) mailchimp_subscribed = models.NullBooleanField(blank=True) mailchimp_msg =models.TextField(null=True , blank=True) timestamp =models.DateTimeField(auto_now_add=True) updated =models.DateTimeField(auto_now=True) def __str__(self): return self.user.email def marketing_pref_create_reciever(sender, instance, created, *args, **kwargs): if created: status_code, response_data = Mailchimp().subscribe(instance.user.email) print(status_code, response_data) post_save.connect(marketing_pref_create_reciever, sender=MarketingPreference) def marketing_pref_update_reciever(sender, instance, *args, **kwargs): if instance.subscribed != instance.mailchimp_subscribed: if instance.subscribed: #subscribing user status_code, response_data = Mailchimp().subscribe(instance.user.email) else: #unsubscribing user status_code, response_data = Mailchimp().unsubscribe(instance.user.email) if response_data['status'] =='subscribed': instance.subscribed = True instance.mailchimp_subscribed = True instance.mailchimp_msg = response_data else: instance.subscribed = False instance.mailchimp_subscribed = False instance.mailchimp_msg = response_data pre_save.connect(marketing_pref_update_reciever, sender=MarketingPreference) def make_marketing_pref_reciever(sender, instance, created, *args, **kwargs): if created: MarketingPreference.objects.get_or_create(user=instance) post_save.connect(make_marketing_pref_reciever , sender=settings.AUTH_USER_MODEL) my utils.py is: MAILCHIMP_API_KEY = getattr(settings, "MAILCHIMP_API_KEY" , None) MAILCHIMP_DATA_CENTER = getattr(settings, "MAILCHIMP_DATA_CENTER" … -
How to use Django form elements in jQuery
I have a django app that allows users to add other users in a table via a front end. Is there anyway to use django {{form_fields}} in JQuery? The code below just prints '{{ form.users }}' as text instead of the form, which contains a list of users. var row = '<tr>' + '<td><div class="form-group ">{{ form.users }}</div></td>' + '<td>' + actions + '</td>' + '</tr>'; $("table").append(row); Thanks, -
Anonmyous web chat help Roadmap
I am trying to create a web chat app in which a just has to enter his/her name and join the chat room. But the problem is I don't know how to approach/start this self-learning project. I would like to use the Python Django framework since I know the basics of i I am not an experienced developer. I read a lot of blogs and I came to know for the successful delivery of data I have to use Socket programming in it. Can anyone please tell me the steps/technologies/roadmap which I need to learn in order to give this idea a reality. It's fine if you can't help me in detail but giving just a small idea, tech stack, etc will be a great help. Thank you for giving your valuable towards my request. -
Passing static image paths to templates dinamcally as statements in DJANGO
I am new to Django and still struggling to grasp static files and media files. IF i want have images that are stored in models with mode.FilePathField on my website that are static then how should i call them properly in my templates: using static tag Like that:{% static project.image.path %} or that just by calling it: {{ project.image.path }} When reading tutorial i got answers that the first one but then it doesn't work. It gives me wrong paths i will get 'static/MyApp/static/Myapp/img.jpg' instead of MyApp/static/Myapp/img.jpg I would be really glad for an example of static files called dinamacally. -
How to link two forms (wagtail form and django form) with a foreign key?
I'm using a django form in conjunction with a wagtail form. The django form will record some fields that will be on any form of this type: name, email and the wagtail form will record extra data defined by the form page creator specific to that instance. I've overloaded the serve method to capture both sets of data and I can process both forms, but I'm stuck when trying to add the logic to relate the form contents to each other so that when one submission set is deleted, the other set will be as well. I think what I need is a foreign key. The following code fails at form_submission.event_submission = a.id where I'd like to take the id from the wagtail form submission and add that as a foreign key to the django form, so that when the wagtail form portion is deleted, the other is deleted as well, and so that I can have a usable link between the two form submissions. def serve(self, request, *args, **kwargs): if request.method == 'POST': form = EventSignupForm(request.POST) wagtail_form = self.get_form(request.POST, request.FILES, page=self, user=request.user) if form.is_valid() and wagtail_form.is_valid(): a = self.process_form_submission(wagtail_form) form_submission = form.save(commit=False) form_submission.event_submission = a.id form_submission.save() return self.render_landing_page(request, form_submission, …