Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render Django AuthenticationForm in Jinja2
I have installed Jinja2 for Django 2.1 and it works fine for j2 templates. I'm trying to render standard AuthenticationForm via following j2 template: <h2>Login</h2> <form method="post"> {{ csrf_input }} {{ form.as_p }} <button type="submit">Login</button> </form> Unfortunately it doesn't display the form. Just the button. Login form rendered via Jinja2 Equivalent for Django template works fine: <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> Login form rendered via Django Can you advise? -
max retries exceeded django getstream
after integrate with getstream.io with django, and few click on follow - unfollow some people i have this error: HTTPSConnectionPool(host='api.stream-io-api.com', port=443): Max retries exceeded with url: /api/v1.0/feed/timeline/1/follows/user:3/?api_key=1234567 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f78d423e828>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)) First clicks works good but after that I have this error. -
TypeError: unsupported operand type(s) for -: 'DateTimeField' and 'DateTimeField'
I have the following equation in a Django 2.1 class: import datetime class FormBacktest(forms.Form): dateStart= forms.DateTimeField(label="Date Start", widget=DateTimePickerInput() dateEnd= forms.DateTimeField(label="Date End", widget=DateTimePickerInput() timeInMin = int((dateEnd-dateStart).total_seconds()/60) I know from the documentation that the DateTimeField is a datetime.datetime instance, so this question should be overcomed. Any reccomendations? -
How to delete only one record from user instance
I created a delete function to remove a specific "goal" record from a user. The delete function currently deletes all "goal" records assoicated with a user. I would like the function to delete a specific goal record for a user depending on the html delete button that is pressed. HTML <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.0.instrument }}</p> <p class="date">{{ goals.0.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.0.goal_info }}</p> </div> <form action="{% url 'student:goal_progress' %}" method="POST"> {% csrf_token %} <div class="buttons"> <button type="submit" name="submit" class="btn white_button box_button">Delete</button> </div> </form> </div> </div> </div> <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.1.instrument }}</p> <p class="date">{{ goals.1.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.1.goal_info }}</p> </div> <form action="{% url 'student:goal_progress' %}" method="POST"> {% csrf_token %} <div class="buttons"> <button type="submit" name="submit" class="btn white_button box_button">Delete</button> </div> </form> </div> </div> </div> views.py @login_required def goal_progress(request): goals = Goal.objects.filter(user=request.user) form = GoalForm() if request.method == 'POST': form = GoalForm(request.POST) goals.user = request.user goals.delete() return redirect('/student/dashboard') else: form = GoalForm() form = GoalForm() context = {'form' : form, 'goals' : goals} return render(request, 'student/goal_progress.html', context) -
Django - Site.objects.get_current().domain returns example.com
I currently have a Django app running on Amazon EC2. I have this code inside my Django app which basically has this code if not 'request' in self.context: #In case we dont have a context current_site = Site.objects.get_current().domain ret['employer_image'] = current_site + ret['employer_image'] now Site.objects.get_current().domain is returning example.com any suggestions on why its returning example.com ? I can always hard code the url but I wanted to know why this was failing ? -
Django + Channels + Daphne + Caddy + Admin File Upload = 413 Error
I have a Django web application that is deployed, in production, with Caddy. I use Caddy as a reverse proxy pointing to daphne which is pointing to my Django app. However, when I try to upload a 5MB file to the django admin portal in production I get a 413 error. In debug mode, when I am just using Django (without caddy or daphne), I do not get this error. Anyone have any ideas? Here is my Caddyfile and related files: 0.0.0.0:2015 on startup daphne peptidedb.asgi:application & header / { -Server # be sure to plan & test before enabling # Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" Referrer-Policy "same-origin" X-XSS-Protection "1; mode=block" X-Content-Type-Options "nosniff" # customize for your app #Content-Security-Policy "connect-src 'self'; default-src 'none'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; img-src data: 'self'; object-src 'self'; style-src 'self'; script-src 'self';" X-Frame-Options "DENY" } proxy / localhost:8000 { transparent websocket except /static } limits 750000000 log / stdout "{combined}" errors stdout asgi.py import os from channels.routing import get_default_application import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "peptidedb.settings") django.setup() application = get_default_application() wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "peptidedb.settings") application = get_wsgi_application() -
Django troubles by comparing three different values from two tables
Since this code is very extensive I'm going to explain it with a smaller example. I have two classes: 1) Soldier: +-----------------------------------+ | id | code| personal_number | name | |----+-----+-----------------+------| | 1 | SAR | 1 | John | |----+-----+-----------------+------| | 2 | SAR | 2 | Matt | |----+-----+-----------------+------| | 3 | ADM | 1 |Justin| +-----------------------------------+ 2) SoldierRank: +----------------------------+ | id | rank_code| rank_name | |----+----------+------------| | 1 | ADM | admiral | |----+----------+------------| | 2 | SAR | sergeant | +----------------------------+ As you can see, SoldierRank is a reference class for Soldier class. The problem is that as you can see in table 1, it can be more than one personal_number similar to others, as long as they have a different code (Rank). For exmaple Justin and John are both personal_number 1 because Justin is 1 for admirals and John is 1 for sergeants. So I'm trying to use aggregate(max_val=Max('personal_number') but I'm having problems. The query is from a form and this form is posting rank_code but I need to get that rank current max personal_number so I'm trying something like this: soldierCode = SoldierRank.objects.get(rank_code=form.cleaned_data.get('rank_code')).rank_name This code is returning "sargeant" if the value sent was "SAR" … -
How to render full templates in a div on a page in django
So I am working on a way for users to be able to customize their webpages in django. I want the left side of the page to be the part for customizing and the right side of the page to show the webpage that is being customized. So I'm trying to figure out how to get the right div to somehow serve as a body and render the django template document, if that makes any sense. So basically I'm am trying to render a html template page within a div, or only on part of a page. What is the best way to do this? -
ImproperlyConfigured at /rango
i can't load my app in the web browser can someone please help me Environment: The included urlconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Request Method: GET Request URL: http://127.0.0.1:8000/rango Django Version: 1.8.13 Exception Type: ImproperlyConfigured Exception Value: The included urlconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Exception Location: C:\Python37-32\lib\site-packages\django\core\urlresolvers.py in url_patterns, line 410 Python Executable: C:\Python37-32\python.exe Python Version: 3.7.2 Python Path: ['C:\Users\user\Dev\tango_with_django_project', 'C:\Python37-32\python37.zip', 'C:\Python37-32\DLLs', 'C:\Python37-32\lib', 'C:\Python37-32', 'C:\Python37-32\lib\site-packages'] Server time: Tue, 5 Feb 2019 04:21:16 +0000 -
How to redirect after a POST request without breaking the back button?
I am using Django to develop a website and need some help figuring out how to redirect correctly after a POST request. Kinda new to web-dev, so any help is appreciated. My main page is index.html, which links to a page called items.html. Suppose items.html displays a long list of items, and for each item there is a button that performs an action on that item - for example, marking it as expired. The button submits the form to a view which performs the required logic and should afterwards redirect back to the items page (where the specific item will be displayed differently - perhaps marked in a certain color). The problem: When I perform the "Mark as expired" action on multiple items in a row, each form submission counts as a new page visit, and multiple back button clicks are required to get back to index.html. My items.html template: {% for registration in cancelled_registrations %} <div> <form action="/mark-as-expired/" method="post"> {% csrf_token %} <input type="hidden" name="item-pk" value="{{ item.pk }}"> <input type="submit" value="Mark as expired"> </form> </div> {% endfor %} mark_as_expired view: def mark_as_expired(request): # Performing logic here return HttpResponseRedirect('/items/') Is there a way make it so after any number of … -
No response to python3 manage.py runserver command
I have created my first django project by following a tutorial and I am trying to test it. Command python manage.py runserver returned a SyntaxError: invalid syntax. My Django version is (pip3 show django-command): Name: Django Version: 2.1.5 Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD Location: /home/.local/lib/python3.6/site-packages Requires: pytz I found a similar problem/question How to solve SyntaxError on autogenerated manage.py? and run python3 manage.py runserver command as suggested in the answers. It gave me absolutely no response. The server is not running. Terminal just skipped into new row. screenshot of the terminal Can anyone help jme run my project on the server? -
I get error from terminal when adding module to django
I've just started developing web with django but I'm trying to encode in the same way I'm following lessons from the internet I couldn't find a nuisance in the code I'm getting such an error when I want to create my own module and the visual studio code says "No module named blog" enter image description here -
django throwing errors about template having to do with links
I am a newbie with Django. I'm following the tutorial here: We just got to the part with templates. So I have a template now, base.html: {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django Boards{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> {% block breadcrumb %} {% endblock %} </ol> {% block content %} {% endblock %} </div> </body> </html> I have a homepage that extends base.html: {% extends base.html %} {% block title %}Boards{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item active">Boards</li> {% endblock %} {% block content %} <table class="table"> <thead class="thead-inverse"> <tr> <th>Board</th> <th>Posts</th> <th>Topics</th> <th>Last Post</th> </tr> </thead> <tbody> {% for board in boards %} <tr> <td> <a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a> <small class="text-muted d-block">{{ board.description }}</small> </td> <td class="align-middle">0</td> <td class="align-middle">0</td> <td></td> </tr> {% endfor %} </tbody> </table> {% endblock %} I have a page called topics.html that does not (yet) extend base.html: {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{ board.name }}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body> <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item active">{{ board.name … -
Form Django give me an error when the key is already in the database
I have a model with an unique field: phone. I'm trying to create a form to ask to the user his phone and then search in data base. But when I try to do: form.is_valid() I receive an error saying the user is already in data base. Any idea of what I should do? The idea is that the phone should always be in database, almost like a login. -
I cannot save a picture link from a facebook account
I am trying get a picture link from a facebook account but get this message: django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile.user_id I can see a picture link in console, but I cannot save it in user profile. here is my model.py when I'm trying to do that. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from allauth.account.signals import user_signed_up, user_logged_in from allauth.socialaccount.models import SocialAccount import hashlib try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') city = models.CharField(max_length=30, blank=True) about = models.TextField(blank=True) avatar = models.ImageField(upload_to='avatars/', verbose_name='Images', blank=True) sound = models.BooleanField(default=False) points = models.DecimalField(max_digits=4, decimal_places=2, default=0.00) energy = models.IntegerField(default=0) avatar_url = models.URLField(max_length=500, blank=True, null=True) class Meta: db_table = 'user_profile' verbose_name = 'Profile' verbose_name_plural = 'Profiles' def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.userprofile.save() #@receiver(user_logged_in) @receiver(user_signed_up) def set_initial_user_names(request, user, sociallogin=None, **kwargs): preferred_avatar_size_pixels = 25 if sociallogin: if sociallogin.account.provider == 'facebook': picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format( sociallogin.account.uid, preferred_avatar_size_pixels) profile = UserProfile(user=user, avatar_url=picture_url) #profile = UserProfile.objects.get(user=user) #profile.avatar_url = picture_url profile.save() If I am doing like that at the end: #profile = UserProfile(user=user, avatar_url=picture_url) profile = … -
AttributeError at /course/expression-regular-django/ 'ContactCourses' object has no attribute 'name'
I had this problem whem i want do Send local email on my django app... I'm not realizing it, because I'm accessing the attribute inside the class. Memos when I step {name}, it does not recognize. Thanks Best regards class ContactCourses(forms.Form): name = forms.CharField(label="Name", max_length=100) email = forms.EmailField(label="Email") message= forms.CharField(label='Message', widget=forms.Textarea) def sendEmail(self, course): subject = f'Contacto {course}' message= f"Nome: {self.name}, E-mail: {self.email}, {self.message}" context = { 'name': self.cleaned_data['name'], 'email': self.cleaned_data['email'], 'message': self.changed_data['message'] } message= message% context send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [settings.CONTACT_EMAIL]) -
Return JSON response without redirecting
I'm new with django and i'm trying to update fields in my view without redirecting, i'm trying to return a JSON file when a view function is called, but i can't seem to find how to do so withouth redirecting to some url. I think it may have something to do with my urls.py: ... path('#', views.myFunction, name='myFunctionName'), -
How to manipulate documents in web
I'm got recommendation to do a Web app the can store a document and automatically format(font size,font) it. Its possible to do it? How? -
Loading URL patterns without activating them?
My Django project has two applications in it: a web tool and a REST interface. I run the REST interface on my database system (e.g. db.myhost.com). This interface only has URL patterns that correspond to the various REST endpoints: app_name = "rest" urlpatterns = [ url(r'^report/id/(?P<rid>[0-9]+)/$', views.ReportByID.as_view()), url(r'^report/slug/(?P<slug>[a-z0-9-]+)/$', views.ReportBy/SlugID.as_view()), ] Part of the data that these views ultimately show need links to the other application in my project (which I host on a separate system). That application also has URL patterns: app_name = "mytool" urlpatterns = [ url(r'^some/cool/path/$', views.some_cool_path), ] The REST interface only enables the REST URL patterns, since I only want to serve REST endpoints via that host: # On my REST system ROOT_URL = "myproject.rest_urls" Is there a way that I can get the REST application to load the mytool URL patterns without activating them? I don't want a user to be able to browse to db.myhost.com/some/cool/path/ and get an error because that path isn't served on that host, it's served by the web tool server instead. It would be helpful, however, to be able to use reverse() to get the mytool URLs, even if they are just relative fragments (i.e. /some/cool/path ... I could always prepend … -
How to filter Charfiled by List of Tags in Django ORM
What is the preferred way to filter CharField using List of Tags? in database i have something like this : genres = "something, apple ,something_else ,something_else2, orange, grape, more.." i tried using __in operator nothing comes out elem = list(Elements.objects.filter(genres__in=['apple','orange','grape'])) -
The color changes depending on the truth of the falsity in the loop {% for%}. Django, Python, bootstrap
I have a very simple template that displays all the elements in my class. I would like the 'badge' color to change depending on whether the field 'free_or_no = models.BooleanField (default = None)' is checked or unchecked. However, the colors of all fields are changed at the same time, not the selected ones, in which the value is different. How can I solve this problem? any help will be appreciated. {% for time in daytime %} {% if daytime.free_or_no == True %} <span class="badge badge-lg badge-pill badge-success text-uppercase">{{ time.name}}</span> {% else %} <span class="badge badge-lg badge-pill badge-danger text-uppercase">{{ time.name }}</span> {% endif %} {% endfor %} -
Heroku doesn't display my latest django template change
A bit of a classic works in dev but not production. Never had an issue with heroku not working if it works in dev before. I recently made a commit in django app which changed a png to an svg and change the template accordingly - ie just 2 file changes in the commit. Then realised I needed a quick additional change in the template and force pushed the change to origin and then to heroku. However now heroku just doesn't display that template (and the image within it). Everything else works. Tried to do another change to the template and push another commit to see if that would fix it. I've rolled back heroku for now, but not sure how best to go about determining where the error is? -
Django display data from json
i want to display cryptocurrency prices on my site. Therefor i parse the latest BTC/USD price from coinmarketcap.com now i want to display them in a list but i first dont know who to save the symbol from the json to my database and second how can i display my view propperly. Currently i only save key:value of price_usd where key is the name of the currency. views.py def crypto_ticker(request): list_prices = CryptoPrices.objects.get_queryset().order_by('-pk') paginator = Paginator(list_prices, 100) # Show 100 prices per page page = request.GET.get('page') price = paginator.get_page(page) return render(request, 'MyProject/crypto_ticker.html', {'price': price}) urls.py url(r'^crypto_ticker/$', MyProject_views.crypto_ticker, name='crypto_ticker'), models.py class CryptoPrices(models.Model): symbol = models.CharField(max_length=10) key = models.CharField(max_length=30) value = models.CharField(max_length=200) celery update task: @periodic_task(run_every=(crontab(minute='*/1')), name="Update Crypto rate(s)", ignore_result=True) def get_exchange_rate(): api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=100" try: exchange_rates = requests.get(api_url).json() for exchange_rate in exchange_rates: CryptoPrices.objects.update_or_create(key=exchange_rate['id'], defaults={'value': round(float(exchange_rate['price_usd']), 3)} ) logger.info("Exchange rate(s) updated successfully.") except Exception as e: print(e) -
How to group by two columns on queryset in Django2?
I am getting little confused about how to use .annotate on quesryset. To be quick: I have a model: class Row(models.Model): order = models.ForeignKey('order.Header', blank=True, null=True) qty = models.IntegerField(blank=True, null=True, default=0) name = models.CharField(default='', blank=True, null=True) total = models.DecimalField(max_digits=10, decimal_places=2,default=0, blank=True, null=True) profit = models.DecimalField(max_digits=10,decimal_places=2,default=0, blank=True, null=True) profit_percent = models.DecimalField(max_digits=6,decimal_places=2,default=0, blank=True, null=True) month_sold = models.IntegerField(default=0) month_painted = models.IntegerField(default=0) area_painted_1 = models.DecimalField(max_digits=5,decimal_places=2,default=0, blank=True, null=True) area_painted_2 = models.DecimalField(max_digits=5,decimal_places=2,default=0, blank=True, null=True) What I need to do is to create a kind of a summary, that will tell me month by month, a sum of Total, Profit Avg of profit, and also a sum of the painted area. Something like that: +-------+-------+--------+----------+--------+--------+ | month | Total | Profit | Profit % | area_1 | area_2 | +-------+-------+--------+----------+--------+--------+ | 0 | 23000 | 3000 | 13% | 55 | 12 | | Jan | 10000 | 1000 | 10% | 43 | 44 | | April | 20000 | 1000 | 5% | 99 | 134 | +-------+-------+--------+----------+--------+--------+ I tried to achieve that with .annotate: result = Rows.objects.values('month_sold') \ .annotate(total=Sum('total')+1) \ .annotate(profit=Sum('profit')) .annotate(profit_percent=Round(F('profit')/F('total')*100, 2)) .annotate(area_1=Sum('area_painted_1')) .annotate(area_2=Sum('area_painted_2')) .values('month_sold', 'total', 'profit', 'profit_percent', 'area_1', 'area_2') .order_by('moth_sold') But obviously, it groups by month_sold. So total, profit values are good, … -
Auto populate fields from database in django
models.py class InfraServiceInfo(db.Model): app_name = db.CharField(choices=VIEW_APP_CHOICES, max_length=1000) stack = db.CharField(max_length=1000) description = db.TextField('InfraServiceInfo', choices=VIEW_DESC_CHOICES) A description is associated with every app_name in the InfraServiceInfo table. As app_name is a drop down list, when the selects a particular app_name the corresponding description associated with that app_name should be auto populated in the forms. Example: app_name = "test", description = "testing" and app_name = "test2", description = "testing2". When the user select test from drop downlist, the description should auto populate testing string. How do I do this?