Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
incorrect email recieved from contact form django
HI i've got small issue with my contact form it wokes it sends emails but for some reason those emails are not correct i've got field in the form that asks uder email and no matter what i type there the mail comes like from me .. the email i type in the form is in the subject.. i'm not sure if this is correct view def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail([from_email], subject, message, [EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "blog/contact.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.') form class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
403 error with Django-Rest-Framework and Django-Oauth-Toolkit in client_credentials mode
I am trying to us the Django-Oauth-Toolkit authentication with the client_credentials mode, and I can: create successfully create my client_id and client_secret register my token But after, any api call using this token yields a 403 error with the message: { "detail": "You do not have permission to perform this action." } My settings.py is: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "oauth2_provider", "rest_framework", "drf_yasg", "users", ] MIDDLEWARE = [ "oauth2_provider.middleware.OAuth2TokenMiddleware", "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", ] AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",}, ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework.authentication.SessionAuthentication", # To keep the Browsable API ), "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", "oauth2_provider.contrib.rest_framework.TokenHasReadWriteScope", ), } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", # To keep the Browsable API "oauth2_provider.backends.OAuth2Backend", ) -
Django thousands and decimal separation
I have the following code in my html files: {% load humanize %} <table > ..... <td> {{e.giacenza_euro|floatformat:'2' |intcomma}} € </td> But it shows me ad example 1,000,00 €, but I wanto to obtain the following result: 1.000,00 €. How can I obtain it? -
How to restart Django development server without clearing cache?
Anyone know how I can restart Django's development server without clearing the cache? I thought maybe using a filesystem cache would do the trick, but it does not seem to. It appears that Django invalidates the previous cache keys when the development server is restarted. Or rather, Django probably looks for cache keys with a new prefix that is dependent upon the timestamp of the time when the server started. How do I prevent this behavior? -
Django - display and saving in a simple form
This is a very beginner-orientated question but I've been stuck on this issue all day. I would like to load the data for a specific record and be able to save it (Submit button in a template) but i'm still trying to understand instances and the save method. models.py class model_essays(models.Model): user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=100, default='') date_added = models.models.DateTimeField(auto_now_add=True) body = models.TextField() def __str__(self): return self.title I understand the id is created automatically forms.py class frm_essays (forms.ModelForm): class Meta: model = model_essays fields = ['title', 'date_added', 'body'] urls.py urlpatterns = [ path('essay/<int:pk>', views.views_essay), ] views.py {stuck here} @login_required def views_essay(request, pk): if request.method == 'POST': updatedForm = essay_detail(request.POST, instance=request.? {I want the ID of the essay}) if u_form.is_valid(): updatedForm.save() messages.success(request, f'this essay has been updated') return redirect('essay_detail') else: updatedForm = frm_core_concept(instance=request.{as above}) context = { 'updatedForm': updatedForm } return render(request, 'essay_detail.html', context) On the decorator - I haven't gotten around to only allowing the users to view their own created essays, this would be the next large hurdle but not the issue I'm asking about. -
displaying a list of lists in django template
i have the following list of lists : [[ "task1","task2"],["task3","task4", "task5"]] and I'm trying to display each list on the x axis of a graph ( so in total I have 2 graphs) in the HTML template using a script as follow: {% for j in range %} <script> var x = "id"+{{j}}; var myChart = document.getElementById(x).getContext('2d'); Chart.defaults.global.defaultFontFamily = 'Arial'; Chart.defaults.global.defaultFontSize = 14; Chart.defaults.global.defaultFontColor = 'Darkblue'; var massPopChart = new Chart(myChart, { type: 'line', //bar horizontalbar, pie, line, doughnut, radar, polarArea data:{ labels:[ {% for t in tas %} {% for s in t %} '{{s}}', {% endfor %} {% endfor %} ], datasets:[{ label: 'Points', data:[{% for foo in pend %} '{{foo.pending_task.points_upon_completion}}' ,{% endfor %} ], backgroundColor:"grey", borderWidth:2, borderColor:'black' }] }, options:{ title:{ display: true, text:"Productivity", fontSize:20 }, legend:{ display: false // show or not show //position:'', // change position maybe left right }, layout:{ padding:{ left:0, right:0, top:0, botton:0 }, } } }); </script> {% endfor %} but it's not working, I'm not able to separate the two lists -
Django - substracting time
Welcome I have a problem. What field should be in model to substract times. I mean for example: 1st car made 500h 28 mins, 2nd car made 350h 15 min and i need a column substract where I'll have substraction from this two times. I made currently working model but only on integer field. When i tried time field and add something like 500:28 it gave me an error " incorrect time". Current model: class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.IntegerField(help_text = "test", null = True) #current hours ch = models.IntegerField(help_text = "test", null = True) #rm = models.IntegerField(help_text = "test", null = True) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) def __str__(self): return self.registration Really thanks for help -
make length in integerfield django model
my model.py is : from django.core.validators import MinLengthValidator,MaxLengthValidator class clients(models.Model): client_identity_id = models.IntegerField(validators=[MaxLengthValidator(11),MinLengthValidator(11)], unique=True) ' ' my serializers.py is : class UserSerializer(serializers.ModelSerializer): #money = serializers.IntegerField(required=False) class Meta: model = clients fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num') read_only_fields = ('money','client_id') def create(self, validated_data, **kwargs): validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(8)) return clients.objects.create(**validated_data) my views.py is : def post(self,request): data=request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but when i make a post request with client_identity_id=12345678910 it keep telling me "object of type 'int' has no len()" how can i fix that please ? -
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. Django
I'm developing to do lists app , and have some issues , I tried some options , but it didn't help Here is my code: models class Lists(models.Model): date = models.DateTimeField(default=datetime.now,blank=True) title = models.CharField(max_length=200) class ListsItem(models.Model): date = models.DateTimeField(default=datetime.now,blank=True) title = models.CharField(max_length=200) main_list=models.ForeignKey(Lists, on_delete=models.PROTECT, null=True) views lists = Lists.objects.order_by('-date') listitem = ListsItem.objects.order_by('-date').filter(main_list=lists) Here what I tried listitem = ListsItem.objects.order_by('-date').filter(main_list=lists[0]) listitem = ListsItem.objects.order_by('-date').filter(main_list=lists).count() Is there any solutions ? -
Django project pdfkit.from_url not render image
I have used PDFkit to render my HTML file into a PDF. However, the image is not being displayed. I tried the solution for a similar problem posted here and rewrote my code as so: def get_pdf_for(request, slug): invoice = get_object_or_404(Invoice, slug=slug) data = dict() data["object"] = invoice data["DOB"] = "Jan 10, 2015" template = get_template('invoice/invoice_detail.html') html = template.render(data) pdf = pdfkit.from_string(html, False) filename = "sample_pdf.pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response -
Split issues in django html template drop-down list
Actual Data Save in the table field: Active Network Tasks,Network Security,DC facilities Html Template: {% for subcat in all_subcats_keys %} <option value="{{subcat.subcategory }}">{{subcat.subcategory }}</option> {% endfor %} </select> Data's are displaying the drop-down list but it is not splitting by comma. It is displaying in a single data but I need to display as a list. So user select anyone value from the list. Means e.g. Active Network Tasks Network Security DC facilities Please help how to resolve this issues and I was trying to split the data but unable to do it. -
My django server app stops working everytime I insert code described bellow [closed]
Python 3.8.2 Django 3.0.5 When I insert this code: SETTINGS_DIR = os.path.dirname(__file__) PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir) PROJECT_ROOT = os.path.abspath(PROJECT_PATH) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), into my Django web app, it stops working. Terminal says SyntaxError: unexpected EOF while parsing Browser says Error connection refused But without that code it works without any problem. Please help. I appreciate your help. -
Django query that filters on calculated fields, searching for character within string
I have a django model that describes a cyclical status between two dates. It looks something like: class OnCallCycle(models.Model): crew = models.ForeignKey(Crew, on_delete=models.CASCADE) start = models.DateField() end = models.DateField() cycle = models.CharField(max_length=255) where start and end are the inclusive start and end date of the cycle, and cycle is a string representing the on call status cycle using one character per day. E.g.- if you had a 12 day cycle where the first 6 days were on (represented by a P), and the last 6 days were off (represented by an N, cycle would look like: PPPPPPNNNNNN. If the number of days between start and end are greater than the length of the cycle, it repeats. Thus, given an OnCallCycle instance, occ, one can calculate the on call status for a given date, d (known to be between start and end) by: delta = (d-occ.start).days status = occ.cycle[delta % len(occ.cycle)] Is there any way to do this within a query for a given date, d? I would like to do something like this: active_cycles = OnCallCycle.objects.filter( start__lte=d, end__gte=d ).filter( # Find all OnCallCycles where the cycle status for date d is not 'N' ) I am using Postgres for my … -
function inside class is not defined?
I'm trying to check if the unique id generated is unique in the database because it's only 6 characters. class Images(models.Model): uid = models.CharField(max_length=10, default=genid(), editable=False) def genid(): uid = uuid.uuid4().hex[:6] if Images.objects.get(uid=uid).exists(): uid = uuid.uuid4().hex[:6] return uid but it's not working. it tells me genid is not defined, Images is not defined. how can I fix this? thanks -
'[Errno 13] Permission denied: '/static'' even when I have permissions? Django Admin
I recently finished deploying my website using apache2 and django. I was testing everything, including the uploading process. But, when I select a file to upload and hit 'Save', it gives me an error: PermissionError at /admin/path/path2/add/ [Errno 13] Permission denied: '/static' I have all the right permissions, since I wrote these commands to allow permissions: sudo chown -R :www-data project/static sudo chmod -R 775 project/static sudo chown :www-data project/db.sqlite3 sudo chmod 664 project/db.sqlite3 sudo chown :www-data project/ This works, since when I do ls -l, the permissions are correct. This is my apache2 config file (just the static folder part): Alias /static /home/alexholst/excelsite/static <Directory /home/alexholst/excelsite/static> Require all granted </Directory> My settings.py file has this as STATIC_ROOT and STATIC_URL: STATIC_URL = '/static/' STATIC_ROOT = '/home/user/project/static' I dont know if this has to do with anything, but my css does load so i dont think it should have to do with the settings.py. Any suggestions are very much appreciated! -
django-dynamic-formset: copy values on adding form
I am using django-dynamic-formset to add forms of 2 inputs. I would like to to copy the values entered to the fields when the user clicks 'add another'. As far as I understand the description, this can be done with the option keepFieldValues. The script portion is this one <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}', keepFieldValues: '#id_set_set-0-id', }); </script> The part of the template renders as <tr class="row1 formset_row-set_set"> <td> <input type="hidden" name="set_set-0-id" id="id_set_set-0-id"> <input type="hidden" name="set_set-0-workout" id="id_set_set-0-workout"> <div id="div_id_set_set-0-reps" class="control-group"> <div class="controls"> <input type="number" name="set_set-0-reps" placeholder="reps" min="0" class="numberinput" id="id_set_set-0-reps"> </div> </div> </td> Am I misunderstanding the option or how should I apply it? I tried a couple of different options but without any success. TIA! -
Django URL as a variable not working for external site
I have a link being rendered to a template in Django, which changes from record to record. the HTML comes up blank, even though I verified the link works when hard coding it in the site. HTML source rendered: <div id="container2"> <img id="image2" src="" style="width:75%;height:40%;"> </div> source HTML template: <div id="container2"> <img id="image2" src="{{trip.pcs_mca_image.url}}" style="width:75%;height:40%;"> </div> the variable itself is a fully qualified URL such as https://googalopolis.photos.category.jdslkjf.blah.blah when I copy/paste the URL and not use jinja variable it works, but this is issue as each refresh is a new link. -
DjangoCMS - multisite with shared pages
I'm trying to build several websites with DjangoCMS with some shared pages. Is it possible to create a page which is shared across all django Sites? When looking at the code I've seen that the TreeNode is linked to a specific Site (https://github.com/divio/django-cms/blob/develop/cms/models/pagemodel.py#L52), so I guess that if it's possible it won't be really simple (even if I hope so :p). I'd be fine with an external module if DjangoCMS does not handle this, or even some ideas or lead of how to code this, I really don't have a clue. Thanks! -
Use foreign key in django_tables2
I am using django_tables2 to display some data, however one of the columns uses a foreign key and I can't figure out why this data isn't being displayed. I know the foreign key is working, since I can access it in the shell using: In [25]: b = Forms.objects.get(id = "v_akkadianakka1240-mM-1") In [26]: b.source.display Out[26]: 'Black 2000' But it is not clear to me how this translates to the table.py class. model.py class Sources(models.Model): category = models.TextField(db_column='CATEGORY', blank=True) bibtexkey = models.TextField(db_column='BIBTEXKEY', blank=True, primary_key = True) display = models.TextField(db_column='DISPLAY', blank=True, null=True) class Meta: managed = False db_table = 'sources' def __unicode__(self): return self.display class Forms(models.Model): id = models.TextField(db_column='ID', blank=True, primary_key = True) # Field name made lowercase. local_id = models.IntegerField(db_column='Local_ID', blank=True, null=True) # Field name made lowercase. language_id = models.TextField(db_column='Language_ID', blank=True, null=True) # Field name made lowercase. parameter_id = models.TextField(db_column='Parameter_ID', blank=True, null=True) # Field name made lowercase. value = models.TextField(db_column='Value', blank=True, null=True) # Field name made lowercase. form = models.TextField(db_column='Form', blank=True, null=True) # Field name made lowercase. segments = models.IntegerField(db_column='Segments', blank=True, null=True) # Field name made lowercase. comment = models.TextField(db_column='Comment', blank=True, null=True) # Field name made lowercase. source = models.ForeignKey(Sources, on_delete=models.CASCADE, db_column='source') cognacy = models.IntegerField(db_column='Cognacy', blank=True, null=True) # Field name made … -
Subquery for returning the most recent foreign key less than equal to a date
I have two models, Rank and Product. Rank has a foreign key Product. Every day a new Rank is created for each product. However, occasionally an error happens and some date may not have a Rank object for a Product. Therefore, I am trying to return a QuerySet that grabs the most recent Rank object less than or equal to date_str for every Product object. date_str can be any arbitrary date. If several Products do not have Rank objects with a pub_date equal to date_str this queryset should return the most recent Rank in the database before date_str. I thought this function would work, but it fails to return anything at all when an exact match for date_str is not found. date_str = '2020-04-27' def get_queryset(self): r = super().get_queryset().filter(pub_date__lte=self.date_str) return r.filter( pub_date=Subquery( (Rank.objects .filter(product=OuterRef('product')) .values('product') .annotate(last_updated=Max('pub_date')) .values('last_updated')[:1] ) ) ).order_by('-day_rank') -
Is there any way to set up a password for my sqlite3 database in Django?
I have made a ToDoList app using Django. It's a rather simple app as I made it while I was just learning Django. I am still a novice programmer. Anyways, for the database I went with Django's default offering SQLite 3. Now my app won't be used by millions of users around the world so a lightweight database works fine but my main concern is that the database is not protected via a password. For production, the app is hosted on PythonAnywhere via their free tier service and they support SQLite3 for free. I know using something like Postgres is preferred for production scale use. But the app is only made as a personal project and no one is likely to use it for commercial use so SQLite3 seems fine. Moreover, using Postgres would require a paid account on PythonAnywhere. So, I was wondering if I could do something to set up a password for my db file. My settings.py file is this: 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! … -
Confusion creating modal form with Django ModelForm
I'm trying to create a pop-up form for a web app where doctors select a journal (research/scientific journal name) and input some information and it gets added to a list of components showing that information. I'm trying to abstract the form used for them to input journal information into a pop-up form, and am really surprised by how much work it is to add this functionality. I am a beginner with Bootstrap, and am using https://pypi.org/project/django-bootstrap-modal-forms/ because apparently it's almost impossible to get Bootstrap modals to work with Django otherwise. Here are the code changes to the relevant files specified by the library--I have replaced their "create-book" with "create-journalentry" etc. There is a lot of code but it's really a very simple app, and this inability to get modals to work with the ModelForm has been stunningly frustrating me for over a week. models.py from django.db import models from datetime import date from django import forms from bootstrap_modal_forms.forms import BSModalForm JOURNAL_NAME_CHOICES = [ ('NEJM', 'New England Journal of Medicine'), ('JVS', 'Journal of Vascular Surgery'), ] # Create your models here. class JournalEntry(models.Model): name = models.CharField( null=False, choices=JOURNAL_NAME_CHOICES, max_length=256) renewal_date = models.DateField( verbose_name="Date of Renewal", auto_now=False, auto_now_add=False, blank=True, null=True, ) sub_cost … -
RuntimeError: Model class myapp.models.class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
This error has been addressed a lot of times but none of the answers seems to applied to me. I am fairly experienced with Python 2 and 3. I used django for the first time.I started making a project. As i was working with a basic DB and after i called the class.objects for the first time the title error occurred. After some time trying to fix it i moved to the django tutorial and i decided to do everything step by step. The error occured again specifically at "Writing your first Django app, part 3" right befor using render. Directories: \home_dir \lib \Scripts \src \.idea \pages \polls \migrations __init__.py admin.py apps.py models.py test.py views.py \templates \django_proj __init__.py asgi.py manage.py settings.py urls.py wsgi.py __init__.py db.sqlite3 manage.py Do not bother with pages it's a test app. django_proj\settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My App 'polls' 'pages' ] TEMPLATES and DATABASES are well configured polls\apps.py: from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' polls\manage.py from django.db import models from django.utils import timezone import datetime # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) published_date = models.DateTimeField('date published') objects = models.Manager() def __str__(self): return self.question_text … -
AttributeError Django
Getting "Generic detail view ItemDetailView must be called with either an object pk or a slug in the URLconf". #models.py class Pic(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) caption = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'pk2': self.pk}) def __str__(self): return self.caption #views.py class ItemDetailView(generic.DetailView): model = Pic template_name = 'picture/pic.html' #urls.py urlpatterns = { url(r'item/(?P<pk2>[0-9]+)/$', views.ItemDetailView.as_view(), name='item-detail'), } -
Can different Django apps serve the same URL for different MIME types?
I want a URL, say /users/fred, to serve different content based on the Accept header. If the requested MIME type is application/activity+json, I want to serve an ActivityPub representation of Fred's account; otherwise, I want to serve an HTML page. The twist is that I want to implement the ActivityPub view and the HTML view in different Django apps. If they were at different URLs, this would be easily done with urls.py, but that doesn't seem to allow filtering by Accept. Is there a standard way to do this? Do I need to implement something new in middleware?