Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django in memory uploaded file has no attribute starts with
i'm coding up a rest api where i'm passing a python file. i'd like to take the python file, import a function from it and use it. I can read in the file using this: custom_file = request.FILES['custom']. If I print out the type of this, I get <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. This is a python file called test.py. ` I'd like to import a function from that file but I can't seem to do it properly. Here's what i'm trying: mod = import_module(custom_file) new_func = getattr(custom_file, file_name) df = new_func(json_file) I think there's a confusion between what i'm supposed to be passing to import_module, it requires a string of the file, but i'm passing in the file as a request to my API. How would I go about doing this? I've tried loading up the function without the request using the commands above (if i just have it in the same directory without the rest api) and it works. So I just need to figure out how to access the right information from the request call. -
Combining multiple substitutions with regular expressions in python, django
Couldn't find any solution to my question from the questions answered before. These are my patterns that match title, subtitle, an italic text and so on: p1 = re.compile(r'(#\s?).+\s') # title p2 = re.compile(r'##\s?.+\s') # subtitle p3 = re.compile(r'\s\*[^*]*\*(\s|\.)') # italic p4 = re.compile(r'(\s\*\*)[^*]*(\*\*(\s|\.))') # boldface p5 = re.compile(r'(\s\*\*\*).*(\*\*\*\s)') # bold italic p6 = re.compile(r'\w*\n') # paragraph p7 = re.compile(r'(\*|-)(\s?)[^*]*(\n)') # list p8 = re.compile(r'\[[^ ]*\)') # link Here is my function in views.py of Django: def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": util.get_entry(title), "title": title }) Just for information, this function shows me the content of the page via the context ("entry": util.get_entry(title)), which will be passed to the template. Currently, the page shows me the markdown content, texts with symbols. The function and other related ones are working fine, so no need to change them (no need to focus on this part). I'd like to convert all words wrapped with symbols to respective texts by substituting them (in short, markdown to HTML). If I change the dictionary in context by putting one of my patterns, like "entry": p3.sub(r'replacement', util.get_entry(title)), it … -
Django-Allauth OAuth2 problems with Gunicorn behind Nginx reverse proxy
I would ask for help on my specific configuration: I have a Django application executed by gunicorn with an Nginx reverse proxy. Everything runs on the same Docker instance, run by Supervisord. Gunicorn runs on port 8000, Nginx runs on port 80. Note: If I run only the Django application (no Nginx proxy) everything works properly and OAuth from Google works. The Nginx config is server { listen 80; location /static/ { alias /home/app/static/static_assets/; } location /media-files/ { internal; # only the django instance can access this url directly alias /home/app/media/media_assets/; } location / { proxy_pass http://localhost:8000; } } I am trying to use the above solution to make OAuth2 work with Google. With the original configuration the error is as follows: Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:8000/accounts/google/login/callback/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/${your_client_id}?project=${your_project_number} If I add the configuration snippet I get the error below: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Forwarded-Proto $scheme; Code: unknown, Error: HTTPSConnectionPool(host='accounts.google.com', port=443): Max retries exceeded with url: /o/oauth2/token (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f79207eb640>: Failed to establish a new connection: [Errno … -
Django - AJAX Fetch sends request for each input letter
This might be far from how it should be done, I'm learning on the go and it's my first time trying something like this. Problem: Even with the setTimeout function, server sends response for each letter I have written, though I would expect it to wait for user to stop typing and just fetch the finished word(s) Script in my template: lookup.addEventListener('keyup', e => { let searchValue = e.target.value; if (searchValue.length > 4){ setTimeout(() => { fetch(`{% url 'find_book' %}?param=${e.target.value}` ) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err))}, 2000); } views.py @api_view(['GET']) def find_book(request): param = request.GET.get("param") if param: url = f'https://www.googleapis.com/books/v1/volumes?q=intitle:{param}&key=xxx' r = requests.get(url) if r.status_code == 200: data = r.json() return Response(data, status=status.HTTP_200_OK) else: return Response({"error": "Request failed"}, status=r.status_code) else: return Response({}, status=status.HTTP_200_OK) -
Python Cannot find file when using terminal
I am trying to use the MacOS terminal to makemigratons to a certain file. I typed python ./manage.py makemigrations in the terminal but MacOS give me this error: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory I'm used to windows so it could be a formatting error but I'm not sure. Irfan -
Using Django-Q in production
I was wondering whether I had to do anything special when using Django Q (https://django-q.readthedocs.io/en/latest/) in production. I have a Q_Cluster setup and I can run mange.py qcluster to start all my scheduled tasks. Would I be doing the same in production? -
Add processing text in a column of datatable
I have a DataTable which basically contains a list of location and corresponding IP Address. In the status column, I want a gif which would mean it's pinging the IP Address to check whether the host is up or down. I am using Django and I have a function which returns True or False depending on the state, but how do I that? I have looked upon processing functionality of the Datatable but that would mean I would have to wait for all the ping test to complete before loading the table. Is it possible to show processing while pinging is going on and once the result is received, update that particular cell value to True? -
Add view to Django only for testing (not in production)
I want to test my session handling. I wrote a view and a test for this, and everything is fine. But I don't like the fact, that the URL is accessible in the production system, too. Is there a simple way to make an view only available during testing. In the production system this URL should not be in known to the url-resolver. -
Problems installing django-observer package
Hello I am trying to install django-observer for python3 on my Win10 PC but I keep getting following error message: Collecting django-observer Using cached django-observer-0.4.3.tar.gz (7.4 kB) Requirement already satisfied: django>=1.2 in c:\users\luca dieling\appdata\local\packages\pythonsoftwarefoundation.python.3.8_qbz5n2kfra8p0\localcache\local-packages\python38\site-packages (from django-observer) (3.1.4) Collecting distribute Using cached distribute-0.7.3.zip (145 kB) ERROR: Command errored out with exit status 1: command: 'C:\Users\Luca Dieling\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Luca Dieling\\AppData\\Local\\Temp\\pip-install-k757dx1_\\distribute_c11e8be23eda49c7809d38d8e88b222e\\setup.py'"'"'; __file__='"'"'C:\\Users\\Luca Dieling\\AppData\\Local\\Temp\\pip-install-k757dx1_\\distribute_c11e8be23eda49c7809d38d8e88b222e\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Luca Dieling\AppData\Local\Temp\pip-pip-egg-info-00os3tdp' cwd: C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\ Complete output (15 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\setuptools\__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\setuptools\extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\setuptools\dist.py", line 7, in <module> from setuptools.command.install import install File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\setuptools\command\__init__.py", line 8, in <module> from setuptools.command import install_scripts File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\setuptools\command\install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "C:\Users\Luca Dieling\AppData\Local\Temp\pip-install-k757dx1_\distribute_c11e8be23eda49c7809d38d8e88b222e\pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I am running the command pip install django-observer Thank you for your help -
django-allauth: letting user complete all steps for signing up but prevent login
Is it possible to configure django-allauth such that a user can proceed to verify emails after signing up, but not log in until I manually enable the account in the Admin site? Background: I will be releasing an app on the Internet but I don't want everyone to start using it. I want to manage the number of users logging in just in case my website is crashed. The server is hosted on AWS. I'm not sure if this is a good strategy. Should I start autoload balancing from day 1? Possible duplicates: Django Allauth Signup Prevent Login Conflicting answers - one is saying I don't need to extend the SignUp view and another has the extension. prevent user login after registration using django-allauth The answer is for cases where email verification is not needed. -
Django crispy forms isn't loading css
When I try to display a form with {{ form | crispy }} it shows the form, but without any css. I haven't been able to find any tutorials or questions that explain how to fix the problem. my form + view: from django import forms from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User CARRIER_CHOICES =( ('@txt.freedommobile.ca', 'Freedom Mobile'), ('@txt.luckymobile.ca', 'Lucky Mobile'), ('none', 'None'), ) class RegisterForm (forms.Form): username = forms.CharField() password = forms.CharField() check_password = forms.CharField() email = forms.EmailField() phone = forms.CharField(required=False) carrier = forms.ChoiceField(choices=CARRIER_CHOICES, required=False) def register (request): form_error = 'none' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] check_password = form.cleaned_data['check_password'] phone = form.cleaned_data['phone'] carrier = form.cleaned_data['carrier'] phone = str(phone) if password == check_password: email = phone + carrier user = User.objects.create_user(username, email, password) user.is_staff = False user.is_active = True user.is_superuser = False return redirect ("/register/success") else: form = RegisterForm(request.POST) return render (request, 'register.html', {'form':form}) my html: {% load crispy_forms_tags %} <form method="post" class="bootstrap4"> {% csrf_token %} {{ form | crispy }} <button type="submit" class="btn btn-success">Submit</button> </form> The form does not load the css, and it looks like this: https://ibb.co/BjHGCcP How come it is not … -
How to get rid of whitespaces in pdfkit with wkhtmltopdf
In a django project i am trying to export data in PDF on click of a button, am using pdfkit and am turning html to pdf with WKHTMLTOPDF, everything works very nicely but am getting white spaces in middle of the generated PDF. My Html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE-edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Email Template</title> <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;1,700&display=swap" rel="stylesheet"> <style type="text/css"> * { box-sizing: border-box; } body { margin: 0; padding: 0; font-family: 'Montserrat', sans-serif !important; color: #fff; font-size: 15px; line-height: 25px; font-weight: 400; } p, h1,h2,h3,h4,h5{ font-family: 'Montserrat', sans-serif !important; } table { border-spacing: 0 } td { padding: 0; } tr { vertical-align: top; } img { border: 0; max-width: 100%; } a:hover{ color: #fd7960 !important; } @media screen and (max-width: 599px) { } @media screen and (max-width: 400px) { } * { page-break-inside: avoid; } tr { page-break-inside: avoid; } </style> </head> <body style="min-height: 100vh;height: 100%;"> <center class="_wrapper" style="width:100%;table-layout: fixed;background-color: transparent;"> <div class="_ebody" style="margin: 0 auto;"> <!-- table begin --> <table class="_tableOutter" align="center" width="100%" style="margin: 0 auto;"> <tr> <td style="text-align: center;padding: 35px 15px 25px;color: #fff;"> <table width="100%" style="border-spacing: 0;padding: 0 15px 15px;"> {% for value in … -
how to use JQuery Vector Map and Django
i am trying to visualize my django model data of six columns on a jqueryVector Map and i dont know how to do that. i need an answer as soon as possible. $(function() { $('#map').vectorMap({ map: 'world_mill_en', series: { regions: [{ values: gdpData, scale: ['#C8EEFF', '#0071A4'], normalizeFunction: 'polynomial' }] }, backgroundColor: '#eef3f7', onLabelShow: function(e, el, code) { el.html(el.html() + ' (GDP - ' + gdpData[code] + ')'); } }); }); -
Django error with models (ManyToManyField)
I was building my app using django but I got this error in the models.py file: creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE) NameError: name 'Teacher' is not defined This is my current code in models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class School(models.Model): nombre = models.CharField(max_length=355) profesoras = models.ManyToManyField(Teacher) class Teacher(models.Model): user = models.ForeignKey(User, related_name="teacherClass", blank=False) school = models.ManyToManyField(School, blank=True) class Post(models.Model): creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE) title = models.CharField(max_length=255) text = models.TextField(max_length=2000) Do you know how can I solve this error? -
Django UserPassesTestMixin confusion/questions?
I am currently working on an admin dashboard, which include specific views for company administrators only which are labeled as Business users. The app is going to have about 10 views, and I had a few questions in regards to the UserPassesTestMixin Basically, all of my views would include this, def test_func(self): return self.request.user.user_type == 'Business' To make sure the users are Business users I am protecting the views that way. A couple questions that I am having trouble solving on my own are: Now with that being repeated say 10 times, is there a cleaner way to do this, rather than having def test_func in every CBV? The other question that comes up, if the user doesn't pass test, it redirects to the login page, which I don't really like either. These views are all returning json. If the user does not pass test, I would like to just send them to something like, JsonResponse({'message': 'Only company administrators have access to this view'}) How would I able to change that redirect only if the user does not pass test? Keeping in mind that these views also inherit from LoginRequiredMixin as well, in which if the user is not logged … -
Calculate and save the total of an invoice in django
When i add an invoice, the Total is always 0 but when i update without any changes, it s updated with the totalsubtotals(). i understand that there are many calculations and in my case, the total calculation is done before the subtotals. Any recommandations. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total = models.DecimalField(default=0, max_digits=20, decimal_places=2) def totalsubtotals(self): items = self.invoiceitem_set.all() total = 0 for item in items: total += item.subtotal return total def save(self, *args, **kwargs): self.total = self.totalsubtotals() super(Invoice, self).save(*args, **kwargs) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) subtotal = models.DecimalField(default=0, max_digits=20, decimal_places=2) def save(self, *args, **kwargs): self.subtotal = self.price * self.quantity super(InvoiceItem, self).save(*args, **kwargs) -
Django | Serve two uploaded images version - WebP and JPEG
I just want to ask you for a best practice, how to serve both WebP and JPEG images via Django to users. I have a website about vehicles - there are about 1 000 vehicles added every day and every vehicle has about 10 images. That is a lot of images. I have made a custom "import django-admin command", which parse a vehicle: It downloads a JPEG image from the source (10 images for a single vehicle) Then for all downloaded images a watermark is applied After that, this image is converted to WebP format and uploaded via Django save() to Images table, which has a ForeignKey to a Vehicle (I am using ImageField for that) Then it compresses original JPEG images and via shutil.move these compressed JPEG images are moved to the same folder, where WebP image formats are stored. Because I am using an AMP HTML, I can simply do a fallback from WebP to JPEG for browsers, which has no WebP support. And because images are in the same /media/.../ folder, it works perfectly. But today I have found, that this method is not perfect. When there are the same image names, Django in save() method get_random_string() … -
How to write a shell command in the Procfile to copy a database from production to staging on Heroku?
I wanted to use Procfile in a Django project to copy the database we use in production to the staging environment on Heroku. This would then be done any time there is a deployment on staging. I could not find relevant information however. Using the Heroku CLI, it is pretty straightforward as the below suffice: heroku pg:copy your-app::DATABASE_URL DATABASE_URL -a yourapp-staging The way I would like to use it is via proper use of curl and the Heroku API. So far, the .sh file I use in the Procfile is like this : echo "Beginning workflow specific to STAGING" echo "Turning off the web dynos."; curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \ -d "{\"maintenance\": true }" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3" \ -H "Authorization: Bearer $HEROKU_API_KEY" echo "Copying from production database to staging database ..."; """MISSING CODE HERE""" echo "Turning the staging server back on."; curl -X PATCH https://api.heroku.com/apps/${app_name_or_id} \ -d "{\"maintenance\": false }" \ -H "Content-Type: application/json" \ -H "Accept: application/vnd.heroku+json; version=3" \ -H "Authorization: Bearer $HEROKU_API_KEY" Would anyone know how to do it, please? -
Django: admin interface: how to change user password
In Django: I have created a super user and can view all the users I have also implemented forgot password for my user, who can input their email and a password reset link is sent to their email and then the user can reset his password But how can admin change some users password from the admin dashboard -
Which Django model relationship is appropriate?
Let's say I create a Profile extending the Django User Model, each time a new user is created. And I want to store multiple items in a field, for example, 10 track names in the track name field for a particular user, in the Profile(will differ from user to user). Which model relationship can help achieve this? Or do I create a new model for songs, named preferably "songs", and use a model relationship to Profile? What is the best way to do this? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) track_name = models.CharField(on_delete= models.CASCADE , related_name="track") artiste_name= models.CharField(on_delete=models.CASCADE , related_name="artiste") album_name = models.CharField(on_delete= models.CASCADE, related_name= "album") class Meta: db_table = "Profile" def __str__(self): return self.track_name -
List only three element n my homepage in django/python
{% for post in BusinessPost %} <li>{{ post.title}} -- {{post.author}} -- {{post.source_date}} </li> {% endfor %} this is my code to get all the element of my model into listView page but i only wat to get the first 3 element of this list. Can anyone help -
Data transfer from one HTML page to another
When creating a technical site, I faced the need to transfer data and save it in a file. I am making a website in Django. In models I create input data. I receive these data in HTML and, if necessary, the user changes them and JS performs the necessary calculations, the results of which are sent to the same page. It is possible to do a lot of analytical work on outgoing data (build graphs, calculate a loan, calculate various project risks). I prefer to create several pages so as not to fill one. All pages have already been built. There was a problem of this nature: On the main page, JS did his job but I do not know how to access this data on other pages. Is there a solution to write a JSON string to a file or send them to Django model (update static data). I read a lot and looked for solutions, but I could not figure it out until the end. Maybe someone knows the solution. Thank you in advance. If need more information, please let me know. This is my first request for help, so please don’t be strict if I cannot ask … -
Django dynamic filtered ListView returning error: get() got multiple values for argument 'self'
I need some help trouble shooting this. I think I'm doing what is suggested by the django docs (https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/), but I keep getting this error: get() got multiple values for argument 'self' textbook_list.html <a href="{% url 'lesson_list' textbook.pk %}"> <button type="button" class="btn btn-info">More Info</button> </a> urls.py urlpatterns = [path('grade/<int:pk>/', TextbookLessonList.as_view(), name='lesson_list')] views.py class TextbookLessonList(ListView): template_name = 'textbook_lesson_list.html' def get_queryset(self): self.textbook = get_object_or_404(Textbook, self=self.kwargs['pk']) #This is the offending line return TextbookLesson.objects.filter(textbook.pk==self.textbook) -
Django Template Condition with css
my Question is: I want do a condition in Django Template with css but it didnt work. <label>{% if not typ.required %} {% trans 'Bitte Auswahl treffen' %}{% endif %}</label> <input type="checkbox" {% if typ.required %} style="display:none;" checked="checked" {% endif %} name="checkbox" data-toggle="toggle" id="{{ typ.typ_id }}" value="{{ cookie_id }}" /> {% if typ.required %} style="display:none;" checked="checked"{% endif %} checked="checked" works but the Style not. If i press f12 to watch the site i see this style in the input type Thank you guys -
Django returning form error but the input seems to be valid
One of my models is a Product model which has 3 different price fields, so that one of its prices can be chosen when creating an order. I created a select input in one of my forms to allow the user to choose one of the prices, but when the form is submitted, Django returns an error telling me to introduce a valid number, even though I checked the request.POST and the value it's sending is a valid number. models.py: class Product(models.Model): ... price_1 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_2 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles price_3 = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0) # Separador de miles forms.py: class CartAddProductForm(forms.Form): price = forms.DecimalField() quantity = forms.IntegerField( label ='Amount' ) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], price=cd['price'], override_quantity=cd['override']) return redirect('cart:cart_detail') Template: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_price">Precio</label> <select name="price" id="id_price" class="select2 form-control" data-toggle="select2" required> <option value="{{ product.price_1 }}" selected>Precio retail: ${{ product.price_1|intcomma }}</option> {% if product.price_2 %} <option value="{{ product.price_2 }}">Precio mayorista: ${{ …