Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
usercreationform can not change password label
I can't change password1,password2 labels from UserCreationForm class. The email address seems to be ok. What could be the problem? class SignUpForm(UserCreationForm): class Meta: model = User fields = ('email','password1','password2',) labels = { 'email' : 'Email address', 'password1' : 'Password', 'password2' : 'Confirmation Password', } -
why i get error when use get_object_or_404?
i used get_object_or_404 in api: @api_view(['POST']) def ticket(request): get_ticket = get_object_or_404(Ticket, pk=106) return Response({'result':'ok'}) when the ticket there is not..i get this error: django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. -
Why am I able to GET data but not PUT it?
I am using React frontend and Django backend, deployed on Heroku. I require authentication (login done with Django), and authentication is required for the API. However, while axios is able to GET data, I am not able to PUT it without getting this error: Error: Request failed with status code 403 I have tried solutions here but none of have worked: CSRF with Django, React+Redux using Axios -
Django Rest Framework - Generate a Token for a non-built-in User model class
I wanted to know if I am able to create a Token for a normal model class. Suppose that I have the following class: class User(models.Model): name = models.CharField(max_length=30, unique=True) profile_pic = models.FileField(upload_to='None/',default='placeholder.jpg') joined_date = models.DateTimeField(verbose_name='date joined', auto_now_add=True) Note that my User class does not extend auth.models.User . Now when I use a signal like this: @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Then Django states that Token.user is not an instance of User. Basically, the same as in this SO thread. From that link above, I learned that my User class has to extend the built-in auth.models.User class provided by Django for authentication. But I am curious and would like to know if there is a way to generate a Token for classes that do not extend auth.models.User ? Is that possible ? If yes, how ? -
Django form.is_valid() is skipped and return false
My form doesn't read the is_valid() part. In the terminal it returns: "POST /app/contact/send_/ HTTP/1.1" 302 0 "GET /app/contact/send_/fail/ HTTP/1.1" 200 4648 I tried to typed random words inside the form.is_valid(), still returns the same as above. It won't allow to successfully send the information to destined email address. I don't know what I have missed. Any help is great. Thank you My Models.py class MessageForm(models.Model): CATEGORY = ( ('B', 'Business inquiry',), ('C', 'Career opportunity',), ('G', 'General inquiry',), ) name = models.CharField(max_length=200) email = models.EmailField(max_length=200) phone = models.CharField(max_length=200) category = models.CharField(max_length=1, choices=CATEGORY) text = models.TextField() forms.py from django import forms from .models import MessageForm class MessagesForm(forms.ModelForm): class Meta: model = MessageForm fields = ['name','email','phone','category','text'] labels = { 'name': "Name", 'email': "Email ", 'phone': "Phone", 'category': "Category", 'text': "How can we help you with?" } Views.py from .forms import MessagesForm from django.shortcuts import render, redirect from django.core.mail import send_mail def contact(request): if request.method == 'POST': form = MessagesForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] category = form.cleaned_data['category'] text = form.cleaned_data['text'] subject = [name, phone, category] form.save() send_mail(subject, text, email, [settings.EMAIL_HOST_USER], fail_silently=False) return redirect('success/', status='success') else: return redirect('fail/', status='fail') else: form = MessagesForm() context ={'form':form} return render(request, … -
Django 'Handler' is not defined
I'm currently working on a Django REST project, and trying to implement the Chain of responsibility pattern on it. Since I downgraded my Python version from 3.9.2 to 3.6.5, I've encountered another problem, which is the following: NameError: name 'Handler' is not defined And this is the code where the error is: from abc import ABCMeta, abstractmethod from typing import Any, Optional class Handler(metaclass=ABCMeta): """ The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request. """ @abstractmethod def set_next(self, handler: Handler) -> Handler: pass @abstractmethod def handle(self, request) -> Optional[str]: pass How can I fix it? -
Why does my HTML footer's width doesn't fill the whole page?
I'm currently using Django to make a website, with Programming With Mosh's tutorial as my foundation. I'm trying to add a footer into my page, but it doesn't fill the whole width of the page. Here's the picture of the footer: https://i.stack.imgur.com/PSgBp.png Here's my base code (Footer part only, to save some time): <body> <div class='container'> {% block content %} {% endblock %} </div> <!--Footer--> <style> .footer-dark { margin:0; padding:50px 0; color:#f0f9ff; background-color:#282d32; } .footer-dark h3 { margin-top:0; margin-bottom:12px; font-weight:bold; font-size:16px; } .footer-dark ul { padding:0; list-style:none; line-height:1.6; font-size:14px; margin-bottom:0; } .footer-dark ul a { color:inherit; text-decoration:none; opacity:0.6; } .footer-dark ul a:hover { opacity:0.8; } @media (max-width:767px) { .footer-dark .item:not(.social) { text-align:center; padding-bottom:20px; } } .footer-dark .item.text { margin-bottom:36px; } @media (max-width:767px) { .footer-dark .item.text { margin-bottom:0; } } .footer-dark .item.text p { opacity:0.6; margin-bottom:0; } .footer-dark .item.social { text-align:center; } @media (max-width:991px) { .footer-dark .item.social { text-align:center; margin-top:20px; } } .footer-dark .item.social > a { font-size:20px; width:36px; height:36px; line-height:36px; display:inline-block; text-align:center; border-radius:50%; box-shadow:0 0 0 1px rgba(255,255,255,0.4); margin:0 8px; color:#fff; opacity:0.75; } .footer-dark .item.social > a:hover { opacity:0.9; } .footer-dark .copyright { text-align:center; padding-top:24px; opacity:0.3; font-size:13px; margin-bottom:0; } </style> <div class="footer-dark"> <footer> <div class="container"> <div class="row"> <div class="col-sm-6 col-md-3 … -
django.db.utils.OperationalError: no such table: contacts_contact
I am trying to migrate to migrate my database using python manage.py makemigrations but always getting this error django.db.utils.OperationalError: no such table: here is the full traceback. python manage.py makemigrations Traceback (most recent call last): File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: contacts_contact The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/neonwave/.virtualenvs/42/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = … -
Find all records without a field
I have mongoDB with an object totals in collection. In some objects dissapeared fields value I have a function which can add field value to objects So how can I make a query which returns all records where it's not value pd = PaymentDoc.objects( date__gte=datetime(2021, 1, 1, 0, 0), #totals__value what should be here? ) -
Django-crontab using AWS EBS
I have successfully created a cron job using the Django-crontab library and its running as expected locally. I now need to deploy my app to Elastic beanstalk but I am not sure how to add my cron jobs once my app is deployed. When running my app locally python manage.py crontab add is used to initialize my jobs. How do I do this using Elastic Beanstalk? settings.py CRONJOBS = [ ('0 9 * * *', 'verify.cron.remove_empty_pages'), ('0 9 * * *', 'verify.cron.remove_expired_credits'), ('*/59 * * * *', 'verify.cron.disconnect_accounts') ] -
Django queryset to get max score of individual ids using annotate
I have the followin model named sitting Class Sitting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("Quiz"), on_delete=models.CASCADE) current_score = models.IntegerField(verbose_name=_("Current Score")) complete = models.BooleanField(default=False, blank=False, verbose_name=_("Complete")) end = models.DateTimeField(null=True, blank=True, verbose_name=_("End")) class Question(models.Model): quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) questionmarks = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Question Marks"), help_text=_("Marks of each question. Beginner-1,Intermediate-2,Advanced-3,Expert-4")) I am trying to create a leaderboard where for a particular period which show all 10 toppers for that week/month. To determine score in % I use the following method. def get_max_score(self): questionmarks= Question.objects.filter(id__in=self._question_ids()).aggregate(Sum('questionmarks')) #return len(self._question_ids()) print(questionmarks) return questionmarks['questionmarks__sum'] def get_percent_correct(self): dividend = float(self.current_score) divisor = self.get_max_score if divisor < 1: return 0 # prevent divide by zero error if dividend > divisor: return 100 correct = float((dividend / divisor) * 100) if correct >= 1: return correct else: return 0 I wanted to get the top 10 users with max % score combined across all quizzes. I tried using code below but unable to determine % score using queryset. sitting = Sitting.objects.filter(complete=True).annotate(total=Count('id')).values('user__username','current_score').order_by('user__username')[:10] Any help is appreciated. -
django ...Could not parse the remainder: ''css/materialize.min.css’' from ''css/materialize.min.css’'
I do follow a tutorial where is add a chat bot ui...the ui is embedded in django.. the structure looks the following... . ├── db.sqlite3 ├── installDjango.sh ├── manage.py ├── rasadjango │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── static │ ├── urls.py │ └── wsgi.py ├── rasaweb │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py └── venv ├── bin ├── lib └── pyvenv.cfg static folder . ├── css │ ├── materialize.min.css │ └── style.css ├── img │ ├── banner.png │ ├── body.png │ ├── botAvatar_old.png └── js ├── chart.min.js ├── jquery.min.js ├── materialize.min.js └── script.js in the rasadjango/settings.py PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') when run ... python manage.py runserver i get an error Could not parse the remainder: ''css/materialize.min.css’' from ''css/materialize.min.css’' part of my index.html file...on top i do load the static.... {% load static %} .... <link rel= “stylesheet” type= “text/css” href= ”{% static 'css/materialize.min.css’ %}”> ... What is wrong... -
Django - Run collectstatic to collect static files but collect all the files in the project directory instead
I am trying to run collectstatic command to collect all of the my static files from the subdirectories of apps and deployed them to my Amazon S3 buckets. I tried to use Zappa following the steps as found in this link: https://romandc.com/zappa-django-guide/walk_static/ After running the command python /manage.py collectstatic, all of the files in my project directory get copied into the static folder. Plus, it is not deployed into the S3 bucket. Here is my code: STATIC_URL = '/static/' STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "/static"), ] if os.environ.get("collectstatic")=='True': # STATICFILES_DIRS += 'static', STATIC_ROOT = os.path.join(BASE_DIR, 'test') #STATIC FILE SETTNGS FOR S3 #Used when we seperate css and js into a static folder DEFAULT_FILE_STORAGE = "django_s3_storage.storage.S3Storage" if os.environ.get('stage'): STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = 'static-myapp-'+ os.environ.get('stage') # These next two lines will serve the static files directly from the s3 bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_S3_BUCKET_NAME_STATIC STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN else: STATICFILES_DIRS+=BASE_DIR, # AWS BUCKET FOR UPLOADED FILES AWS_S3_UPLOAD_BUCKET = "myapp-uploads" Can anyone point out what I did wrong please? Thank you! -
Instantiating Django's User Model
I have seen the different ways of creating an instance of Django's User Model. Which follows best practices in Django development 1. from django.config import settings class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) 2. from django.contrib.auth.models import User class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) -
How can I fix error "'NoneType' object has no attribute 'day'" in django website
I noticed this error in my application, "'NoneType' object has no attribute 'day'". What I have noticed about it is that. I have a model named course_schedule, the course schedule has an option of Monday to Sunday. If the course schedule is partially populated, that is I populate only some days, like 3 days out of the complete 7 days in a week, I get the error but whenever I populate the course schedule populate course schedule model completely, I don't have the error and everything works well. error log: Traceback (most recent call last): File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\FIVERR\Ayyub_SMS\sms\schoolapp\views.py", line 1609, in student_course_list get_all = getall(2021, sch.day) Exception Type: AttributeError at /en/student_course_list Exception Value: 'NoneType' object has no attribute 'day' models.py class course_schedule(models.Model): days_choices = ( ("Mon", 'Monday'), ("Tue", 'Tuesday'), ('Wed', "Wednessday"), ('Thurs', "Thursday"), ('Fri', "Friday"), ('Sat', "Saturday"), ("Sun", "Sunday"), ) day = models.CharField(max_length=60, default="Sun") time_session = models.CharField(max_length=150, default='8:00am') end_session = models.CharField(max_length=150, default='10:00am') def __str__(self): return self.day views.py def getall(year, day): dates = { "Sun": 6, "Mon": 0, "Tue": 1, "Wed": 2, "Thurs": 3, "Fri": 4, "Sat": 5 } d = date(year, … -
setting up search ui ("search experience") for django and elasticsearch
I have a django "back-end" app aiming to provide search & filtering view for an elasticsearch index (currently set-up locally; planned to be deployed on AWS Elasticsearch Service). I am researching how to provide a front-end for the search/filtering functionality with some sort of "boilerplate" package, and I came across the following two potential candidates: https://www.elastic.co/enterprise-search/search-ui https://searchkit.co/ However, I am struggling with this, as to me it feels both are a bit of an "overkill" i.e. they require set-up/installation of number of dependencies, running additional services on additional ports, setting up a proxy... etc. I would expect django to be able to handle most of it. What am I missing here? And is there a more straightforward solution? -
Use annotations on Pytnon 3.6.5
I'm working on a project where I was asked to code some validations using Chain of Responsibility. I am currently using python 3.9.2 on my machine, but the project on docker is on 3.6.5 This piece of code works nice on my machine, but it breaks on Docker: from __future__ import annotations from abc import ABC, abstractmethod from typing import Any, Optional class Handler(ABC): """ The Handler interface declares a method for building the chain of handlers. It also declares a method for executing a request. """ @abstractmethod def set_next(self, handler: Handler) -> Handler: pass @abstractmethod def handle(self, request) -> Optional[str]: pass The error that shows is the following: from __future__ import annotations django_1 | ^ django_1 | SyntaxError: future feature annotations is not defined Is there a way to make the code work on python 3.6.5? -
Working with sqlite django database in python
Im doing a web scraping django project which in short will be a site with pc components like gpus and cpus and it will work as a price monitoring site, tracking all daily price changes etc. Right now Im starting to write a code for the scraper itself which will be just checking and updating prices. My question is what would be the most efficient way to access the product sqlite database in order to get all links that will be redirected to bs4 scraping function which will check all prices. Should I just directly parse through fetched links through basic SELECT query like this (code below) or should I first save these links to other file and then open it with my scraper or is there other "recommended" way. I have 0 experience with working with databases via python and would appreciate all the suggestions. conn = sqlite3.connect('db.sqlite3') c = conn.cursor() c.execute("SELECT link FROM core_product") c.fetchall() #code for scraping would be here, for exapmle: def get_prices(link): #do webscraping for a single product for link in c.fetchall(): get_prices(link) -
Reverse URL resolution for Spring Boot GetMapping
I am currently writing a Spring Boot REST API and wanted to do a reverse resolution of a URL that is defined in a GetMapping. In the Django web framework there is a method for doing that: reverse. But I was not able to find anything like that for Spring Boot. I am looking for something like this: package help.me.stack.overflow; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("api") public class SomeController { @GetMapping(value = "/items/{filter}/blob") public ResponseEntity<?> getItems(@PathVariable String filter, @RequestParam String sorting) { return ResponseEntity.ok().body("here you go"); } @GetMapping(value = "/give-me-url") public ResponseEntity<?> getTheUrl() { return resolveUrl(SomeController.getItems, "foo-filter", "foo-sorting"); // should produce "api/items/foo-filter/blob?sorting=foo-sorting" } } Does something like that exist? How can I use it? -
How to filter by the last element of a json array field in Django
I have a model MyModel with a JSONField called data. This json field contains an array of objects like: [ { "date": "2021-01-01", "amount": 120 }, { "date": "2021-01-02", "amount": 150 } ] I would like to filter by the amount of the last element of the array. From the Django documentation, I understand that I can filter by the first element using: MyModel.objects.filter(data__0__amount__gte=100) How could I do this using the last element? -
I have an error in django views.py file, httpresponse
This is my views.py file from django.shortcuts import render, HttpResponse Create your views here. def Index(request): return HttpResponse("Danial") This is my urls.py file from django.shortcuts import render, HttpResponse Create your views here. def Index(request): return HttpResponse("Danial") -
Django filtered relation not adding condition to query
I have two models: class Album(models.Model): title = models.TextField() class Track(models.Model): name = models.CharField(max_length=50) album = models.ForeignKey('Album', on_delete=models.CASCADE) When build query I would like to achieve left outer join with extra condition. I'm using qs = Album.objects.filter(ljoin=FilteredRelation( 'tracks', condition=Q(tracks__name='demo') ) ) When printing print(qs.query) the join condition is made only on id columns. How to achieve that extra condition like track.name = 'demo' is included in join query? -
Serializes ManyToMany relations in Django Rest Framework
I want to serializing ManyToMany fields. So, in the response for tje Application model should also the band and the band description listed. But I've got the following error message: Got AttributeError when attempting to get a value for field bands on serializer OsdSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Application instance. Original exception text was: 'Application' object has no attribute 'bands'. Anyone who knows why it doesnt work? models.py class Band(models.Model): band = models.CharField(max_length=3) description = models.CharField(max_length=255) in_satellite = models.ForeignKey('Satellite', on_delete=models.PROTECT, blank=True, null=True) wavelength = models.DecimalField(max_digits=4, decimal_places=0, default='0', help_text='Central wavelength (nm)') resolution = models.DecimalField(max_digits=4, decimal_places=0, default='0', help_text='Spatial resolution (m)') def __str__(self): return '%s | %s' % (self.in_satellite, self.band) serializers.py class BandSerializer(serializers.ModelSerializer): class Meta: model = Band fields = ['band', 'description', ] class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer() class Meta: model = Application fields = ['name', 'description', 'bands',] views.py class OsdView(APIView): def get(self, request): applications = Application.objects.all() serializer = OsdSerializer(applications, many=True) return Response({"Your open space data:": serializer.data}) -
Django-tables2 - how can I get counts out in my table on a custom table field?
I'm trying to get some frequency data out from my queryset in a column in my table in django-tables2. I am trying this via a custom field: class MyTable(tables.Table): custom_field = tables.Column(empty_values=()) def render_custom_field(self): total_queryset = self.data.data # trying to get out the row object, to do a filter query something like: row_object = self.rows.instance freq = total_queryset.filter(myfield=row_object.myfield) return f"{len(freq)}/{len(total_queryset)}" However I cannot get the row instance out to do this query. Does anyone know how I can get the row instance out to do this? (I'm also aware getting the total_queryset from self.data.data is probably a hacky way of doing this...) Thanks! -
Django namespace issue: django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace
I've implemented user authentication using the urlpatterns in django.contrib.auth.urls. All the URLs work fine, except logging out. When attempting to logout what I get is this error: NoReverseMatch at /accounts/logout/ 'admin' is not a registered namespace I've tried setting a web_app namespace but then that leads to a new set of problems. Would this still be a better approach, or is there a simple fix to my issue?