Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CommentForm design question about Django-comments package
In Django's own comment framework, django-contrib-comments, it has below class defined: In models.py, class Comment (CommentAbstractModel): is defined. In forms.py, class CommentForm (CommentDetailsForm): is defined. Q: since the comment framework is a comment-db-table driven package, why not we use ModelForm to create forms from models, instead of redundantly create another CommentForm class ? -
Issue Pre-populating form in Django
I'm trying to get the user profile name to populate the form field 'user' from AgendaForm but what I get "'user': None". And the prints I get from the views are: {'user': None, 'date': datetime.date(2021, 9, 24), 'time': datetime.time(4, 0), 'comment': 'some comment', 'mode': 'ONLINE'} {'user': <Profile: Jhon Doe>} views.py @login_required(login_url='login') @allowed_users(allowed_roles=['user] def agenda(request): user = request.user.profile initial_data = { 'user': user } form = AgendaForm(initial=initial_data) if request.method == 'POST': form = AgendaForm(request.POST, initial=initial_data) if form.is_valid(): form.save() print(form.cleaned_data) print(initial_data) context = {'form': form} return render(request, 'agenda.html', context) agenda.models.py class Agenda(models.Model): user = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) date = models.DateField(null=True, blank=True, default="1900-01-11") ... def __str__(self): return '%s' % (self.user) main.models.py #(The OneToOneField 'User' comes from the UserCreationForm Django function) class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) id = models.AutoField(primary_key=True, null=False, blank=True) first_name = models.CharField(max_length=50, null=True, blank=True) ... def __str__(self): return '%s %s' % (self.first_name, self.last_name) -
Sending notification to a specific type of user and save the notification in the database using django channels
I want to send notification to a specific group of users. Let's say the specific group is Admin. When an user register on my site after admin approval the user will be activate. For this admin needs to be notified. The main problem was with the database design. I need to save the notification. class Notification(models.Model): view_name = models.CharField(max_length=255) notification_type = models.CharField(max_length=255) sender = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_sender') recipient = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='notification_receiver') title = models.CharField(max_length=255) redirect_url = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_read = models.BooleanField(default=False) Here is the model. Here recipient will be the admin. Now main problem is there will be more than 1 admin. If i want to save the notification the solution came to in my mind is that to iterate through the User model find the admin and send each admin notification which is not a good solutions. Django channels doc shows there is a way to send multiple user using gruop_send() yes I can use that but how can I save the notification in the db with multiple recipient? -
Why won't cmd recognize the from command?
The code that I tried to run. The instructions for said code. I am not sure how my code was any different from what the instructions said to run, does anyone know what I am doing wrong or have any suggestions? -
How to fix 'guni:gunicorn STARTING' error when deploying django project on ec2 ubuntu
I'm hosting a django project on aws EC2 and I have the following content in gunicorn.conf file: [program:gunicorn] Directory=/var/www/html/myapp command=/usr/local/bin/gunicorn --workers 3 --bind unix:/var/www/html/myapp/app.sock myproject.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn.out.log [group:guni] programs:gunicorn After configuring gunicorn I ran the command sudo supervisorctl status. I expected the output to show RUNNING but that is not the case, instead what I'm seeng is guni:gunicorn STARTING: ubuntu@ip-172-31-17-212:/etc/supervisor/conf.d$ sudo supervisorctl status guni:gunicorn STARTING I ran the command whereis gunicorn to know the directory of gunicorn and I got the following output: ubuntu@ip-172-31-17-212:/etc/supervisor/conf.d$ whereis gunicorn gunicorn: /usr/local/bin/gunicorn I want to know where I'm getting it wrong. Also, if the gunicorn.conf file seems accurate, how do I locate the source of the error? With gunicorn status showing STARTING instead of RUNNING, all the web pages are showing 404. Though I'm not very sure whether the gunicorn issue is the cause of404 ERROR on web page. But I want to get the gunicorn running first. -
Python thread breaks down silently when run in the background
In django i am using thread to read xlsx file in the background using thread but after sometimes it breaks down silently withoutgiving any error. thread_obj = threading.Thread( target=bulk_xlsx_obj.copy_bulk_xlsx ) thread_obj.start() -
Canada Post Shipping Cost - Django/Python [API]
I am developing an E-Commerce site with Django and for the shipping, we want to use Canada Post to estimate and show the shipping cost. Unfortunately, their API documentation doesn't have any python guidelines to perform this task. Can anyone please suggest how to use their API to do this? -
Using Stream Field in WagTail throws an error in block content
I followed this official tutorial for WagTail. Now I want to change my BlogPage body column from RichText to StreamField in models.py. I follow this manual to make it works. I changed BlogPage class to look like this class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog_app.BlogCategory', blank=True) body = StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), StreamFieldPanel('body', classname="full"), InlinePanel('gallery_images', label="Gallery images"), ] Now I'm able to edit StreamField in Admin page of Wegtail. I changed content of base.html from {% block content %}{% endblock %} to {% include_block page.body %} to not throwing an error. Now I'm able to see content of StreamField in my post. But because I replaced {% block content %} I'm not able to see anything else (like all posts on blog_index_page.html). But because blog_index_page is looping posts I have to include {% include_block page.body %} in base to properly render content of StramField and not throwing an error that the block … -
how to generate barcode once
i have a problem, i generate barcode for field barcode in model Article barcode On first insert of new object it saved normally but when i update it, the application generate new barcode, how can i make drop it just once? models.py from django.db import models import random from django.contrib.auth.models import User import barcode from barcode.writer import ImageWriter from io import BytesIO from django.core.files import File `Status=(('0','Non'),('1','Oui')) class Article(models.Model): user= models.ForeignKey(User,blank=True,null=True,on_delete=models.CASCADE) numero=models.IntegerField(blank=True) barcode=models.ImageField(upload_to='article/codes',blank=True) nom = models.CharField(max_length=20) quantity=models.IntegerField(null=True) categorie=models.ForeignKey(Categorie,on_delete=models.CASCADE) date_entree=models.DateField(null=True) prix_achat=models.IntegerField(null=True) statut=models.CharField(max_length=2,null=True,default='0',choices=Status) def __str__(self): return self.nom def save(self,*args, **kwargs): EAN =barcode.get_barcode_class('upc') # rend=str(random.randint(2055,99999)) # print(r) r=self.categorie.id+self.user.id rr=self.categorie.id+self.date_entree.day+self.prix_achat ean=EAN(str(self.categorie.id)+str(self.user.id)+str(r)+str(self.date_entree.year)+str(self.date_entree.month)+str(self.date_entree.day)+'34',writer=ImageWriter()) buffer =BytesIO() ean.write(buffer) self.numero=ean.__str__() self.barcode.save(str({self.nom})+'.png',File(buffer),save=False) return super().save(*args, **kwargs) -
Django/Selenium KeyError from None 'GMAIL_PASSWORD'
ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../Django/python-tdd-book/functional_tests/test_login.py", line 36, in test_can_get_email_link_to_log_in body = self.wait_for_email(test_email, SUBJECT) File ".../Django/python-tdd-book/functional_tests/test_login.py", line 72, in wait_for_email inbox.pass_(os.environ['GMAIL_PASSWORD']) File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'GMAIL_PASSWORD' I'm following the obeythetestinggoat book which is awesome but i can't get passed this error, i found another unresolved question on here exactly the same but, not resolved, I've tried digging into gmail access docs eg. 'Allow insecure apps', triple checking i've got the env vars loaded, the system is actually working ie. sending emails out with the correct information and allowing login for that user when clicked, all is working except the tests, the env vars are loaded in the shell i am executing the test from ie. echo $GMAIL_PASSWORD, I did notice the python version for this states is the system python3 but when i run which python3 from my virtualenv it shows the virtualenv version, i've tried recreating my virtualenv even, any help would be awesome i've spent a day on this error. from django.core import mail from selenium.webdriver.common.keys import Keys import re import os import time import poplib def wait_for_email(self, test_email, subject): if not self.staging_server: email = mail.outbox[0] … -
Django is giving different date values for objects accessed via queryset
Context I get different values for datetime field when I access them differently. I am sure there is some utc edge magic going on here. (Pdb++) Foo.objects.all().values_list('gated_out__occurred__date')[0][0] datetime.date(2021, 9, 9) (Pdb++) Foo.objects.all()[0].gated_out.occurred.date() datetime.date(2021, 9, 10) How do I fix/figure out what is happening? -
DataError('value too long for type character varying(40) on Heroku but not on development
My project works fine under the development but got this error on Heroku. The error occurs when user try to register. I use registration redux Traceback (most recent call last): File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(40) ) was the direct cause of the following exception: File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 53, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 56, in form_valid new_user = self.register(form) File "C:\Users\sdgy\SaaS\sdg\sdgenv\users\views.py", line 44, in register new_user = super(Register, self).register(form_class) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\backends\default\views.py", line 96, in register new_user = self.registration_profile.objects.create_inactive_user( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 185, in create_inactive_user registration_profile = self.create_profile( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 211, in create_profile profile.save() File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, … -
Can't connect to Pod in DevSpace following Django tutorial
The DevSpace-Django tutorial in question is the following: https://devspace.cloud/blog/2019/10/18/deploy-django-to-kubernetes Trying something completely barebones to understand how devspace works to decide if I want to make the switch from skaffold. There are a number of things in the above tutorial that seem to be no longer accurate or have changed in more recent versions of devpsace. At any rate, I'm not able to connect to the Django tutorial app when I navigate to localhost:8000. It just says "Can't connect to the server." This is the output I get when I devspace dev: devspace dev [warn] There is a newer version of DevSpace: v5.15.0. Run `devspace upgrade` to upgrade to the newest version. [info] Using namespace 'mysite' [info] Using kube context 'mysite' [info] Execute 'helm upgrade mysite component-chart --namespace mysite --values /var/folders/tl/wqf19mws155_7bkqyw401z_w0000gn/T/325113665 --install --repo https://charts.devspace.sh --repository-config='' --version 0.8.0 --kube-context mysite' [info] Execute 'helm list --namespace mysite --output json --kube-context mysite' [done] √ Deployed helm chart (Release revision: 5) [done] √ Successfully deployed mysite with helm [done] √ Port forwarding started on 8000:8000 (mysite/mysite-7b856bb78b-2ztpf-devspace) ######################################################### [info] DevSpace UI available at: http://localhost:8090 ######################################################### [0:sync] Waiting for pods... [0:sync] Starting sync... [0:sync] Sync started on /Users/cjones/Projects/Apps/Test/mysite <-> . (Pod: mysite/mysite-7b856bb78b-2ztpf-devspace) [0:sync] Waiting for initial … -
Deploy to Heroku State changed from up to crashed
I make prepare all requirements to deploy my project(Python Telegram Bot) to heroku: 1- git init 2- git add Professor_Bot.py Procfile requirements.txt Procfile: contains web: gunicorn Professor_Bot.wsgi 3- git commit -m "Added Files" 4- git push heroku master remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 183.5M remote: -----> Launching... remote: Released v20 remote: https://professorbotapp.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/professorbotapp.git 05091a2..bbb4e1e master -> master 5- heroku logs --tail I'm new to django and gunicorn and Procfile But I see two error in logs I don't know how to solve them I searched a lot: 2021-09-09T21:50:40.076516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=professorbotapp.herokuapp.com request_id=842e9e7e-fa91-4f77-836e-b31a818fecec fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:50:40.400323+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=professorbotapp.herokuapp.com request_id=5207eba6-ddbc-4812-bff4-b0f980d69a16 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:53:26.281857+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=professorbotapp.herokuapp.com request_id=15b29462-518f-4240-b56c-1fb28e9a9e16 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:53:26.664929+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=professorbotapp.herokuapp.com request_id=d31bbda1-47c4-4a0e-878e-cb01ffaa81b1 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https Can anybody Please help me what's the wrong thing that I'm doing... -
Why Django inlineformset_factory getting save prohibited error while file uploading?
Info I am using django inlineformset_factory for file uploading which files are related with Aritcle model. So i have class based view where we are try to save two forms data one is ArticleForm second is FileformSet. ArticleForm data is saved successfully every time but sometime the FileformSet getting error while to uploading files. it's look like one time you can upload successfull second time you can get this error. i also read the documentation but i do not understand it. please anybody tell me how can i solve this issue? ERROR: save() prohibited to prevent data loss due to unsaved related object 'post'. django = Django==3.2.6 python = Python 3.8.10 class NewsCreateView(CreateView): template_name = 'create.html' form_class = ArticleForm model = Article success_url = '/' def get_context_data(self, **kwargs): data = super(NewsCreateView, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = FileFormSet(self.request.POST, self.request.FILES) else: data['formset'] = FileFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() formset = context['formset'] with transaction.atomic(): if formset.is_valid(): formset.instance = form.instance formset.post = form.instance formset.save() return super(NewsCreateView, self).form_valid(form) -
can't cut slash at the end of url in django
I have Django app, There I use some lib. All urls in this lib are ends with slash( / ) path(f"sprite-{get_sprite_hash()}/", home.sprite, name="wagtailadmin_sprite"), path('login/', account.LoginView.as_view(), name='wagtailadmin_login'), I need to make that When I will go on this urls without slash in the end this urls steel working. APPEND_SLASH is not working here, becouse it's only redirect url -> url/ and I need working url without slash and redirections -
setting up django for deployment
I'm trying to deploy my Django app I've split the settings.py and put in a settings folder. Now before I run my server, I must first this set DJANGO_SETTINGS_MODULE=src.settings.dev How can I make the above command to be automatic so I don't have type it every time before running the server .thanks -
Modal forms in change list Django
I'm trying to make it so that when you select an action on the page open modal form. But I don't understand how to display the form when choosing an action. (Use bootstrap for make modal forms) I got only with render(*args) #admin.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.contrib import admin, messages from servers.forms import SetValueForm def set_value_action(self, request, queryset): form = None if 'apply' in request.POST: form = SetValueForm(request.POST) if form.is_valid(): val = form.cleaned_data['val'] count = 0 for item in queryset: item.val = val item.save() count += 1 self.message_user(request, "Success add %d." % (count)) return HttpResponseRedirect(request.get_full_path()) if not form: form = SetValueForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)}) return render(request, 'admin/actions/test.html', {'items': queryset,'form': form, 'title':u'Set new value'}) # forms.py class SetValueForm(forms.Form): VALUES = [ ('Val1', 'Val1'), ('Val2', 'Val2'), ('Val3', 'Val3')] _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) val = forms.ChoiceField(label='value', choices=VALUES) # test.html <div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Set value</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <form action="" method="post">{% csrf_token %} <label>val:</label> {{ form.val }} <p>New value set for:</p> <ul>{{ items|unordered_list }}</ul> <input type="hidden" name="action" value="set_value_action" /> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input type="submit" name="apply" class="btn btn-primary"> </div> … -
AADSTS90102 error when using django-microsoft-auth for SSO with Azure AD
I followed the steps in this tutorial to enable SSO with Azure Active Directory for the admin portion (to start) of my Django app: https://django-microsoft-auth.readthedocs.io/en/latest/usage.html Navigating to /admin yields this page, which is good: Clicking Microsoft brings up this new window: The important error seems to be: AADSTS90102: 'redirect_uri' value must be a valid absolute URI. In this window, I used the browser console and found that a GET request was being made like this: https://login.microsoftonline.com/50ce...90ac7/oauth2/v2.0/authorize?response_type=code&client_id=f4...27&redirect_uri=https,https://example.org/microsoft/auth-callback/&s... Note the redirect_uri=https,https://.... It seems like that leading "https," is superfluous and is causing the problem. Any ideas where that could be coming from? In my Azure app, the redirect URI is set to https://example.org/microsoft/auth-callback/: I'm using Python 3.9.6, Django 3.2, django-microsoft-auth 2.4.0, NGINX 1.18.0, uvicorn 0.14.0 I've searched for help on this and haven't found anything relevant to my situation. Thanks in advance! -
Build fails for Django app running on Heroku
So I'm currently working on a project where I want my Django app to run. The app itself is hosted with Heroku and so, I have a requirements.txt file with the following packages: django-heroku==0.3.1 django==3.2.7 gunicorn==20.1.0 noise==1.2.1 numpy==1.19.2 pandas==1.2.4 scipy==1.6.3 scikit-image==0.17.2 Cython==0.29.23 opencv-python==4.4.0.46 I recently added the Cython and OpenCV packages as I require them for the POT package. However, when I try to deploy the app, the build log says there isn't a module named numpy. I presume this is because numpy hasn't been "installed" yet. Here's the full build log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.7 To use a different version, see: https://devcenter.heroku.com/articles/python runtimes -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.7 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting django-heroku==0.3.1 Downloading django_heroku-0.3.1-py2.py3-none- any.whl (6.2 kB) Collecting django==3.2.7 Downloading Django-3.2.7-py3-none-any.whl (7.9 MB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting noise==1.2.1 Downloading noise-1.2.1.tar.gz (125 kB) Collecting numpy==1.19.2 Downloading numpy-1.19.2.zip (7.3 MB) Installing build dependencies: started Installing build dependencies: finished with status 'done' … -
my sitemap link are not clickable using django sitemap
i am using django sitemap for my model but when i go to sitemap.xml it shown as plain text and not clickable at all any idea what i have done wrong here is my code which i executed my sitemap.py from django.contrib.sitemaps import Sitemap from .models import * class MovieSitemap(Sitemap): def items(self): return Movie.objects.all() under my movie model def get_absolute_url(self): return reverse('blogs:movie_read',kwargs={"title":str(self.urltitle)}) url for detail view path('<slug:title>/movie',views.movie_read,name="movie_read"), settings.py 'django.contrib.sites', 'django.contrib.sitemaps', then main projects url.py from django.contrib.sitemaps.views import sitemap from blogs.sitemaps import * sitemaps={ 'movie':MovieSitemap } path('sitemap.xml',sitemap,{'sitemaps':sitemaps}), and yes i do set site id = 1 in my settings.py screenshot what i mean -
Part of a celery task not being executed
Code: @task def task(): time.sleep(10) a=run() #run is a long running function with string as output logger.critical(a) logger.critical("after running celery") return def view() logger.critical("before running celery") task.delay() return http response Expected Output in log file: before running celery a(string stored in variable a) after running celery Actual Output in log file: before running celery(@time t) after running celery (@time t+10sec) The output of the long running function which is stored in variable a is not being logged. I even tried in the following way in the above mentioned task instead of logger.critical(a) try: a=run() #long running function logger.critical("success") except: logger.critical("failure") Still I got the same output neither success nor failure was logged. Questions Can someone please tell me why the function is not being executed and why I am not even getting an error? I am using a django-redis-celery setup so is it possible to cache the result of the function and display it onto a html page? -
Displaying items from sqlite to django
Hi I'm new and can't quite figure it out. I want to display one item on the last line. I know how for ... in works. But it will display all lines. models.py class shorturl(models.Model): original_url = models.URLField(blank=False) short_query = models.CharField(blank=False, max_length=8) visits = models.IntegerField(default=0) main.html <input class="list-group-item to-copy" placeholder="http://127.0.0.1:8000/{{ ???? }}"> <button class="write-btn">Copy</button> how can i display the last short_query in the database instead of "????" -
Aggregate for multiple instances with a ManyToOne relation
I am new to Django and I want to build a Website to track boardgames. What I want: For each round played a Player will get points and I want to create a table which shows the sum of all Scores for each Player. My model is as follows: class Player(models.Model): name = models.CharField(max_length=150) class Score(models.Model): player = models.ForeignKey(Player, blank=False, null=False, on_delete=models.PROTECT) scorevalue = models.IntegerField(blank=False, null=False) I would like to get a queryset with all players where an additional field with the sum of his scores is added. In SQL something like Select distinct playername, sum(scorevalue) over (partition by playername) from Players Join Scores My main problem is to understand the connection between "aggregate" and "annotate" functions in combination with instances and querysets. With an instance I can get Player.objects.get(pk=1).score_set.aggregate(score_sum=Sum('scorevalue')) but is it possible to do this for every instance in a queryset? Thanks for the help. -
Django - the requested resource was not found on this server
I recently started using django and I followed a tutorial however when I go on the website it states "Not Found The requested resource was not found on this server." Although people have had the same problems as me, I tried to do what they had to do but nothing seems to work. (I made leathercookie the project and leatherbiscuit the app) leatherbiscuit/views.py from django.shortcuts import render def index(request): return render(request, 'hello/index.html') I made index.html under leatherbiscuit/templates/hello index.html <h1>Hello World!</h1> leathercookie/urls.py from django.contrib import admin from django.urls import path from leatherbiscuit.views import index urlpatterns = [ path('admin/', admin.site.urls), path('leatherbiscuit/', index), ] leathercookie/settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leatherbiscuit', ]