Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use templates to display fields from two tables (using FK)
In my template, I would like to show 'challenges' grouped by 'category' e.g. Category 1 Challenge 1 Challenge 2 Category 2 Challenge 3 Challenge 4 Here is my models.py: class Category(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=400) class Challenge(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) answer_text = models.CharField(max_length=200) In my template file I want to do something like this: {% for category in category_list %} {{ category.title }} <ul> {% for challenge in Challenge.objects.get(category_id=category.id) %} <li>{{ challenge.question_text }}</li> {% endfor %} </ul> {% endfor %} But I understand you cannot call functions in templates. How else can I display data from two sets in a relationship? -
All access attempts share the same IP Address Django-Axes
I'm having an issue where all access logs/attempts recorded to the server via the Django-axes module are under the same IP address. These two logs seen below were made under two different IP addresses, yet they are recorded as if they are the same. Any ideas on what could be causing this issue? Documentation if necessary: https://django-axes.readthedocs.io/en/latest/ -
Accessing different domain via jQuery $ajax()?
How do you let jQuery access a different domain via its $ajax() method? I have a Django site running at https://example.com:4567/somepage and I want a page to access an Flask-based API running on https://example.com:5678/path/to/rest/api. The only difference in the domain is the port. However, the browser is giving me the error: Access to XMLHttpRequest at 'https://example.com:5678/path/to/rest/api' from origin 'https://example.com:4567' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Some similar questions recommended adding these CORS headers to the $ajax() call like: $.ajax({ url: '//example.com:5678/path/to/rest/api', headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type':'application/json' }, dataType: 'jsonp', success: function(data, textStatus, jqXHR){ do_stuff } }); but this doesn't seem to have any effect. What else do I need to do to allow Javascript on my page to access a different domain? -
Render html-content from remote html-file (AWS bucket) into django-template
I am running a django app and I am building a newsletter. I have a newsletter-model that has a file-field where I attach a html-document (which is the content of the newsletter). This file gets automatically uploaded to an AWS bucket. I also want to display the newsletter on my website. So I am trying to find a solution how I could render the HTML-content from the HTML-file as my django-template. My model: class Newsletter(models.Model): subject = models.CharField(max_length=150) content = models.TextField(null=True, blank=True) attachment = models.FileField(null=True, blank=True, storage=MediaStoragePrivate()) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I tried various things: I tried getting the attachments content, saving it into a variable and rendering it to the template def list_newsletter(request): newsletter = Newsletter.objects.last() attachment = self.attachment.read().decode("utf-8") return render( request, "newsletter_list.html", {"newsletter": attachment} ) This gives me the text but with the html-tags included (<h1> ladadilada </h1>), but I want the interpreted html not raw text. I tried this with beautiful soup htmltxt = Newsletter.objects.last().attachment soup = BeautifulSoup(htmltxt, 'html.parser') But also this prints the html-tags. I can print it with .text, but this does not interpret the html-tages but just prints raw text. Tried rendering the URL but it gives me the URL. Is it … -
Heroku Django SendGrid sends email on development server but doesnt send emails in production
I am struggling to find the issue with my current password_reset functionality in my Django app in production settings. In my development settings, reset password emails are successfully sent by SendGrid to Gmail accounts. However, when it comes to sending them to Gmail accounts on my production the password_reset email is not being sent successfully. I do not know why this is happening as when I use the send_mail in the Heroku python shell the emails are sent to Gmail successfully, and this issue only seems to be for Gmail users. I have tested this with @hotmail.com accounts and it seems to run smoothly. My website email is on Microsoftoutlook but again on development, the emails are sent successfully but on Heroku they aren't. I was wondering why is this happening as I cannot find this issue anywhere? Or am I just better off switching to mailgun? -
Getting two database models to show on one html page
Currently working on a web page and I want to show two different tables of information one is for individual foods and the other is for recipes, however when I can only get the first class to pull up any information I've tested to see if the first class can pull up the recipe database and it, in fact, currently out of ideas on what to try next. class SearchFoodResultsView(ListView): model = Food template_name = 'nutrihacker/search.html' context_object_name = 'food_list' # overrides ListView get_queryset to find names containing search term and pass them to template def get_queryset(self): query = self.request.GET.get('term') if (query == None): return Food.objects.all() else: # If there are any foods containing the query, they will be in the resulting object_list which is used by search.html in a for loop food_list = Food.objects.filter( Q(name__icontains = query) ) return food_list class SearchRecipeResultsView(ListView): model = RecipePreset template_name = 'nutrihacker/search.html' context_object_name = 'recipe_list' # overrides ListView get_queryset to find names containing search term and pass them to template def get_queryset(self): query = self.request.GET.get('term') if (query == None): return RecipePreset.objects.all() else: # If there are any recipes containing the query, they will be in the resulting object_list which is used by search.html in … -
ERR_ABORTED 404 (Not Found) error in VueJS
I deployed a Django+VueJS application to a Digital Ocean droplet using Nginx, the Django app is working but i can't see the VueJS components loaded by Webpack (i'm using Django-Webpack-Loader). In my console, i keep seing these errors: GET http://MYURL/static/vue/js/stopwatch.js net::ERR_ABORTED 404 (Not Found) GET http://MYURL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found) Which means that the static folder was not found. I made sure to use npm run build and manage.py collectstatic and i can see that the static folder is there, even though the app doesn't see it. Here is the path: django-vue-mpa |-vue_frontend |-django_vue_mpa |-static The full code of the application is here (i just cloned that repository and tried to deploy it). Here is my vue.config.js (i think the problem might be here): const BundleTracker = require("webpack-bundle-tracker"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const pages = { "stopwatch": { entry: "./src/stopwatch.js", chunks: ["chunk-moment", "chunk-vendors"], }, "index": { entry: "./src/index.js", chunks: ["chunk-vendors"], }, 'vue_app_01': { entry: './src/main.js', chunks: ['chunk-vendors'] }, 'vue_app_02': { entry: './src/newhampshir.js', chunks: ['chunk-vendors'] }, } module.exports = { pages: pages, filenameHashing: false, productionSourceMap: false, publicPath: process.env.NODE_ENV === 'production' ? '/static/vue' : 'http://localhost:8080/', outputDir: '/django-vue-mpa/django_vue_mpa/static/vue/', chainWebpack: config => { config.optimization .splitChunks({ cacheGroups: { moment: { test: /[\\/]node_modules[\\/]moment/, name: "chunk-moment", chunks: … -
uwsgi can't be installed
i'm stuck trying to install uWSGI for the purpose of deploying my django application using pip install uwsgi, but encounter this error : enter image description here i've found several answers that unfortunately didn't work for me, like update dev tool ,install cywin or modify uwsgiconfig.py (wich does'nt exist since it's not installed ), or maybe i'm missing something. Thanks a lot for your help. -
how to add placeholder to modelform fields with over-riding form
I am trying to add placeholder to the fields of a modelform. I found this answer very insightful and used the method of the second answer: How to add a placeholder attribute in Django Form however, I want to improve the code snippet but I have some problems. First showing my code: class SampleModelForm(ModelForm): field_attrs = { 'email': {'placeholder': 'email placeholder', }, 'first_name': {'placeholder': 'first_name placeholder', }, 'middle_name': {'placeholder': 'middle_name placeholder', }, 'last_name': {'placeholder': 'last_name placeholder', } } class Meta: model = SampleModelForm fields = [K for K in self.field_attrs.keys()] def __init__(self, *args, **kwargs): super(ConsultantAddStudentAccountForm, self).__init__(*args, **kwargs) for k, v in self.field_attrs.items(): self.fields['k'].widget.attrs['placeholder'] = v['placeholder'] I have two problems: I cannot do this: fields = [K for K in self.field_attrs.keys()] I cannot do this: for k, v in self.field_attrs.items(): self.fields['k'].widget.attrs['placeholder'] = v['placeholder'] Please let me know how I can do what I am trying to achieve. Thank you -
How to use "for" statement in Django template
Here is Django template code. I tried to put out images to template. amount of image put out to template is depending on {{object.image_amount}} However since {{object.image_amount}} is an integer I can not iterate like this {% for i in object.image_amount %} So I tried this but does not work as well. {% for i in range object.image_amount %} What should I do? -
Cannot find Chrome binary when using selenium and Django on server
I used selenium with Django in local machine.All thing was good. Then, I want to deploy project on server. When I run page that selenium work on that, I got this error: WebDriverException at /panel/data/page Message: unknown error: cannot find Chrome binary I placed chromedriver on my project directory and get full path to executable_path. Also I set options with --headless for that. These are my codes: from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless") self.driver = webdriver.Chrome(executable_path='/full/path/to/chromedriver', chrome_options=chrome_options) How can I fix that? Also I have another question: Is it best practice and safe way(security) to use chromedriver on server? -
Adding new posts in production in React
I want to deploy react application, but the problem is I want to make like a blog application, where I can add new posts daily. I can make something like this using React combined with Django-rest-framework, but It's tricky for me to deploy the server also. Can I somehow deploy react application which will get the posts data from a rented server, or from somewhere on the Internet? -
staticfiles at django + nginx + gunicorn + vps
I have django project. I can't deploy it on vps. staticfiles not load... in Google Chrome Console panel: Status code at "Network": 403 Forbidden to my staticfiles /etc/nginx/sites-enabled/default server { listen 80; server_name <site_domain>; access_log /var/log/nginx/example.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/code/3p_site_new/; } location /media/ { root /root/code/3p_site_new/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } /root/code/3p_site_new/gunicorn_config.py command = '/root/code/3p_site_new' pythonpath = '/root/code/3p_site_new/3p_site_new' bind = '127.0.0.1:8001' workers = 3 user = 'root' limit_request_fields = 32000 limit_request_field_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=Site.settings' I am trying to start project with gunicorn -c "/root/code/3p_site_new/gunicorn_config.py" Site.wsgi tree: /root/code/3p_site_new/* |-- Main | |-- __init__.py | |-- admin.py | |-- apps.py | |-- creds.json | |-- forms.py | |-- migrations | | |-- <files> | |-- models.py | |-- my_config.py | |-- static | | |-- css | | | |-- <files> | | |-- js | | | |-- <files> | | `-- media | | `-- img | | |-- <files> | |-- templates | | |-- <files> | |-- tests.py | |-- urls.py | `-- views.py |-- Site | |-- __init__.py | |-- settings.py | |-- … -
Django: Verify email before creating a user
I have a Django project. I would like to verify email before creating a user account. What's the best way to do so? I decided to create an independent model first but I'm confused now. I decided not to use allauth model because it's too complex. Instead, I'm generating a random number and sending it over email. Once the activation code is confirmed, a user should type a password. After obtaining a verified email and password, I need to create a User model. Email will be used as a username. EmailVerifyModel class EmailVerifyModel(models.Model): email = models.EmailField(help_text=_('A valid email address please')) isVerified = models.BooleanField(default=False) activation_code = models.IntegerField(blank=True) EmailVerifyForm class EmailVerifyForm(forms.ModelForm): email = forms.EmailField(widget = forms.TextInput(attrs={ "type": "email", "name": "email", "id": "email", "placeholder": _("Email"), "class": "form-control form-control-md", "required": "" }), label = "") class Meta: model = EmailVerifyModel fields = ('email', 'activation_code') widgets = { 'activation_code': NumberInput(attrs={'class': 'form-control','placeholder': 'Verification code'}), } View def signup_view(request): form = EmailVerifyForm(request.POST or None) email_verified = False if form.is_valid(): new_email = form.save(commit=False) pin = randint(1000,9999) new_email.activation_code = pin new_email.save() cd = form.cleaned_data if not cd['activation_code']: current_site = get_current_site(request) subject = _('Verify Your Email') email_body = render_to_string('email/verify-email.html', { 'domain': current_site.domain, 'token': pin, }) msg = EmailMessage(subject, email_body, 'no-reply@test.com', … -
django template slow rendering
my sql querset : 109 queryset in 20.3ms but the total time rendering is 3 seconds {% for fooo in degray %} {% for foo in data %} {% for foor in data_list %} {% if fooo.id|cut:" " == foo.withdegrey_id|cut:" " and fooo|cut:" " == foor.name|cut:" " %} <tr> <td colspan="1" >{{ foo.percontage }} %</td> <td colspan="1" > {{ foo.date }} </td> <td colspan="1" >{{ foo.nomberhodor }}</td> <td colspan="1" >{{ foo.nomberesteda }}</td> <td colspan="1">{{ foor.nomberetud__sum }}</td> <td colspan="1">{{ foor.name }}</td> </tr> {% endif %} {% endfor %} {% endfor %} {% endfor %} is useing a lot loop in template with condition make rendering slow ?? -
UUID vs Hash Field django
I want to make my primary key look like unrecognized and I found these two solutions. which one is best and why ? refrences : hash : https://pypi.org/project/django-hashid-field/ UUID :https://www.geeksforgeeks.org/uuidfield-django-models/ -
Beginner problem. How i can display all images from a product? Django + Python
I'm a beginner and i need a little help. I want to display all images from a product and i can't find the right way. the code is below: models.py: class Product(models.Model): name = models.CharField(max_length=200) short_description = models.CharField( max_length=200, null=True, blank=True, help_text="Enter a brief description of the product") description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) default_image = models.ImageField(null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('product-detail', args=[str(self.id)]) @property def imageURL(self): try: url = self.default_image.url except: url = '' return url def image_tag(self): return mark_safe('<img src="{}" height="50"/>'.format(self.default_image.url)) image_tag.short_description = 'Image' class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, default=None, related_name='images') title = models.CharField(max_length=50, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.product.name this is the view: class ProductDetail(DetailView): model = Product URL: path('product/<int:pk>', views.ProductDetail.as_view(), name='product-detail'), and template product_detail.html: {% extends 'store/home.html' %} {% load static %} {% block content %} <div> <h1>{{ product.name }}</h1> <p>{{ product.description }}</p> <!--<img src="{{product.imageURL}}" alt=""> --> </div> {% endblock %} The comment is returning only the default image. The indentation is correct in my VS Code but here is pretty hard to write it. Any suggestions would be greatly appreciated. Thank you. -
How to arrange the settings.STATIC_ROOT to point towards the correct path?
I am trying to add CSS styling to my html email to be sent so I used django-inlinecss 0.3.0 In my template I am using the following: {% load inlinecss %} {% inlinecss "/css/bootstrap.css'" %} TEXT {% endinlinecss %} After debugging I found that the reason is due to [Errno 2] No such file or directory: 'C:\\Users\\User\\Desktop\\static_root\\css\\bootstrap.css' Here is the files structure: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') So, how should I fix this error? -
why doesn't the save () command in django work?
please help me solve the problem. I study the Django framework at the course https: //webformyself.com/djang ... ign = django, everything went fine until I got to Part 1, Lesson 9. When trying to save records to the database via the news1.save () variable, an error occurs: news1.save () Traceback (most recent call last): File "D: \ django-sites \ testsite \ venv \ lib \ site-packages \ django \ db \ backends \ utils.py", line 84, in _execute return self.cursor.execute (sql, params) File "D: \ django-sites \ testsite \ venv \ lib \ site-packages \ django \ db \ backends \ sqlite3 \ base.py", line 413, in exec ute return Database.Cursor.execute (self, query, params) sqlite3.OperationalError: table news_news has no column named updated_at The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "D: \ django-sites \ testsite \ venv \ lib \ site-packages \ django \ db \ models \ base.py", line 753, in save self.save_base (using = using, force_insert = force_insert, File "D: \ django-sites \ testsite \ venv \ lib \ site-packages \ django \ db \ models \ base.py", line 790, in save_base updated = … -
What does the @ symbol mean in a Django URL?
In urls.py there is a line: path('profile/view/@<username>/', main.views.foo.profile, name='fooprofile'), What does the @ mean in @<username> ? Where can I find this in the Django documentation? -
invalid literal for int() with base 10: 'Moniczka' occured when I tried to register new user in REST API
I created registration API view using Django REST API and when I tried to use endpoint, after POST I could have seen the error: invalid literal for int() with base 10: 'Moniczka'. I've checked RegisterSerializer, RegisterAPI view and url and I can't see any mistakes. Mayby some of you can help me. Here is my serializer class: class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User(validated_data['username'], validated_data['email'], validated_data['password']) return user Here is my views.py: # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) And finally urls.py: urlpatterns = [ path('register/', RegisterAPI.as_view(), name='register'), ] I hope that one of you could help me :( -
how to get username as initial value on forms in django
I would like to get initial value on the following form but i get error : name 'user' is not defined. I don't know how to get user.username. class InvoiceForm(ModelForm): date = forms.DateField(widget=DateInput) user = forms.CharField(initial={"username": user.username}) class Meta: model = Invoice fields = "__all__" and the view to create the invoice is : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self, request): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet() products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet(self.request.POST) if (form.is_valid() and formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: addmore = self.request.GET["addmore"] if addmore == "True": return redirect("update_invoice", pk=self.object.id) except Exception as e: pass return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) I would like to get initial value on the following form but i get error : name 'user' is not defined. I don't know how to get user.username. -
How do I populate my OrderItem model with fields from my Product model in Django?
I am using ModelViewSet and serializers to view my orders and products. So in my admin panel for my Product model I already added product, price, and price per pound. So eg. (banana, 2.00, 2.99). class Product(models.Model): name = models.CharField(max_length=70) price = models.DecimalField(max_digits=10, decimal_places=2) price_per_pound = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) category = models.ForeignKey(Categories, related_name='products', on_delete=models.CASCADE) def __str__(self): return self.name In my OrderItem model I can select the product that is available, but when I select the banana I want the price and price_per_pound fields to auto populate with what I have in my Product model eg.(2.00, 2.99). How would I go about this? class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='+', on_delete=models.CASCADE) price = models.DecimalField(Product.price) //Tried this way, but doesn't work. price_per_pound = models.ForeignKey(Product, related_name='product_price_per_pound', on_delete=models.CASCADE) //this still only give me the field names of my product quantity = models.PositiveIntegerField(default=1) ready = 1 on_its_way = 2 delivered = 3 STATUS_CHOICES = ( (ready, 'ready'), (on_its_way, 'on its way'), (delivered, 'delivered'), ) status = models.SmallIntegerField(choices=STATUS_CHOICES) -
'Profile' object has no attribute 'save' Django error
So I created a Profile model to have a OneToOne field to the the base django "User" model and I am trying to make it so a profile model is created every time a user model is created. Basically every time someone goes through the registration process and creates a user a profile model is also created that is linked the user model that was just created. here is my Profile model in models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') bio = models.CharField(max_length=100, default="") tricks = models.ManyToManyField("Trick") here is my views.py file for the signup field: def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) profile = Profile(user=User.objects.get(username=username)) profile.save() login(request, user) return redirect("home") else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) Every time I complete the registration form to create a new user I get the error: AttributeError: 'Profile' object has no attribute 'save'. The thing that is confusing me is that if I create a profile object in the interactive shell Django provides It allows me to save it with the same exact 'save()' command so why is it throwing an error here, and … -
Facing issue with BASE_DIR in Django
I am working with Django. Facing issue while using BASE_DIR because earlier this was like - BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) and now after the update - - BASE_DIR = Path(__file__).resolve().parent.parent Can someone help as I am using static files in my project as below - STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static', STAICFILES_DIRS = [ BASE_DIR, 'ecom/static', ] earlier than this I was using BASES_DIR as - STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STAICFILES_DIRS = [ os.path.join(BASE_DIR, 'ecom/static'), ]