Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get foreign key reference in serializer using input value
class Channel(models.Model): name = models.CharField(max_length=20) class Product(models.Model): channel = models.Foreignkey(Channel, on_delete=models.PROTECT) id | name ------------- 1 | Channel1 2 | Channel2 3 | Channel3 4 | Channel4 To create Product objects we simply send id of the Channel obj and serializer will be able to get the referenced object. I have a service that exposes an endpoint and the client simply post requests to create objects. Client doesn't know about the channel ids, it only knows the names of the channels. In this situation, is it possible to have a serializer where client can still send the channel names in the request but in the database they get the correct foreign key references when creating Product obj? Could someone point me to any examples or documentation to handle this? -
Set dafault value to nan in Django Float model
I have a model which was created by this definition: float_field = models.FloatField( blank=True, null=True ) Now, I want to replace all Null values with nan. from math import nan float_field = models.FloatField( blank=True, default=nan ) I tried to make the migration and do the migrate, but it returns this error: django.db.utils.OperationalError: cannot ALTER TABLE "model" because it has pending trigger events I followed this soluton and changed the migration, but it doesn't replace blank records with nan. Databse is PostgreSQL. -
Getting "value must be an integer" when trying to seed YAML data
I'm using Django 2, Python 3.7 and the django-address module (https://pypi.org/project/django-address/). I'm trying to insert some seed data. I have this YAML ... - model: address.locality pk: 1 fields: name: "Chicago" postal_code: "60053" state: name: IL country: - United States When I run my seed command python manage.py loaddata maps/fixtures/seed_data.yaml I get this error ... localhost:web davea$ python manage.py loaddata maps/fixtures/seed_data.yaml Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 923, in to_python return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/serializers/python.py", line 157, in Deserializer data[field.attname] = model._meta.get_field(field_name).to_python(field_value) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 928, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'{'name': 'IL', 'country': ['United States']}' value must be an integer."] During handling of the above exception, another exception occurred: 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 "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/commands/loaddata.py", … -
Django - Multiple photo upload
Is there any way to upload multiple photos, with the same upload button? I know there is an extra widget that you can add a certain amount of images to a modelformset_factory, but I am looking for a way to let the user decide how many photos to upload. Everything works fine if I add extra=3 to the formset. But I would like to eliminate that altogether. Some users will want to upload 3 pics, some will want to upload maybe 25. My view def list_home(request): image_form_set = modelformset_factory(Images, form=ImageForm) if request.method == "POST": listing_form = ListingForm(request.POST) formset = image_form_set(request.POST, request.FILES, queryset=Images.objects.none()) if listing_form.is_valid() and formset.is_valid(): post = listing_form.save(commit=False) post.user = request.user post.save() for form in formset.cleaned_data: if form: image = form['image'] photo = Images(listing=post, image=image) photo.save() return render(request, 'success.html') My Form class ListingForm(forms.ModelForm): class Meta: model = Listing exclude = ('user', 'longitude', 'latitude', 'pub_date') class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image', widget=ClearableFileInput(attrs={'multiple': True})) class Meta: model = Images fields = ['image'] My Image model class Images(models.Model): image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') listing = models.ForeignKey(Listing, on_delete=models.CASCADE) def __str__(self): return str(self.image) -
Changing primary_key in django model
previously I didn't have id in Server class and primary_key was in name, but I wanted to allow users to create multiple Servers with the same name so I decided to create id as a primary_key in Server model. models.py class Server(models.Model): name = models.CharField(max_length=20) id = models.IntegerField(primary_key=True, default=404) owner = models.ForeignKey( User, on_delete=models.CASCADE, ) users = models.ManyToManyField( User, default=owner, related_name='server_users', ) When i'm trying to migrate changes I get error django.db.utils.OperationalError: (1068, 'Multiple primary key defined') You can reproduce it from github repo by changing Server model like above: adding id with primary_key = True and removing primary_key from name -
FormName has no attribute 'error_messages'
I am asking You to help me get over that error: 'NewAnnouncementForm' has no attribute 'error_messages' So, I have a "Announcement" model: class Announcement(models.Model): announcement = 'announcement' alert = 'alert' offer ='offer' announcement_types = ( (announcement, 'Announcement'), (alert, 'Alert'), (offer, 'Offer'), ) id = models.AutoField(auto_created=True, primary_key=True, serialize=True, verbose_name='ID') text = models.CharField(max_length=1500, null=False, blank=False) announcement_type = models.CharField(max_length=12, choices=announcement_types, default=announcement) user_name = models.ForeignKey(CustomUserModel, db_column='user_name', on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) price = models.DecimalField(max_digits=6, decimal_places=2) building_id = models.ForeignKey(Buildings, db_column='building_id', on_delete=models.CASCADE) And I am trying to make a form and view to allow user add his announcements. Here is my form: class NewAnnouncementForm(forms.ModelForm): text = forms.CharField(label='Treść ogłoszenia', max_length=1500) announcement_type = forms.ChoiceField(label='Typ ogłoszenia', widget=forms.RadioSelect, choices=Announcement.announcement_types) #user_name dodac do views przed savem i dodac w save (?) price = forms.DecimalField(label='Podaj oczekiwaną cenę, w przypadku darmowego ogłoszenia wpisz 0') user_name = forms.CharField(widget=forms.HiddenInput()) building_id = forms.IntegerField(widget=forms.HiddenInput()) class Meta(forms.Form): model = Announcement fields = ('text', 'announcement_type', 'price', 'user_name', 'building_id') def save(self, commit=True): announcement = super(NewAnnouncementForm, self).save(commit=False) announcement.text = self.cleaned_data['text'] announcement.announcement_type = self.cleaned_data['announcement_type'] announcement.price = self.cleaned_data['price'] if commit: announcement.save() return announcement And views.py which is a main problem i guess: def add_announcement(request): if request.user.is_authenticated: if request.method=='POST': username = str(request.user.username) user_object = CustomUserModel.objects.values_list('address', flat=True).get(username=username) form = NewAnnouncementForm(request.POST) form.fields['user_name'].initial = username form.fields['building_id'].initial = user_object … -
Problem while adding a new question in Django Polls app
Facing " OperationalError at /admin/polls/question/add/ " while adding a new question. https://i.stack.imgur.com/6tkzY.png -
Simplest way to assign version numbers to static files in django to avoid caching?
I want to introduce versioning on static files so that the browser doesn't cache them since I will be putting out changes quite often. So currently in my index.html, I call my two files index.css and index.js like so {% extends "base.html" %} {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/index.css' %}"> <script type="text/javascript" src="{% static 'js/index.js' %}"></script> Now I want to introduce versioning such that the browser is forced to fetch the latest files when I update the files with some changes. Offcourse this doesn't mean it should always fetch new files but when I ask it to. So to do that I need to register a template tag. So I make a folder called templatetags and keep it in the same level where my models.py and urls.py are. (Keeping it elsewhere Django throws error). I name the file as assign_version.py. This is the content inside the file import time from django import template register = template.Library() @register.simple_tag def static_version(): print("version changed!!") version = int(round(time.time() * 1000) return version Now I change my index.html to refer to these two tags like so {% extends "base.html" %} {% load staticfiles %} {% load assign_version %} <link rel="stylesheet" href="{% static … -
Django sum based on foreignkey relationship (3 models involved)
I have the following question: I have 3 models: Contrato, Movimiento and MovimientoDato, I need to generate a queryset that throws me the SUM of the field importe of MovimientoDato for each Contrato, MovimientoDato is linked to Movimiento and Movimiento is linked to Contrato through foreign keys In the resulting queryset I need all the Contrato fields plus a field that we can call balance that adds up the amounts of MovimientoDato.importe related to each Contract using Movimiento as the bridge to make SUM Group, is this possible? Here are the models: class Movimiento(models.Model): fecha = models.DateField(default=timezone.now) contrato = models.ForeignKey(Contrato, related_name='rn_contratos', on_delete=models.CASCADE) OPCIONES = ( (1, 'Abono'), (2, 'Cargo'), ) tipomovimiento = models.IntegerField(choices=OPCIONES, default=1) formapago = models.ForeignKey( FormaPago, on_delete=models.CASCADE, null=True, blank=True) nota = models.CharField(max_length=255, blank=True) archivo = models.FileField(upload_to='images/', blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class MovimientoDato(models.Model): movimiento = models.ForeignKey( Movimiento, related_name='partidas', on_delete=models.CASCADE) categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) concepto = models.CharField(max_length=150, verbose_name="Concepto") importe = models.DecimalField(max_digits=12, decimal_places=2, default=0) class Contrato(models.Model): propiedad = models.ForeignKey(Propiedad, on_delete=models.CASCADE) inquilino = models.ForeignKey(Inquilino, on_delete=models.CASCADE) fechainicio = models.DateField(default=datetime.now) fechafinal = models.DateField(default=datetime.now) renta_check = models.BooleanField(default=True) renta = models.DecimalField(max_digits=15, decimal_places=2, default=0) mantenimiento_check = models.BooleanField(default=True) mantenimiento = models.DecimalField( max_digits=15, decimal_places=2, default=0) agua_check = models.BooleanField(default=True) agua = models.DecimalField(max_digits=15, decimal_places=2, default=0) electricidad_check = models.BooleanField(default=True) electricidad = … -
ProgrammingError at / ORDER BY "id" is ambiguous LINE 1: ...logapp_article.userid=blogapp_useradd.uname ORDER BY id DESC
Exception Value: ORDER BY "id" is ambiguous LINE 1: ...logapp_article.userid=blogapp_useradd.uname ORDER BY id DESC Error location from views.py def Index(request): ad1 = ads.objects.raw("select * from blogapp_ads order by id desc limit 1") ad2 = ads.objects.raw("select * from blogapp_ads order by id desc limit 1 offset 1") ad34 = ads.objects.raw("select * from blogapp_ads order by id desc limit 2 offset 2") ob1 = news.objects.raw("select * from blogapp_news order by id desc limit 5") obb = article.objects.raw( "select * from blogapp_article inner join blogapp_useradd on blogapp_article.userid=blogapp_useradd.uname ORDER BY id DESC LIMIT 14") obj = article.objects.raw( "select * from blogapp_article inner join blogapp_useradd on blogapp_article.userid=blogapp_useradd.uname ORDER BY id DESC LIMIT 5") ob = article.objects.raw( "select * from blogapp_article inner join blogapp_useradd on blogapp_article.userid=blogapp_useradd.uname ORDER BY id DESC") return render(request, 'Guest/Index.html', context={'data9':obb, 'data3': ob1,'data1': ob, 'data2':obj, 'time': now,'data4':ad1,'data5':ad2,'data6':ad34}) -
Change URL without reload in Django 3
I've wondered if there is a smart way to change URL in django 3, without reload. So I basically wanna change www.myurl.dk/step1 to www.mysite.dk/step2 without refreshing in django 3 There's a very little focus on the new django version so far, so I specifically wanna know how it's done there. -
Django - Model - create x new fields based on interger value in another field
I am new to Django and have hit a wall about how to setup my data model (and possibly form logic) I have equipment that is controlled by IP based powerbars - these powerbars can have 2, 4, 8, or 16 outlets. The "equipment", which can consist of more than one physical item (e.g. server, monitor, fan, etc...) can use one or more outlets. We would like to ignore the idea of powerbars and base the system on outlets - so if I have two 8 outlet powerbars, there would be 16 outlets (numbered 1-16), and so on.... Each piece of equipment would have 1 to x outlets assigned to it, regardless of which powerbar the outlet is actually physically installed in. Knowing all this, I have a few issues. 1) In the model/admin interface how would I add a powerbar, select from a drop down the number of outlets it has (2, 4, 8 or 16) and then have the form show the correct amount of interger fields so we can type in the assigned outlet number. I.e. If I was creating two powerbars Powerbar 1 has 8 outlets, Powerbar 2 has 16 - so I would number them … -
How to display a current user only in django user form
class Book(models.Model): description = models.CharField(max_length=10) pdf = models.FileField(upload_to='books/pdfs/') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.description def delete(self, *args, **kwargs): self.pdf.delete() super().delete(*args, **kwargs) #forms.py class BookForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(BookForm, self).__init__(*args, **kwargs) class Meta: model = Book fields = ('description', 'pdf', 'user') When i run an application it shows all the users, I want to restrict to only current user who is logged in. -
Options and post method django rest framwork
can anyone tell me what is the difference between 1st and last line in the screenshot screenshot here when I am trying to log in from frontend login form(react) it gives nothing as response and showing the first line in my terminal on the other hand when I am trying to log in from rest-framework's built-in login form then it successfully logged in and generate my token. how can I resolve this issue? -
How to save data into database
forms.py class AddGradeForm(forms.Form): student = forms.CharField(label='Nazwisko') subject = forms.CharField(label='Nazwa przedmiotu') grade = forms.ChoiceField(label='Ocena', choices=GRADES) views.py class AddGradeView(View): def get(self,request): form = AddGradeForm() return render(request, 'exercises/form.html', {'form':form}) def post(self,request): form = AddGradeForm(request.POST) if form.is_valid(): last_name, subject, grade = form.cleaned_data.values() student = Student.objects.filter(last_name=last_name) if not student: return HttpResponse("Student doesnt exist!") przedmiot = SchoolSubject.objects.filter(name=subject) if not przedmiot: return HttpResponse("Subject doesnt exist") *** how to send new grade for given student and subject redirect to student grades? new_grade, created = Student.objects.get_or_create(last_name=student, grades = grade, subject=przedmiot) return redirect('student', pk=new_grade.pk) else: return render(request, 'exercises/form.html', {'form': form}) -
How to merge bytes into a single memoryview object
I have a list of memoryview objects and needs to be parsed as numpy array. I can parse a single memoryview object, but I can't do it using a list. binaries = MyModel.objects.all().values_list('my_binary_field', flat=True) np.frombuffer(binaries[0], dtype=np.float64) # OK np.frombuffer(list(binaries), dtype=np.float64) # I can't do this I don't wanna copy the bytes into a buff since they are already loaded in RAM. There is a way o concatenate memoryview objects? -
Accessing via www. will throw Nginx welcome page [+ Gunicorn + Django]
Nginx + Ubuntu 18.04 + Django 2.2.10 Accessing directly via "www.examples.com" will show nginx welcome page, but accessing anything else--"examples.com", "https://examples.com", "https://www.examples.com"--will work as expected. On DigitalOcean, I have two A-type records [www.examples.com, examples.com] directing to the IP address--I believe they are correctly set up. On my Django project, I have ALLOWED_HOSTS = ['localhost', 'examples.com', '137.68.49.136', 'www.examples.com'] set. Here is my /etc/nginx/sites-available/project: server { server_name examples.com www.examples.com; charset UTF-8; error_log /home/jay/eco/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/jay/eco/static; } location /media/ { alias /home/jay/eco/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/examples.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/examples.com/privkey.pem; # managed by Certb$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = examples.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name examples.com; return 404; # managed by Certbot } What am I missing? -
How to set crispy_forms' Layout to render a Django DecimalField with exactly 2 decimal places?
In a Django form my_form with a DecimalField I would like to show in that field a float value with exactly two decimal places. The definition of this field is fee = forms.DecimalField(decimal_places=2, max_digits=7) and in the html template I render the form with crispy_forms as {% crispy my_form %} If the decimal places of fee have any value not 0 everything works fine (e.g. 70.12 --> "70.12"). But if I they are 0 only the integer part of this value is shown (70.0 --> "70"). Is there any way to convince crispy_forms to display values always with two decimal places (70.0 --> "70.00")? I searched for hours in the world wide web for a solution but found really nothing. Thx in advance. Humbalan -
Nginx/Gunicorn/Django server timeout problem
I have a website using Django, Gunicorn and Nginx. I use some integrated services (like Mautic) using API requests. But eventually this services stop and the server throws a 502 Bad Gateway error due to a timeout. I searched extensively for answers but found only answers that suggested increasing the Nginx's or Gunicorn's timeout tolerance time. The problem is that when a service stop it will never respond and as the error is generated by the server, the process in Django apparently is killed. An example of a view with a simple flow @api_view(['GET','POST']) def view_example(request, format=None): item = request.GET['item'] simple_request(item) # from this line onwards is not executed The request example using requests import requests def simple_request(item): url = 'https://example.com' data = {'item': item} headers = {'example': 'example'} response = requests.post(url, data=data, headers=headers) -
Django/Form i want to save form with request.POST and request.FILES
When i will save, it is dont save photos, only values were update, how can i add options, save values and media def detail_edit(request, id): if request.user.username == 'admin': item = Buses.objects.get(id=id) form = ItemForm(request.POST or None, instance=item, ) if request.method == 'POST': if form.is_valid(): form.save() messages.success(request, 'Объект успешно изменен') return redirect('index') messages.error(request, 'Что то пошло не так, объект не изменен') return redirect('index') return render(request, 'buses/detail_edit.html', {'form': form, 'bus': item}) return redirect('index') -
i clone git my django project and wsgi application could not be loaded
this is my code screenshot i clone my git project but this is error. why? Everything worked before uploading to git. how fix this error? django.core.exceptions.ImproperlyConfigured: WSGI application 'web.wsgi.application' could not be loaded; Error importing module. The exact code can be found in the screenshot above settings.py """ Django settings for web project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=8)rt!ugu3bbe-_myr7#&ae6cs=%#krp+h+&a57nh35gic&+%r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'livereload.middleware.LiveReloadScript', ] ROOT_URLCONF = 'web.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'web.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': … -
Django only regenrate Thumbnail if postcover chnages
I'm using signals to delete uploaded files on Object delete or change but i went into the issue that I have to determine when to re-generate the postocover_tn or not and I don't know how to implement this step. I just need to re-generate postcover_tn on change of postcover models.py (generate thumbnail on save) postcover = models.ImageField( verbose_name="Post Cover", blank=True, null=True, ) postcover_tn = models.ImageField( verbose_name="Post Cover Thumbnail", blank=True, null=True, ) ... def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if os.path.exists(self.postcover.path): image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 500 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 175 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover_tn = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) elif self.postcover_tn: self.postcover_tn.delete() super(Post, self).save(*args, **kwargs) signals.py @receiver(models.signals.pre_save, sender=Post) def post_auto_delete_files_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding object is updated with new file. """ if not instance.pk: return False try: old_postcover = sender.objects.get(pk=instance.pk).postcover old_postcover_tn = sender.objects.get(pk=instance.pk).postcover_tn except sender.DoesNotExist: return False if … -
Django ValidationErrors not being displayed
Hi, I'm applied a validation for when the users selects a future date in the datepicker, so far if the user tries to save the form does not save it, this is expected, but it does not show the error message for the field. This is one of the things that I have tried so far: forms.py class PostPagos(forms.ModelForm): def clean(self): cleaned_data = super(PostPagos, self).clean() fecha = cleaned_data.get('fecha') hoy = datetime.date.today() if fecha > hoy: raise forms.ValidationError( 'La Feha no puede ser mayor al día de hoy') class Meta: model = Pagos fields = ('carro', 'pago', 'fecha', 'semana', 'renta') widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}), 'semana': forms.DateInput(attrs={'type': 'week'}) } views.py class PagosCreate(CreateView): form_class = PostPagos template_name = "AC/add_expense.html" def form_valid(self, form): object = form.save(commit=False) object.startweek, object.endweek = self.weekdatetimeconverter( object.semana) object.save() return super(PagosCreate, self).form_valid(form) def weekdatetimeconverter(self, semana): d = semana startweek = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w") endweek = datetime.datetime.strptime(d + '-0', "%Y-W%W-%w") return (startweek, endweek) models.py class Pagos(models.Model): carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=False, null=False) pago = models.DecimalField(max_digits=6, decimal_places=2) fecha = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) semana = models.CharField(max_length=20) startweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) endweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) renta = models.ForeignKey( Renta, on_delete=models.PROTECT, blank=False, null=False) created_at = … -
Accessing a dynamic url in a django template
How do I call the dynamic value of a view function in a template file? My view function looks like this: @login_required(login_url="bashorunemmascrumy/accounts/login") def move_goal(request, goal_id): dictionary = {'error': 'A record with that goal id does not exist'} try: goalname = ScrumyGoals.objects.get(goal_id = '%s' % goal_id) except Exception as e: return render(request, 'bashorunemmascrumy/exception.html', dictionary) And the urlconf for the app is: urlpatterns = [ path('', views.get_grading_parameters), path('movegoal/<int:goal_id>', views.move_goal, name="movegoal"), ] While the template is: <p><a href={% url 'bashorunemmascrumy:movegoal' 'goal.goal_id' %}>Move Goal</a></p> When 'Move goal' is clicked I want the url bar to have '.../bashorunemmascrumy/movegoal/1. The value (1) is represented by goal.goal_id. But in this case, I'm having a Templates syntax error in this form: TemplateSyntaxError at /bashorunemmascrumy/movegoal/1 Empty variable tag on line 12 Request Method: GET Request URL: http://127.0.0.1:8000/bashorunemmascrumy/movegoal/1 Django Version: 3.0.2 Exception Type: TemplateSyntaxError Exception Value: Empty variable tag on line 12 Exception Location: /home/bashorun/Documents/linuxjobber-internship/venv/lib/python3.6/site-packages/django/template/base.py in parse, line 444 Python Executable: /home/bashorun/Documents/linuxjobber-internship/venv/bin/python3 Python Version: 3.6.8 Python Path: ['/home/bashorun/Documents/linuxjobber-internship/myscrumy', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/bashorun/Documents/linuxjobber-internship/venv/lib/python3.6/site-packages'] Server time: Thu, 6 Feb 2020 17:35:56 +0000 How do I get the url to work as I intend? -
Django: Localize Date without Year
Any idea how to localize a date, which should only displays day and month respectively month and day? I know how to format the whole date: formats.date_format(datetime.now(), format="DATE_FORMAT", use_l10n=True) Which returns the date as: Feb. 6, 2020 or 6 Feb. 2020 according to the locale setting. I need the same Output, but without the year.