Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can I get screen resolution request in django?
I wanna change some of the following line based on the resolution of the screen(device): {% if forloop.counter|divisibleby:3 and not forloop.last %} no javascript, just django. so getting the "screen.width" in the view.py for example, would be helpful. -
Django, how to calculate the total of each line
I would like to calculate 'total' for each line. with the following code, it shows only last line total, not each line total. this in case we have many products in this invoice. need total of each product (price*quantity) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) def total(self): items = self.invoiceitem_set.all() for item in items: amount_due = (item.price * item.quantity) return round(amount_due, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) HTML {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{object.total}}</td> </tr> -
How to solve this modelForm Django error?
I'm trying to follow this tutorial about Django on youtube, and I'm writting exactly the same way the teacher writes on the video, but my code is throwing errors that I can't identify. I've already made some search about it, I've made all the imports apparently correctly and I really don't know where to look. My code: from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User # When form.save() runs, its going to be saved on the User model fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(Modelform): class Meta: model = Profile fields = ['image'] It returns the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File "/home/isaacrpl7/.local/lib/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File … -
PyChram Django project Interpreter not adding up
My Django projects started showing the error bash-3.2$ python manage.py runserver File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax After googling and trying different approaches, I reinstall PyCharm. Now When I open an old project that was working. the Interpreter shows an old script file name instead of project Venv. I tried to edit and add the interpreter. If I choose to add new, it says the folder is not empty. If I try to create new, it shows total empty. -
Django : object.filter().value_list() problem
I am trying to render data related to a model attribute which is inputed in the frontend by the user in a django view. Unfortunately, I keep running in the same problem here is my view: @method_decorator(login_required, name='dispatch') class SupplierPage(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) context = {} #if query and request.method == 'GET': Supplier = supplier.objects.filter(supplier = query) supplier_items = Item.objects.filter(fournisseur = query) queryset = Item.objects.filter(fournisseur = query) table = SupplierData(queryset) labels = Item.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(labels) default_items = Item.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] print(default_items) label1s = Item.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] default_item1s = Item.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] context.update({'Supplier' : Supplier, 'supplier_items' : supplier_items, 'table': table, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) return render(request, 'Supplier.html',context) now in my log, I get this: DEBUG (0.001) SELECT "dashboard_item"."reference", "dashboard_item"."fournisseur", "dashboard_item"."demand_30_jours", "dashboard_item"."stock_reel", "dashboard_item"."en_cours_de_reception", "dashboard_$ DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."reference" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."number_of_sales" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG (0.001) SELECT "dashboard_item"."reference" FROM "dashboard_item" WHERE "dashboard_item"."fournisseur" IS NULL LIMIT 10; args=() DEBUG (0.001) SET search_path = 'pierre','public'; args=None DEBUG … -
Django Axios GET Request not allowed
I'm trying to make a simple, unauthorized request from axios to Django, but it's not working, with result "501 unauthorized". The thing is, this request doesn't require that user is signed in, so I don't know exactly what's the error. my django view: @api_view() @renderer_classes([JSONRenderer]) def main_enterprise_name(request): return Response({'name': Enterprise.objects.get(main_instance=True).name}) The Django URL: path('api/enterprise/main/', views.main_enterprise_name, name='main_name'), Axios config: axios.defaults.xsrfCookieName = "attcsrf" axios.defaults.xsrfHeaderName = "X-CSRFATTTOKEN" const api = axios.create({ baseURL: "http://127.0.0.1:8000", }); api.interceptors.request.use(function (config) { const token = getToken(); if (token){ config.headers.Authorization = 'Bearer '.concat(String(token)); } return config; }); When I make this request in browser, it works just fine, but with axios this fails with unauthorized. -
How can I add a tag <a href=""> to a send email using django and mailgun? [closed]
Using django and mailgun, my email its ok, but the link in my html when it send doesn't look like I need (I mean just to click on a word and redirect to the link), in the email just see the word without a link when you hover it. I don't know what else I can do for this. I have this: def send_confirmation_email(self, user): """ Send account verification link to the created user """ verification_token = self.generate_token(user) subject = 'Confirm your account to make some swaps' from_email = 'ssss <noreply@ssss.com>' html_body = render_to_string( 'verify_account.html', { 'token': verification_token, 'user': user } ) mail = EmailMultiAlternatives(subject, html_body, from_email, [user.email]) mail.attach_alternative(html_body, "text/html") mail.send() and my html: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>Welcome {{ user.username }}</p> <p> Before you start using this app we need you to do one last thing. Please visit the following <a href="localhost:8000/verify/{{ token }}">link</a> </p> </p> </body> </html> Thanks a lot. -
Properly escaping strings in raw Django SQL query
Really the root of the problem is poor database design going back to long before I started here, but that problem isn't going to be resolved by the end of the day or even the end of the week. Thus, I need to find a better way to handle the following to get a feature added. I'm forced to deviate away from the Django ORM because I need to build a raw SQL query due to having to write logic around the FROM <table>. We've elected to go this route instead of updating the models.py a couple times a year with the new tables that are added. There are numerous areas starting here where the Django documentation says "Do not use string formatting on raw queries or quote placeholders in your SQL strings!" If I write the query like this: cursor.execute(""" SELECT * \ FROM agg_data_%s \ WHERE dataview = %s \ ORDER BY sortorder """, [tbl, data_view]) It adds single quotes around tbl, which obviously causes an issue, but will correctly construct the WHERE clause surrounded in single quotes. Doing this, will not put single quotes around tbl, but will force you to put single quotes around the WHERE … -
Cannot pass variables to Django 3 method from HTML template
I am a Django newbie who is trying convert and existing HTML based website to Django 3. The only complex piece of this page is a call to a Django method that uses the django.core.mail package and everything works, but, I am trying to pull some data off of the HTML template and pass it to this method. The method works only it sends a blank email. I am trying to pass contact information that the end user would fill out on the form. If I hard code the data into the method it works. I have tried passing the data through urls.py, but, everything I try fails to even parse when I call the method. When I use a request.GET.get everything seems to work, just no data. I was hoping to use some similar to JQuery like the following in the method. name = str(request.GET.get('Name:', '').strip()) email = str(request.GET.get('Email:', '').strip()) msg1 = str(request.GET.get('Message:', '').strip()) with the fields being in the HTML form. I am going to include some of the relevant configuration items below. urls.py from django.urls import path from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views app_name = 'willdoit' urlpatterns … -
Is there a method to restrict going back in selected views?
I have a question, Adding or inserting an X record redirects me to another page, all good so far. But in Chrome I can go back with the <- button, which makes it difficult for me, because I can make infinite records with different clear IDs, now my question is: How not to regress in different points of view? It is good to go back, but not in the views of: insert, update or delete. There is a Javascript method for Chrome, but it didn't work very well for me. Is there a method? enter link description here I am working with Django 3.1, Python 3.8, Postgresql Your help would be greatly appreciated. -
Order elements in html Django
So I have this elements {% for chat in content %} <a class="clearfix" href="{% if chat.second == request.user %}{{ chat.first }}{% elif chat.second != request.user %}{{ chat.second }}{% endif %}"> <div class="ProfileImg" style="background-image: url({% if chat.second == request.user %}{{ chat.first.profile.avatar.url }}{% elif chat.second != request.user %}{{ chat.second.profile.avatar.url }}{% endif %})"></div> <div class="about"> <div class="name">{% if chat.second == request.user %}{{ chat.first }}{% elif chat.second != request.user %}{{ chat.second }}{% endif %}</div> <input type="hidden" class="number" value="{% if chat.second != request.user %}{{ chat.first_thread_notification }}{% elif chat.second == request.user %}{{ chat.second_thread_notification }}{% endif %}"> <div class="status"> {% if chat.second != request.user %} {% if chat.first_thread_notification >= 1 %}{{ chat.first_thread_notification }} msg sin leer <i class="fa fa-circle notification"></i>{% else %}chat activo{% endif %} {% elif chat.second == request.user %} {% if chat.second_thread_notification >= 1 %}{{ chat.second_thread_notification }} msg sin leer <i class="fa fa-circle notification"></i>{% else %}chat activo{% endif %} {% endif %} </div> </div> </a> {% endfor %} in the input class='number' val there is a value that contain a number, an especific number of each chat. what I need is to order the elements depending on the value of the number I try this but that doesnt work // order the chat values $( … -
Getting error: not enough values to unpack (expected 2, got 1)
I have a project where the user can register and then he is getting a confirmation email. The project is working fine on my local computer but after I deployed the project on pythonanywhere I am getting this error when a client tries to register:not enough values to unpack (expected 2, got 1) Also the email is not send but I can see him on the admin panel. I hope you can help. views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return redirect('/login') else: return HttpResponse('Activation link is invalid!') def confirmation_phase(request): return render(request, 'confirm_email.html') def signup(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Hesabınızı Aktifleştirin.' message = render_to_string('acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect('/confirmation_phase') else: form = RegisterForm() return render(request, 'signup.html', {'form': form}) traceback Environment: Request Method: POST Request URL: http://itucampus.pythonanywhere.com/signup/ Django Version: 3.1 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
How to make a python script run when ever I browser refresh is performed in django
I currently have a views.py file in my django application this is it def index(request): greeting = "Welcome to FireCDN" description1 = "You are not currently logged in." description2 = "Login / Signup now to enjoy the benefits of a CDN but this time free" description3 = "Hold up 🤚, you need to login in before before you can access this page" description4 = "Error occurred!" time = timezone.now() try: import httplib except: import http.client as httplib def check_internet_connection(url="www.google.com", timeout=4): connection = httplib.HTTPConnection(url, timeout=timeout) try: conn.request("HEAD", "/") conn.close() return True except Exception as e: print(e) return False connect = check_internet_connection() context = { "greeting": greeting, "description1": description1, "description2": description2, "description3": description3, "description4": description4, "time": time, "connection": connect, } return render(request, 'home/index.html', context) The thing is when I reload the browser the following template gets renders {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="description" content="This is a free alternative to CloudFare and beats the competitors out there like jsDeliv, made with ♥, by LokotamaTheMastermind"> <meta name="author" content="LokotamaTheMastermind"></meta> <meta name="application-name" content="FireCDN"> <meta name="keywords" content="cdn cloudfare firecdn fire free jsdelivr github storage online"> <link rel="icon" href="{% static 'shared/img/favicon.jfif' %}"> <title>FireCDN - {% block … -
Can't create a custom User model in django
I have a custom passwordless user model built in django 1.11. user model looks like this class User(models.Model): email = models.EmailField(primary_key=True) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' is_anonymous = False is_authenticated = True It's a custom user model and depends on a custom auth backend, given like this class PasswordlessAuthenticationBackend(): def authenticate(self, uid): try: token = Token.objects.get(uid=uid) return User.objects.get(email=token.email) except User.DoesNotExist: return User.objects.create(email=token.email) except Token.DoesNotExist: return None def get_user(self, email): try: return User.objects.get(email=email) except User.DoesNotExist: return None The auth is registered and working fine. The token is just this class Token(models.Model): email = models.EmailField() uid = models.CharField(default=uuid.uuid4, max_length=40) The problem is, when I try to call auth.login in my TestCase, it always throws this error: ValueError: The following fields do not exist in this model or are m2m fields: last_login What are m2m fields? How and where do I specify this last_login? -
forms.ValidationError bug?
this is my third day in django and I'm working on my validation form and i came across this weird bug where my validation form didn't do anything so here's the code class RegisterForm(forms.ModelForm): email = forms.EmailField(label="E-Mail", error_messages={'required': 'Please enter your name'}) class Meta: model = LowUser fields =['fullname', 'email', 'password', 'bio'] widgets = { 'password' : forms.PasswordInput() } def clean_fullname(self): data = self.cleaned_data.get("fullname") if 'ab' in data: raise forms.ValidationError('invalid') else: return data if i input "ac" to the fullname it works perfectly fine it adds the input to the database. But if i input "ab" it didn't do anything it doesn't give me any errors nor add the input to my database. And I'm pretty sure my forms.ValidationError is bugging because if i change my raise forms.ValidationError('invalid') to raise NameError('Test') like this def clean_fullname(self): data = self.cleaned_data.get("fullname") if 'ab' in data: raise NameError('Test') else: return data and i input "ab". It works completely fine and it gave me this page and I'm using django 2.1.5 if you're wondering i would appreciate any help thank you in advance -
Django: User Form not saving the data to the database
So, I'm trying to set the user's profile after they have signed up and I created this ModelForm for User Model and now I'm trying to fetch the data from the ModelForm (HTML) to my view but it's not really saving the data to my database. Although it doesn't give me any error. Here's my view: @login_required def saveprofile(request): if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) form2 = UserForm(request.POST, request.FILES) if form.is_valid(): Form = form.save(commit=False) Form.user = request.user Form.save() if form2.is_valid(): Form2 = form2.save(commit=False) Form2.user = request.user Form2.save() return redirect('usersfeed') Here's my HTML form: <form action="/saveprofile/" method="post" enctype="multipart/form-data" style="transform: translate(60%,200%);"> {% csrf_token %} {{ Form.as_p }} {{ Form2.as_p }} <button type="submit">Submit</button> yaha pr username aur email nahi dikhana </form> My forms.py: from django import forms from django.contrib.auth.models import User from .models import profile class UserForm(forms.ModelForm): class Meta: model = User fields = ['username','email','first_name','last_name'] class ProfileForm(forms.ModelForm): class Meta: model = profile fields = ['desc','pfp','cover'] -
Django 3.1 can't manage to run views asynchronously
I'm running Django-3.1 (and also I've tried master 3.2 version) in asgi mode via uvicorn. But when I open the url in a couple of browser tabs I see requests to be processed sequentially. It seems like this claim from docs: Under a WSGI server, async views will run in their own, one-off event loop. is also applied to ASGI mode. Here's the code I use: # asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") application = get_asgi_application() # settings.py SECRET_KEY = "foo" ROOT_URLCONF = "urls" # urls.py import asyncio import uuid from django.http import HttpResponse from django.urls import path async def view(request): id = uuid.uuid4() print(f"{id} sleeping") await asyncio.sleep(5) print(f"{id} woke up") return HttpResponse("ok") urlpatterns = [ path("", view), ] And here's the sequential output I see: $ uvicorn asgi:application INFO: Started server process [28020] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) bb1d30bc-b05e-4412-94ad-f4507c766074 sleeping bb1d30bc-b05e-4412-94ad-f4507c766074 woke up INFO: 127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK f451d614-89dd-401d-8302-13e842040a3a sleeping f451d614-89dd-401d-8302-13e842040a3a woke up INFO: 127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK -
How to create a form that queries objects in a Model and display the query results in a new page?
I am creating a hobby website (Airbnb clone) where on the index page there is a form that accepts a city and a property type (Apartment, Office, Restaurant, etc). I am using Django as my backend. Hosted: https://directoffices.azurewebsites.net/ (May take some time to load ** No CDN config) The pages are index and listings where the index is the landing page that consists of the search form and listings that have the properties listed. I've built a form (forms.py) : class SearchPropertyForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].required = False self.fields['city'].empty_label = 'Where do you want to go?' self.fields['city'].widget.attrs.update( {'class': 'chosen-select-no-single'}) self.fields['property_type'].required = False self.fields['property_type'].empty_label = 'Any Type' self.fields['property_type'].widget.attrs.update( {'class': 'chosen-select-no-single'}) class Meta: model = Listing fields = ['city', 'property_type'] Views.py def index(request): searchForm = SearchPropertyForm() CONTEXT = { 'searchForm': searchForm } if request.method == "GET": searchForm = SearchPropertyForm(request.GET) if searchForm.is_valid(): location = searchForm.cleaned_data.get('city') property_type = searchForm.cleaned_data.get('property_type') listings = Listing.objects.filter( city=location, property_type=property_type) return render(request, 'core/listings.html', {'listings' : listings}) else: searchForm.errors.as_data() else: return render(request, 'core/index.html', CONTEXT) HTML: <form class="main-search-form" method="GET" target="/listings/"> ** CONTENTS AND FIELDS ** </form> I am not sure whether this is the correct way of doing it and once the listing page is up, the index page … -
DJANGO: Template URL to create new model with ForeingKey as parameter
Best regards!, I'm using a patter like this in Django admin templates to add new models: {% url 'admin:app_model_add' %} where app is an application and model is a model of that app, the problem is this, I have 2 models related by a ForeignKey, lets say I have: class Chapter(TimeStampedModel): title = models.CharField('Título', max_length=250) class Subchapter(TimeStampedModel): title = models.CharField('Título', max_length=250) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, verbose_name='Capítulo') So, if I go to admin's Subchapter add it shows a combobox of all existing chapters to which I can link the Subchapter being added and that's just fine, but what I need is, via URL tag show above, I want to pass a parameter through that add URL so the chapter with a given Id be selected as default and the user does not have the need to select it. Is that possible? any help will be appreciated, thanks in advance! -
how to use a javascript variable in django if statement
My code is <body> <div class="slideshow"> {% for img in image_pr %} {% if img.section == section %} <div class="slideshow_img" style="background-image:url(/static/images/project_images/{{img.name}}.jpg)"> </div> {% endif %} {% endfor %} </div> <script type="text/javascript"> function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } var section = getParameterByName('section'); </script> </body> i would like to use the variable name "section" in the if statement used in body. How can i do it? -
Custom model manager gets clobbered by prefetch_related
I have a model and a corresponding model manager: class MyModelManager(models.Manager): def get(self, **kwargs): return super().select_related('group').get(**kwargs) class MyModel(models.Model): name = models.CharField(...) group = models.ForeignKey('Group', ...) tags = models.ManyToManyField('Tag', ...) # ... others ... objects = MyModelManager() The model manager does a select_related() in the get() routine so that I always have the given foreign key field joined (I'll likely be referring to it often). When I call the get() routine, things work just as I expect: obj = models.MyModel.objects.get(pk=1) print(obj.group) # Doesn't hit the database a second time However, if I make a call to something like prefetch_related(), my custom manager gets discarded along the way: obj = models.MyModel.objects.prefetch_related('tags').get(pk=1) print(obj.group) # Hits the database a second time to get the group The reason becomes pretty clear when I print the types: x = models.MyModel.objects print(type(x)) # Yields <class 'base.models.TestCaseManager'> y = models.MyModel.objects.prefetch_related('tags') print(type(y)) # Yields <class 'django.db.models.QuerySet'> My Question Can I get chained calls to return my custom manager instance, rather than the default one? -
How to get search results in different boxes in html
I have this search engine that gets results based on a search query. I am new to html so I don't know how to manage to put the results in different result boxes and so what happens is that all of the results overlap each other. How can I put them in separate boxes? Thank you for any suggestion. This is my html: {% load static %} <!DOCTYPE html> <html> <head> <title>Ghibli Studio | People</title> <link rel="stylesheet" href="{% static 'core/species.css' %}"> </head> <body> <div class=" header"> </div> <div class="wrap"> <form action='/species' method="POST"> {% csrf_token %} <div class="search"> <input type="text" name="search" class="searchTerm" placeholder=" Type character name, gender, age, or eye color"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <button type="submit" class="searchButton"> <i class="fa fa-search" style="font-size:24px"></i> </button> </div> </form> </div> {% if species %} {% for s in species %} <div> <ul class="result"> <style> @import url('https://fonts.googleapis.com/css2?family=Dosis:wght@300&display=swap'); </style> <h4>{{s.Name}}</h4> <h5 style="color:lightslategray;"> Classification: {{s.Classification}} <br>Eye colors: {{ s.Eye_Colors }} <br>Hair colors: {{s.Hair_Colors}} </h5> </ul> {% endfor %} {% endif %} </div> </body> </html> This is my css: body { background: url(https://ak.picdn.net/shutterstock/videos/1007358814/thumb/1.jpg) no-repeat; background-size: cover; background-position: bottom; background-attachment: fixed; background-color: rgba(140, 35, 207, 0.8); } .header { background: url(https://upload.wikimedia.org/wikipedia/sco/thumb/c/ca/Studio_Ghibli_logo.svg/640px-Studio_Ghibli_logo.svg.png) no-repeat center; font-size: 14px; filter: invert(100%); width: 640px; height: 307px; … -
ValueError: Field 'id' expected a number but got 'asd'
I've looked for other questions, but they're just different errors. I've been developing a simple forum app, and now I've come to the part where I can comment on topics. But then I realized that I have been missing the ForeignKey relationship to the topic from the comment. Then, I created a new ForeignKey but as usual, it asks me to give a default value. I was just about to add Blank and Null true, but then my hands just automatically give asd as a default. Now even when I succeed in making migrations with makemigrations, I got this error when making migrate how can I make this right? -
How to prevent resend inputed data when page is refreshing(F5)/ Django
Pls, advice. How can I escape resending session data when refreshing page(F5) . Name of city is inputed and we see appropriate message. If I will refresh page(F5) that message still will be on the page. It's looks like during refreshing of the page previous data is sending from browser to our app. views.py: import requests from django.shortcuts import render, redirect from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=' err_msg = '' message = '' message_class = '' if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): new_city = form.cleaned_data['name'] existing_city_count = City.objects.filter(name=new_city).count() if existing_city_count == 0: r = requests.get(url.format(new_city)).json() if r['cod'] == 200: form.save() else: err_msg = 'City does not exist in the world!' else: err_msg = 'City already exists in the database!' if err_msg: message = err_msg message_class = 'is-danger' else: message = 'City added successfully!' message_class = 'is-success' form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city': city.name, 'temperature': int((r['main']['temp']-32)*5/9), 'description': r['weather'][0]['description'], 'icon': r['weather'][0]['icon'], } weather_data.append(city_weather) context = { 'weather_data': weather_data, 'form': form, 'message': message, 'message_class': message_class } return render(request, 'weather/weather.html', context -
Why is the bottom half of my site not showing up?
I added another div to bottom half of my site but it is not showing up. I can get it to show up in a separate web page, but not when I paste the same code to the bottom of this web page. Check out code, thanks in advance for you efforts. {% extends 'blog/navBarFooter.html' %} {% block content %} <!-- *************SHOWING UP ON WEBPAGE******************* --> <h1 class="text-center mt-3" id="blogdetailtitle">{{ blog.title }}</h1> <h5 class="text-center mt-3" id="blogdetailtitle">By: {{ blog.by }} | {{ blog.category }}</h5> <hr color="black"> <div class="col-lg-12 col-md-8"> <img id="imgLeft" src="{{ blog.pageOneImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageOne | safe }}</p> <br> <br> <hr> <img id="imgRight" src="{{ blog.pageTwoImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageTwo | safe }}</p> <br> <br> <hr> <img id="imgLeft" src="{{ blog.pageThreeImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageThree | safe }}</p> <br> <br> <hr> <img id="imgRight" src="{{ blog.pageFourImage.url }}" height=190 width=350> <p id="textLeft">{{ blog.pageFour | safe }}</p> <br><br><br><br> <hr> </div> <!-- *************NOT SHOWING UP ON WEBPAGE******************* --> {% for blog in blogs %} <div class="row"> <div class="col-lg-4 col-md-6"> <img src="{{ blog.summaryImage.url }}" height=190 width=350> <p>{{ blog.category }}</p> <a href="{% url 'pageOne' blog.id %}"> <h2>{{ blog.title }}</h2> </a> <p>{{ blog.date|date:'M d Y'|upper }}</p> <p>{{ blog.summary }}</p> </div> {% endfor …