Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Empty path didn't match any urls in Django
Hi I have been trying to implement the tutorial from official tutorial of django. But I am getting this error : enter image description here my views in poll app is enter image description here [enter image description here][3] following are my site url and poll url respectively enter image description here enter image description here -
Unity Web Request + Django: CSRF token missing or incorrect
I am receiving an error from Django that the "CSRF token is missing or incorrect" along with its standard error message. Many other questions have covered the right response when you're working with a standard browser and a Django server, but I'm trying to get UnityWebRequest to play nicely with Django. Conceptually, I have two steps. First, I'm calling a GET request on my login page, parsing out the csrfmiddlewaretoken from my form, and the csrftoken from the set-cookie header. Then, I make a second UnityWebRequest that includes the "referer" as a header and the csrftoken as a header in the cookies. I would add in to the form the username and password and csrfmiddlewaretoken, but the error is present either way. Are there other headers or cookies to set? I assume my trouble is that I'm trying to emulate the behavior of a web browser in Unity, and that's complicated. UnityWebRequest loginPage = UnityWebRequest.Get("https://dividedsky.herokuapp.com/accounts/login/"); yield return loginPage.SendWebRequest (); if(loginPage.isNetworkError || loginPage.isHttpError) { Debug.Log(loginPage.error); yield break; } // get the csrf cookie string SetCookie = loginPage.GetResponseHeader ("set-cookie"); Debug.Log (SetCookie); Regex rxCookie = new Regex("csrftoken=(?<csrf_token>.{64});"); MatchCollection cookieMatches = rxCookie.Matches (SetCookie); string csrfCookie = cookieMatches[0].Groups ["csrf_token"].Value; // get the middleware value string … -
Changing Django language code on the links
(i18n) The ISO language code for Kazakh language uses kk I want to change it to kz in my project to make it convenient for people in Kazakhstan who used to be use kz in links. As example I need to be able instead to www.mydomain.com/kk use www.mydomain.com/kz -
* wants int error in Django when trying to save
I am using cookiecutter which provides Users setup along with Signup and login functionality I have customised the signup form provided by cookiecutter by referring to this link Following is in my forms.py from django.contrib.auth import get_user_model from django import forms class SignupForm(forms.ModelForm): class Meta: model = get_user_model() fields = ['Name', 'Address','Mobile_No','Gender','Age','OTP'] def signup(self, request, user): user.Name = self.cleaned_data['Name'] user.Address = self.cleaned_data['Address'] user.save() return user I am using DjongoDB connector for MongoDB(which is my database) Whenever I am clicking on save, I am getting "TypeError at /accounts/signup/ * wants int" error. This is what is there in signup.html <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo; </button> </form> -
Automatically show the foreignkey's other fields in django
I am trying to show the field(s) related to its foreignkey on html. Let's see I have two models as shown below: models.py from django.db import models class Model_Item(models.Model): item_name = models.CharField(max_length = 20, null = False, blank = False, unique = True) item_unit = models.CharField(max_length = 20, null = False, blank = False) # can be kilogram, pound, ounce, etc def __unicode__(self): return self.item_name class Model_Weight(models.Model): item = models.ForeignKey(Model_Item, to_field = "item_name") item_weight = models.FloatField(null = True, blank = True) def __unicode__(self): return self.item On Model_Item model, each item can have its own unit, and there can be many items. Then when we choose the item on the second model (Model_Weight), we will insert the value of the weight that is according to its unit. How can we show the corresponding "item_unit" in html, such that when we have selected the "item_name", its unit will show/hover somewhere in the webpage which enables us to put the correct weight value? These are the rest of the codes: forms.py from django import forms from .models import Model_Weight class Form_Weight(forms.ModelForm): class Meta: model = Model_Weight fields = ["item", "item_weight"] views.py from .models import Model_Weight from .forms import Form_Weight from django.views.generic import CreateView … -
How to save multiple html inputs with the same name in django?
Hi everyone I want to save the html array for dynamic inputs into the database using django, I have three dynamic inputs on my form, here is my code: Views.py def generatescripts(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = GenerateScriptsForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: Step = request.POST.getlist('Step') for el in Step: form.save() return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = GenerateScriptsForm() return render(request, 'page/generatescripts.html', {'form': form}) forms.py from django import forms from .models import Steps class GenerateScriptsForm(forms.ModelForm): class Meta: model= Steps fields = "__all__" -
Why my python docstring is not recognised?
I'm trying to create docstrings for a class method in django models. The method itself does not matter, it has the following structure: def my_function(self, param1, param2): """My function does this and that. params: param1: something param2: something else """ if param1 == param2: return param1 else: return param2 When in Django shell_plus I run MyClass.my_function.__doc__ it returns nothing, same happens when I try to access docstring via instance or through help(MyClass.my_function) Suggestions on what could be wrong with the docstrings and how to make them work much appreciated. -
gunicorn ImportError: No module named django_jalali
I'm running a project using django, nginx and gunicorn which works fine on local machine. When I moved the project to the server and installed everything, I tested the project using python3 manage.py runserver and it works fine. But when I try to run it using gunicorn, I ran to this error ImportError: No module named django_jalali The full gunicorn command: gunicorn iteachyou.wsgi:application --bind 127.0.0.1:8003 I've installed this package and there's no actual issue with it. There's a almost similar question with this issue here but it's relative to wsgi. Mine is a little weird i guess. Here's the full traceback: [2018-05-13 00:18:34 +0000] [10893] [INFO] Starting gunicorn 19.6.0 [2018-05-13 00:18:34 +0000] [10893] [INFO] Listening at: http://127.0.0.1:8003 (10893) [2018-05-13 00:18:34 +0000] [10893] [INFO] Using worker: sync [2018-05-13 00:18:34 +0000] [10897] [INFO] Booting worker with pid: 10897 [2018-05-13 08:48:34 +0000] [10897] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", … -
The standard process to handle static files
I have the following static htmls 1.the index.html <a href="index.html">Index</a> <br> <a href="list.html">List</a><br> <a href="detail.html">Detail</a> <p>The index page</p> 2. the list.html <p>The List Page</p> 3. the detail.html <p>This the detail page</p> When I open "the index page" in Chrome file:///Users/me/desktop/drafts/index.html Does the chrome implement a standard process like send a request and get a response? -
Django: Hidden/Orphaned oneToOneField values
When I run in manage.py shell qs = UserProfile.objects.all(); qs.count() I get 18 instances. However, when I look at my webpage's admin, under UserProfile, I only see 6 users. I can loop through the users and print the full namefor i in qs: print(i.user.full_name) it prints the first 6's full name and then errors out with this error: AttributeError: 'UserProfile' object has no attribute '_user_cache' I think I have some (12) items in UserProfile that are not linked to a user profile. They don't show up in the admin and so I don't know how to delete them. Does anyone know how I can delete them from the command line or why they may be there in the first place? I'd like to not have orphaned items like these. Each one should relate to a user. It should at least show in the admin tab! models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class User(AbstractBaseUser): ... -
Django: Showing "featured" items?
I'm having a little conundrum with sorting some items. I have a field called featured thats a boolean. I'm trying to display the featured coins first and then the remaining will be sorted by a different metric. In this code im using pub_date. However, when I put an if statement in my template for the featured items it's still showing those that are set to false as well. I'll post code below. index.html loops and if's {% if featured_coins_list %} {% for coin in featured_coins_list %} <div class="large-6 medium-6 cell"> <h2><a href="/coins/{{ coin.id }}/">{{ coin.name }}</a></h2> <p>Ticker: {{ coin.ticker }}</p> <p>{{ coin.summary }}</p> <a href="/coins/{{ coin.id }}" class="button">More Info</a></strong> </div> {% endfor %} {% endif %} {% if latest_coins_list %} {% for coin in latest_coins_list %} <div class="large-6 medium-6 cell"> <h2><a href="/coins/{{ coin.id }}/">{{ coin.name }}</a></h2> <p>Ticker: {{ coin.ticker }}</p> <p>{{ coin.summary }}</p> <a href="/coins/{{ coin.id }}" class="button">More Info</a></strong> </div> {% endfor %} </div> {% else %} <p>No coins are available.</p> {% endif %} views.py for index def index(request): featured_coins_list = Coin.objects.order_by('-featured')[:4] latest_coins_list = Coin.objects.order_by('-pub_date')[:8] context = {'featured_coins_list': featured_coins_list, 'latest_coins_list': latest_coins_list} return render(request, 'coins/index.html', context) models.py class Coin(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) ticker = models.CharField(max_length=5) featured = models.BooleanField(default=False) … -
Django Search form not submitting value
I have a search form in my django app. I want to add a filter option and so I'm adding a radio button for filtering by name alphabetically ascending and descending. The value for the search is getting passed through, but the radio button value is <form method='GET' action='{% url "search:catalog-query" %}' class="form my-2 my-lg-0 search-form"> <div class='input-group'> <input class="form-control" type="text" placeholder="Search" name='q' aria-label="Search" value='{{ request.GET.q }}'> <span class='input-group-btn'> <button class="btn btn-outline-success" type="submit">Search</button> </span> </div> <div> Sort Name: <label for="id_sort_up">Ascending</label><input type="radio" name="name_sort" id="id_sort" value='{{ request.GET.name_sort }}'> <label for="id_sort_down">Descending</label><input type="radio" name="name_sort" id="id_sort" value='{{ request.GET.name_sort }}'> </div> </form> urls.py url(r'^catalog/$', SearchCatalogView.as_view(), name='catalog-query'), view.py class SearchCatalogView(ListView): template_name = "search/view-catalog.html" print('search catalog') def get_context_data(self, *args, **kwargs): context = super(SearchCatalogView, self).get_context_data(*args, **kwargs) query = self.request.GET.get('q') context['query'] = query return context def get_queryset(self, *args , **kwargs): print('get_queryset') request = self.request method_dict = request.GET query = method_dict.get('q', None) # method_dict['q'] print(method_dict) if query is not None: return AAAA.objects.search(query) return AAAA.objects.features() When I print method_dict, I get <QueryDict: {'q': ['searched_option'], 'name_sort': ['']}> regardless of which radio button I am choosing. -
How can i correctly pass kwargs to RedirectView from django login to redirect to user profile?
I am having a problem with having a user login and then redirect to the correct profile. Each user has a profile. Each profile has a dashboard. Using django's built-in login, I want to redirect the newly authenticated user to a url like this: example.com/profile/dashboard/. I can't make this work because I cannot figure out how to pass the kwargs between the django login view and my detailview. In between, there is a redirectview. Can someone show me how to do this? models.py class Profile(TimeStamped, Slugged): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) self.slug = (slugify(self.user.username)) def get_absolute_url(self): return reverse('profiles:detail', kwargs={'profile': self.slug}) class Dashboard(TimeStamped, Slugged): profile = models.OneToOneField(Profile, on_delete = models.CASCADE) uuid = models.UUIDField(default=uuid.uuid4) def __str__(self): return self.profile.user.username def save(self, *args, **kwargs): super(Dashboard, self).save(*args, **kwargs) self.slug = (slugify(self.uuid)) def get_absolute_url(self): return reverse('profiles:dashboard', kwargs={'profile': self.profile.slug, 'dashboard': self.slug}) views.py class DashboardRedirectView(LoginRequiredMixin, RedirectView): permanent = False query_string = False pattern_name = 'profiles:dashboard' def get_redirect_url(self, *args, **kwargs): dashboard = get_object_or_404(Dashboard, slug=kwargs['dashboard']) return super().get_redirect_url(*args, **kwargs) urls.py urlpatterns = [ path('profiles/home/', DashboardRedirectView.as_view(), name = 'home') ......... -
Django allauth got an error is_safe_url() got an unexpected keyword argument 'allowed_hosts'
I am trying to setup Django social login using allauth tutorial here. I am able to display login page, but when I try login using facebook provider in this url http://localhost/accounts/facebook/login/, I got this confusing error: TypeError at /accounts/facebook/login/ is_safe_url() got an unexpected keyword argument 'allowed_hosts' Any suggestion for this issue? -
Django Query by State Name instead of 2 char abbreviation
I have a model that has a MULTISELECTFIELD where the user can select which states relate to them. It uses django-localflavor in the backend and so on the form they choose 'TEXAS' and 'TX' is stored on the database. I'm using this Q query to find the users that are associated with a state. Q(states__icontains=query) But this only returns a success for 'TX' and not 'TEXAS'. That makes sense since that is how it is stored in the database, but how can I search by Texas and get the same return? All I can think of is to go to the Class Manager (myclassManager(models.Manager) and create a get_state_name method that takes in a 2 digit code and returns the state name. If that is the case, I have to make a dictionary with the list by hand. I feel like the could be a cleaner way. Thoughts? -
Django fails on attempt to create a custom login form
I try to create a custom login form, so I have added a LoginForm class in forms.py: from django.forms import forms, CharField, BooleanField, TextInput, PasswordInput class LoginForm(forms.Form): email = CharField(label='email', max_length=255, widget=TextInput("E-mail")) password = CharField(label='password', max_length=255, widget=PasswordInput("Password")) remember = BooleanField(label='remember', required=False) But it throws on the form loading: File "/home/ghostman/Projects/asknow/asknow/asknow/urls.py", line 22, in <module> url(r'^', include('app.urls')), File "/home/ghostman/Projects/asknow/env/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/ghostman/Projects/asknow/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ghostman/Projects/asknow/asknow/app/urls.py", line 3, in <module> from app import views File "/home/ghostman/Projects/asknow/asknow/app/views.py", line 6, in <module> from app.forms import LoginForm File "/home/ghostman/Projects/asknow/asknow/app/forms.py", line 4, in <module> class LoginForm(forms.Form): File "/home/ghostman/Projects/asknow/asknow/app/forms.py", line 5, in LoginForm email = CharField(label='email', max_length=255, widget=TextInput("E-mail")) File "/home/ghostman/Projects/asknow/env/lib/python3.6/site-packages/django/forms/widgets.py", line 284, in __init__ attrs = attrs.copy() AttributeError: 'str' object has no attribute 'copy' Seems it is inside Django... What's wrong? How to fix? -
How to call Python variable in JavaScipt?
Hey! I have a Python function that returns some value. Also I connected to my project Google Charts. So I need to pass that value to a js function in html file of Google Charts. The project is on Django btw. What is the most correct way to do this? {% extends "gappi_tmp/wrapper.html" %} {% block content %} <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['lol',11], // The variable should be here, instead of '11' ['Eat', 11] // Here another variable ]); var options = { title: 'Inbox | Outbox' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> </head> <body> <div style="padding-top: 5px; background: cornflowerblue; width: auto; height: 300px;" id="piechart"></div> </body> {% endblock %} -
django admin application list in readonly
In django admin, we have 3 rules that we can attribute to a table we can add, modify and delete. when you choose for an user the rule of modify, he can't add and delete, My problem is that a have list of object and i don't want that the user modify but can select it. how disable it? -
Django 2.0: Redirect to user Dashboard after login Django RedirectView
I want to redirect a user to that user's dashboard after login. Whatever I am trying returns a 404 error: No Dashboard matches the given query. There are two slugs in the url. I need to know what I am doing wrong and how to fix it. Any help is much appreciated. views.py class DashboardRedirectView(LoginRequiredMixin, RedirectView): permanent = True query_string = True pattern_name = 'profiles:dashboard' def get_redirect_url(self, *args, **kwargs): dashboard = get_object_or_404(Dashboard, slug=self.kwargs.get('dashboard'), profile__slug=self.kwargs.get('profile')) return super().get_redirect_url(*args, **kwargs) project urls.py path('profiles/home/', DashboardRedirectView.as_view(), name = 'home') dashboard app urls.py path('<slug:profile>/<slug:dashboard>/', ProfileDashboardView.as_view(), name = 'dashboard') settings.py LOGIN_REDIRECT_URL = 'profiles/home' -
Django: Displaying image from model field?
I'm having trouble getting an image to display. This should be really easy to fix. I'm just a noob. :/ My models.py is the following: import datetime from django.db import models from django.utils import timezone class Coin(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) ticker = models.CharField(max_length=5) logo = models.FileField(upload_to='static/uploads/thumbs') website = models.URLField(max_length=200, default="https://example.com/") reddit = models.URLField(max_length=200, default="https://reddit.com/r/") twitter = models.URLField(max_length=200, default="https://twitter.com/") summary = models.CharField(max_length=500, blank=True) description = models.TextField() pub_date = models.DateTimeField('date published') def __str__(self): return self.ticker def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class CoinImage(models.Model): coin = models.ForeignKey(Coin, default=None, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='static/uploads', verbose_name='image') In my views.py I have: from django.http import HttpResponse, Http404 from django.template import loader from django.shortcuts import render from .models import Coin def index(request): latest_coins_list = Coin.objects.order_by('-pub_date')[:5] context = {'latest_coins_list': latest_coins_list} return render(request, 'coins/index.html', context) def detail(request, coin_id): try: coin = Coin.objects.get(pk=coin_id) except Coin.DoesNotExist: raise Http404("Coin does not exist") return render(request, 'coins/detail.html', {'coin': coin}) Then finally in my template file details.html: {% load static %} <img src="{{ coin.logo }}" alt="load failed"> <h1>{{ coin.name }} | {{ coin.ticker }}</h1> <p>{{ coin.description }}</p> <li><strong>Website:</strong> {{ coin.website }}</li> <li><strong>Twitter:</strong> {{ coin.twitter }}</li> <li><strong>Reddit:</strong> {{ coin.reddit }}</li> When I view the template I get the alt text. Then … -
Django queryset filter - why is an object meeting all criteria in the filter not included in result set?
My web app is not sending reminders to certain users who should get them. In trying to debug, the following example in a python shell has me pretty confused. Is there anything I'm missing, or doing wrong in the filter? If there's nothing obviously wrong, how can I debug this issue? >>> suz = User.objects.get(email="redacted") >>> suz.reminded False >>> suz.wait_until <= now True >>> suz.wait_until >= an_hour_ago True >>> suz.is_active True >>> remindable = User.objects.filter(is_active=True, ... reminded=False, ... wait_until__gte=an_hour_ago, ... wait_until__lte=now) >>> suz in remindable False -
ModuleNotFoundError: No module named 'django.contrib.auto'
I tried to run "python manage.py migrate" and I got this error. I need someone to please help solve this?! I'm using django 2.0.2 and python 3.6.5 ModuleNotFoundError: No module named 'django.contrib.auto' -
Storing data files for Heroku Django app on S3
I am attempting to deploy a web demo for a trained neural network on Heroku. I am having some trouble with this because the underlying Tensorflow model that needs to be loaded is about 900MB, which is too large to deploy in a Git commit with the code. I need a way to deploy this model file along with my code because of Heroku's ephemeral file system. I hacked together a solution where, only on the first received request, the server downloads the model files from an Amazon S3 bucket. I through this code in the body of the Django views.py file. However, this still isn't working because the first request is timing out on the Heroku server. Is there anywhere else I can put this code or a cleaner way to approach the problem? -
Shopify API JSON Feed / Limit 250 and Pages / GET pulls exactly the same records every time not next page
I am trying to get a list of all collects and when I do the API call to count them: https://[store-username].myshopify.com/admin/collects/count.json HTTP/1.1 200 OK { "count": 307 } I know the limit is 250 and page default is 1 https://[store-username].myshopify.com/admin/collects.json?limit=250?page=1 Will get 250 records. When I do page 2 - I'll get exactly the same records that in page 1 https://[store-username].myshopify.com/admin/collects.json?limit=250?page=2 So for curiosity, I tried page 10 - which is out of range - that would be 2500 > 307 and it returned the same 250 as in page 1 2nd thing: When I put it in the code / python - and I do script to run https://[store-username].myshopify.com/admin/collects.json?limit=250?page=1 It gets 250 records and then I do Page 2 https://[store-username].myshopify.com/admin/collects.json?limit=250?page=2 and return is NONE I am pulling my hair off and can't get those all 307 to update my database only 250 - so I have no idea why the Page 2 in the browser is loading exactly the same records as PAGE 1 and 250 for PAGE 2 it should be 307-250 = 57 records and in the script it is pulling NONE. Can you help? def handle(self, *args, **options): security = urllib2.HTTPPasswordMgrWithDefaultRealm() security.add_password(None, "https://[store-username].myshopify.com/admin/collects/count.json", “[credentials]”, "[credentials]") auth_handler … -
How to enumerate new column?
In my Django admin I have a TabularInLine class. In the picture, each element of this class is numbered with it's own ID. This TabularInLine class has a foreign key to an other class (class Part). How I can to numerate that for each FK with the numbering (my_id) started from 1 as in the picture below?