Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending a emqil with an attachment from django
djando gurus! I need your help! I have an app. It should get the file from the form, then save it to the database and send it by email. I made a model, a form and a view. It seems that everything works fine, the file is saved in the database, a message with an attachment is sent. But the file size in the email attachment = 0 bytes and there is nothing to open it in any email client. What am I doing wrong? Here is a bit of my code: models.py: class Email(models.Model): ... email = models.EmailField(default='...', verbose_name='Email') forms.py: class EmailForm(forms.ModelForm): class Meta: model = Email fields = [..., 'time', 'file', ...] widgets = { ... 'file': forms.FileInput(), } views.py: def sender(request): if request.method == 'POST': form = EmailForm(request.POST, request.FILES) if form.is_valid(): email_save = form.save() ... email_date = request.POST.get('date', '') html_content = render_to_string('email_sender/email_tmpl.html', { ... }) txt_content = strip_tags(html_content) email = EmailMultiAlternatives( email_title, txt_content, settings.EMAIL_HOST_USER, [email_adress] ) email.attach_alternative(html_content, 'text/html') if request.FILES: email_file = request.FILES['file'] email.attach(email_file.name, email_file.read(), email_file.content_type) email.send() return redirect(sender) -
Adding "Did you mean?" feature in Django app
I am working on a simple django app. I have searchbar in which user enters text and then presses search (or enter) and then another page opens with picture of searched word. If user enters wrong word (which is not in dictionary), nothnig happens. I want that, after entering wrong word, new page opens where would be did you mean feature: there would be corrected word which user probably wanted to write and link on picture of that word. I use Norvig's spelling corrector (https://norvig.com/spell-correct.html) I have Index.html: <!DOCTYPE html> <head> <title>Autocomplete with Datalist</title> </head> <body> <h1>DropDown List Autocomplete</h1> <hr /> <!-- horizontal line --> <input list="ddlcomplete" name="q" placeholder="Search fruit name" /> <datalist id="ddlcomplete"> {% for result in autocomplete%} <option>{{result.naziv}}</option> {% endfor %} </datalist> {% if voce.image %} <img src="{{ voce.slika.url }}" class="img-responsive" /> {% else %} <p>No image to preview</p> {% endif %} </body> </html> Spell.py (Norvig's corrector) (in big.txt are all words from dictionary - words that are possible to search for): import re from collections import Counter def words(text): return re.findall(r'\w+', text.lower()) WORDS = Counter(words(open('big.txt').read())) def P(word, N=sum(WORDS.values())): "Probability of `word`." return WORDS[word] / N def correction(word): "Most probable spelling correction for word." return max(candidates(word), key=P) def … -
Login data in token authentication
I used to get this data when i was using session authentication. This data is created when user login from different browser. (on new session object) How do i create this data in token authentication? Since token remains same for all user i cant use post_save / if created signals. Also how do i logout specific user like we used to delete session in session authentication. Thanks in advance! -
Running celery worker on ECS Task and using SQS as a broker
I am building a web application that requires some long running tasks to be on AWS ECS using celery as a distributed task queue. The problem I am facing is that my celery worker running on ECS is not receiving tasks from SQS even though it seems to be connected to it. Following are the logs from ECS task. /usr/local/lib/python3.8/site-packages/celery/platforms.py:797: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format( -------------- celery@ip-xxx-xxx-xxx-xxx.us-east-2.compute.internal v5.0.1 (singularity) --- ***** ----- -- ******* ---- Linux-4.14.252-195.483.amzn2.x86_64-x86_64-with-glibc2.2.5 2021-12-14 06:39:58 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: emptive_portal:0x7fbfda752310 - ** ---------- .> transport: sqs://XXXXXXXXXXXXXXXX:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 2 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> emptive-celery2.fifo exchange=sync(direct) key=emptive-celery.fifo [tasks] . import_export_celery.tasks.run_export_job . import_export_celery.tasks.run_import_job [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' 2021-12-14 06:39:58 [INFO] Connected to sqs://XXXXXXXXXXXXXXXXX:**@localhost// [Errno 2] No such file or directory: 'seq_tokens/emptive-staging_web_sequence_token.txt' [Errno 2] No … -
How to run multiple Django projects on Apache webserver (CentOS)?
I have a Apache webserver and deployed multiple Django projects. So I want to know that what should do if somehow server shutdown or unable to connect with server. How to start or restart services to run my projects. For now, when I am closing my Kitty screen then projects are also not running. Please help me regarding how to run my django projects if I close Kitty session too. I am attaching screenshot below. -
Django UpdateView: Can't update order informations
in my application, I have a template where I should update the order's infos, I succeeded to get two forms in the same template, but I need to update the order's information once I submit it, and here where is the issue. models.py class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name views.py class OrderUpdateView(LoginRequiredMixin, RedirectToPreviousMixin, UpdateView): model = Order form_class = OrderManageForm second_form_class = CustomerForm template_name = 'dashboard/order_details.html' login_url = '/login/' def get_object(self): return Order.objects.get(id=self.kwargs['order_id']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = Customer.objects.get(order__id=self.kwargs['order_id']) context['customer'] = self.second_form_class(instance=customer) return context -
Get list of fileds from reverse relationship
I am trying to get the list of count of a field based on date so I can plot stacked bar graph on frontend. These are my models: class BaseModel(models.Model): id: int created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True) updated_at = models.DateTimeField(verbose_name="Last Updated", auto_now=True) class Meta: abstract = True class A(BaseModel): name = models.CharField(max_length=512, null=True, blank=True) class B(BaseModel): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(BaseModel): b = models.ForeignKey(B, on_delete=models.CASCADE) I am trying to get the count (as list) of B and C when getting the list of A for last 7 days. But I am getting count instead not an object. Using recharts on frontend, my desired output format will be (using sample data from internet): { "items": [ { "name": "android app", "chart_data": [ { "name": "A", "x": 12, "y": 23, "z": 122 }, { "name": "B", "x": 22, "y": 3, "z": 73 }, { "name": "C", "x": 13, "y": 15, "z": 32 } ] }, { "name": "My", "chart_data": [ { "name": "A", "x": 12, "y": 23, "z": 122 }, { "name": "B", "x": 22, "y": 3, "z": 73 }, { "name": "C", "x": 13, "y": 15, "z": 32 } ] } ] } -
Django Schedule task at particular time periodically from user's order in app (without celery)
I am creating a Django App where the user can schedule some tasks to happen at a particular time. for example. in google calendar we tell google what we will be doing tomorrow and then at right time it sends us a notification. similarly here I want it to be flexible, for instance, the user can tell Django the time and function to run. Django will wait for the time and then run the function. like he said turn off lights at 12 pm then Django will do it. or for example:- user says remind me to go to gym in 30 minutes And then after 30 minutes he gets notification. (only Django method without celery or something will be appretiated) Thanks! -
Reverse for 'entrypage' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P<title>[^/]+)$']
VIEWS.PY from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponseRedirect from django import forms import markdown2 from . import util class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) ) def add_page(request): if request.method == "POST": form = AddPageForm(request.POST) entries = util.list_entries() if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) for entry in entries: if title.upper() == entry.upper(): return render(request, "encyclopedia/errorpage.html") else: return HttpResponseRedirect(reverse('encyclopedia:entrypage')) else: return render(request, "encyclopedia/addpage.html", { "form": AddPageForm() }) URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), ] ADDPAGE.HTML <form action="{% url 'encyclopedia:addpage' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-secondary"> </form> LAYOUT.HTML <div> <a href="{% url 'encyclopedia:addpage' %}">Create New Page</a> </div> <div> I have tried updating the urls and the views to this but i keep getting error responses path("add_page/<str:title>", views.add_page, name="addpage"), def add_page(request, title): Please advise where this error response could be coming from as the above edits is what i saw in some other stackoverflow responses to clear the error but this didn't work for me. Thank you -
I keep getting an IntegrityError when i try to use Faker to populate my script
I've tried to delete the migrations folder and then redo the makemigrations process but i keep getting the same IntegrityError and it is probably coming from the migrations code itself but i don't understand it as the creation of the code was automatic by Django. The code below is my population script. import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "first_project.settings") import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake-date)[0] if __name__ == '__main__': print('populating script') populate(20) print('populating complete') -
python argparse - pass file without using command line
I want to pass file using form-data to the argparse. But i'm not getting how to pass file to the argparse without using command-line. I also gone through the [https://stackoverflow.com/questions/31090479/python-argparse-pass-values-without-command-line] this solution but this is not helpful for me. I want to pass file using form-data. can anyone help? Thanks -
Enabling channels leads to SuspiciousFileOperation at /
I noticed that whenever I enable django channels in my code, I get the following error https://drive.google.com/file/d/1YDN8v7rFOsV6jXQseJBCsElXM0pFUC01/view settings.py: INSTALLED_APPS = [ "channels", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "debug_toolbar", "corsheaders", "rest_framework", "rest_framework.authtoken", "core", "drf_yasg2", ] WSGI_APPLICATION = "app.wsgi.application" ASGI_APPLICATION = "app.asgi.application" asgi.py: import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) }) Help would be much appreciated. Thank you in advance! -
how to send data in GET method from client side to server side - ajax
I'm trying to send two dates, start date and end date to return back between two dates , here is what i tried but doesnt work, $(document).ready(function(){ const date_inputs = new FormData(); $('#date_form').submit(function(e){ date_inputs.append('from',document.getElementById('from').value) date_inputs.append('to',document.getElementById('to').value) e.preventDefault(); }) console.log(date_inputs)//returns empty function dateTimePrices(){ $.ajax({ type:'GET', url:'/prices/dateTime/data', data:date_inputs, success:function(data){ const datetimes = data; spinner.setAttribute('hidden',true); var k = '<tbody>'; if(datetimes){ k+= '<tr>'; k+= '<td>' + datetimes["all_qnt"] + '</td>'; k+= '<td>' + datetimes['all_price'] + '</td>'; k+= '</tr>' }else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=2>not found</td>' } k+='</tbody>' document.getElementById('datetime_prices_list').innerHTML = k } }) } dateTimePrices(); }) <form action="" method="GET" id="date_form"> <div class="col-11 p-1 mt-1 mx-auto text-center row rtl "> <p class="col-12 col-sm-6 mx-auto text-left row"> from <input type="date" class="form-control col-9 mr-1" name="from" id="from"> </p> <p class="col-12 col-sm-6 mx-auto text-right row"> to <input type="date" name="to" class="form-control col-9 mr-1" id="to"> </p> <button type="submit" class="btn btn-info >search</button> </div> </form> i also tried this to create the dataForm, const date_inputs= (new Date(fromDate)).toUTCString(); but it say : Property 'append' does not exist on type 'string'.ts(2339) is there away to add date input into dataForm please and here is my django view code def priceByDateTime(request): start = request.GET.get('from') end = request.GET.get('to') print(start,end)# if start and end: datetimes = MyModel.objects.filter(invoice__created_at__range=(start,end)).annotate( … -
User registration with admin authorization
I was wonder if it is possible to include a way that when someone fill the user registration form to register, can the details be sent to an admin email for authorization before the user can login in django? -
Mapping roles in AzureAD to Django groups
Okay, I can now do SSO in Django via AzureAD by using django-microsoft-auth. But I would like to manage the groups there as well. For that we configured to pass roles in the token. But how do I map those to Django groups? I don't seem to find any example for that. -
django.db.utils.IntegrityError: UNIQUE constraint failed: items_auction.auction_id
I have a model called "Auction", it has a unique pk field called auction_id. Now i have a lot of data (over 50k records) and the problem is that when the database is not empty and im trying to upload another batch of records using bulk_create the error pops up. Here is my script for filling data auctions = [ Auction( auction_id=row[0], price=row[1], quantity=row[2], item_id=row[3], auctioned_item=Item.objects.get(item_id=row[3]) if Item.objects.filter(item_id=row[3]).exists() else None, realm_id = realm_id ) for row in reader ] items = [] for auction in auctions: if Auction.objects.filter(pk=auction.auction_id).exists(): Auction.objects.get(pk=auction.auction_id).delete() try: item = auction.auctioned_item if item not in items: item.last_auctioned_date = datetime.now() items.append(item) except: pass Auction.objects.bulk_create(objs=auctions, ignore_conflicts=True) Item.objects.bulk_update(items, ["last_auctioned_date"]) Here is the full error Traceback (most recent call last): File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: items_auction.auction_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 502, in bulk_create returned_columns = self._batched_insert( File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "C:\Users\kacpe\Desktop\praca_inz\venv\lib\site-packages\django\db\models\query.py", line 1270, in _insert return … -
which tools are more suitable for a web app that analyses data
I would like to build a hobby web app to learn more about data analysis. The idea is simple, I want to get publically available data via crawling, such as Covid data and then do some traditional data analysis and plot it on the web. I'm thinking, for the backend, pythong and nodejs seem both as a good choice. Now that I don't know any of them. I have done a lot of web development but never used python while I used nodejs a little bit. Since the app is a web app, nodejs seems a more suitable choice and it seems to have way more npm packages than pip. On the other hand, python seems more suitable for data analysis. What do you think is more suitable for the backend? Writing a web app with python seems like a lot of work while analyzing data with JS also seems like a lot of hustle. Is it practical to merge the two? Use nodejs for the backend and only use python to analysis the data brought by nodejs and then pass it back to nodejs to pass it to the frontend? -
Can't render form fields on profile page so that I can update profile image
Form code: class PFPform(ModelForm): class Meta: model = User fields = ['profile_pic' , 'username'] I added username to check/debug View code: def signed_in_view(request): form = PFPform() return render(request, "hobbies/signed_in.html", { "title": "Signed In Page", "h1": "Signed In Page", }) Where form is called on html template. <form method = "POST" action ="" enctype="multipart/form-data"> {%csrf_token%} {{ form }} <input class = "btn btn-primary" type = "submit"> </form> -
Django is looking for 'postgres' database
I have managed Postgresql database cluster on DigitalOcean. When I set the database parameters in the settings.py and run python manage.py migrate, I get the following error: FATAL: database "postgres" does not exist I've checked with pgAdmin and it is true that there's no postgres database, but why it should be there? My database username is doadmin and database name is defaultdb so why Django is trying to find postgres database? -
how can i add another section in django admin panel footer?
I am working on editing the default django admin panel. I want to add another field here. It already contains delete items. [it contains delete slected items][1] [1]: https://i.stack.imgur.com/Te5RL.png I cant find the correct file for the footer path of admin section. my delete_selected_confirmation.html looks like this. {% load i18n %} <div class="actions"> {% block actions %} {% block actions-form %} {% for field in action_form %}{% if field.label %}<label>{{ field.label }} {% endif %}{{ field }} {% if field.label %}</label>{% endif %}{% endfor %} {% endblock %} {% block actions-submit %} <button type="submit" class="button" title="{% translate "Run the selected action" %}" name="index" value="{{ action_index|default:0 }}">{% translate "Go" %}</button> {% endblock %} {% block actions-counter %} {% if actions_selection_counter %} <span class="action-counter" data-actions-icnt="{{ cl.result_list|length }}"> {{ selection_note }}</span> {% if cl.result_count != cl.result_list|length %} <span class="all hidden">{{ selection_note_all }}</span> <span class="question hidden"> <a href="#" title="{% translate "Click here to select the objects across all pages" %}"> {% blocktranslate with cl.result_count as total_count %}Select all {{ total_count }} {{ module_name }}{% endblocktranslate %}</a> </span> <span class="clear hidden"><a href="#">{% translate "Clear selection" %}</a> </span> {% endif %} {% endif %} {% endblock %} {% endblock %} </div> is this the right file … -
How to override the behaviour of allauth ConfirmEmailView to return a json instead of redirect URL?
I'm using allauth, for confirmation email view, and i need to return a JSON response to front end (React) after successful confirmation as React only understand the 200 but not 301/302, Please help me how i can solve it, Really exhausted. Thanks path('guest/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), -
Django forms taking pre-set value of submit button and not user input
I have two Django forms on one page, i seperate them like this: if request.method == "POST" and "bid" in request.POST: form1 = NewBidForm(request.POST) if form1.is_valid(): # Makes sure the big is higher than the previous highest bid if float(request.POST["bid"]) > listing.startingbid: # Saves bidding to database bidding = form1.cleaned_data["bid"] newbid = Bid(bid=bidding, user=request.user, listing=listing) newbid.save() listing.startingbid = bidding listing.save() return HttpResponseRedirect(reverse("listing", args=[name])) else: messages.error(request, 'This bid is not higher than the previous bid, try again!') return HttpResponseRedirect(reverse("listing", args=[name])) # If the form is not valid, return user to the original listing page else: return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "bids": bids, "highestbid": highestbid, "bidform": NewBidForm(), "commentform": NewCommentForm() }) # Handles user input for user placing a comment on a listing elif request.method == "POST" and "comment" in request.POST: form2 = NewCommentForm(request.POST) print(form2) if form2.is_valid(): # Saves comment to database comment = form2.cleaned_data["comment"] newcomment = Comment(comment=comment, user=request.user, listing=listing) newcomment.save() return HttpResponseRedirect(reverse("listing", args=[name])) else: return render(request, "auctions/listing.html", { "listing": listing, "comments": comments, "bids": bids, "highestbid": highestbid, "bidform": NewBidForm(), "commentform": NewCommentForm() }) The forms look like this: class NewBidForm(forms.Form): bid = forms.DecimalField(label="bid", decimal_places=2, max_digits=10) class NewCommentForm(forms.Form): comment = forms.CharField(label="comment", widget=forms.Textarea) and my HTML looks like this: <form action="{% url 'listing' … -
Django ViewSet with async external calls
I have a Django viewset with actions (endpoints). I have to call two services and - since their response times are long - I want to make it asynchronously. For some reason this code executes synchronously (get_bad_things starts only after get_good_things finishes). import asyncio import requests from rest_framework import viewsets from rest_framework.response import Response class AllThingsViewSet(viewsets.ViewSet): @action(detail=False, url_path="get_things/") def get_things(self, request) -> Response: async def get_good_things(cls): return requests.get("https://stackoverflow.com/") async def get_bad_things(cls): return requests.get("https://stackexchange.com/") try: loop = asyncio.get_event_loop() except RuntimeError: asyncio.set_event_loop(asyncio.new_event_loop()) loop = asyncio.get_event_loop() things = loop.run_until_complete( asyncio.gather(*[get_good_things(self), get_bad_things(self)]) ) return Response(things[0], status=200) What am I doing wrong? I use gunicorn WSGI. -
Django: how to test type of RelatedManager?
How to test the type of a RelatedManager in Django ? assert type(qs) in [models.QuerySet, models.Manager] fails if qs is a RelatedManager how do I test if qs is a RelatedManager ? -
How to use redis-sentinel?
Can Anyone please explain the working of this redis sentinel with master-slave configuration as explained in the image below.