Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tutorial: 'detail' is not a valid view function or pattern name
I am using Windows XP, Python 3.4 and Django 2.0.2 I am new to Django and am trying to follow the instructions in https://docs.djangoproject.com/en/2.0/intro/tutorial04/ the Django tutorial. The most likely mistake that I made is that I did not cut and paste code in the right places. It would be helpful to me (and possibly others) if the writers of the tutorial had a reference to the complete list of the py and html files at each stage (not just part of the code). I have the following error: http://127.0.0.1:8000/polls/ ` NoReverseMatch at /polls/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Exception Location: C:\programs\python34\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\programs\python34\python.exe Python Version: 3.4.3 Python Path: ['Y:\mysite\mysite', 'C:\WINDOWS\system32\python34.zip', 'C:\programs\python34\DLLs', 'C:\programs\python34\lib', 'C:\programs\python34', 'C:\programs\python34\lib\site-packages'] Server time: Thu, 6 Dec 2018 15:35:56 -0600 Error during template rendering In template Y:\mysite\mysite\polls\templates\polls\index.html, error at line 4 Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. 1 {% if latest_question_list %} 2 <ul> … -
Django: Combine two Field Inputs to Generate URL to navgate to another Django Template
In my Django project there is an index model which renders an index.html view, in which I have a form: <input type="text" list="option"> <label >Type or Select Query</label> <datalist id="option"> <option value= "Option 1"> <option value= "Options 2"> </datalist> <div class="input-field"> <select> <option value="view_function1">Text 1</option> <option value="view_function2">Text 2</option> </select> </div> What I want to do is take the text input / option selection in the text field and merge it with the option selected in the drop down field to form something like this: /view_fucntion2/Option 1 or /view_function1/query These urls would serve the various models in a template defined in views.py. The query + drop down merge will execute on a button submit. I understand I may be able to achieve this with Jquery, but my grasp of that is limited. What should I do? -
How does django UpdateView find a html form? (name convention)
I am following a django tutorial and everything is working, but I don't understand how this class, in views.py, find the album_form.html if I didn't pass any parameters of the path/name. class AlbumCreate(CreateView): model = Album fields = ['artist' , 'album_title' , 'genre' , 'album_logo'] The html name is album_form.html and works fine, but if I change to somethingelse_form.html it doesn't work anymore. From where django identifies that it have to use 'album' instead of 'somethingelse'? What is the name convention? Its not from urls.py, because mine is this: url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add') -
How to transfrom static path to web url in Django?
I think my problem is more or less a simple question, but I'm not still accustomed to using webpack and so on, So your advice will be helpful to me. (I'm using Django on backend and React on frontend) Hierarchy of folder Cebula4 - back - settings.py - manage.py - front - static - bundles - MainPage.js (webpacked) Settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') ... Static URL : C:\Users\1Sun\Cebula4\front\static\bundles\MainPage.js How I can transform this Static URL to local web_url like http://127.0.0.1:8000/static/bundles...? -
Django Unit Testing in Visual Studio 2017 or 2019:
Django needs setup code so unit tests on models that need a database will work. Standard Django unit test do that silently in the background but not with Visual Studio. I have not found a good way to provide setup code that will work for starting test runs from both the Visual Studio Test Explorer and with django manage.py test. Visual Studio Test Explorer does not call setUpModule/tearDownModule nor tearDownClass. The following code works from within VS, but I find it ugly, AND it doesn't work with nose/django-nose: import os import django import unittest from django.test.utils import setup_test_environment, teardown_test_environment from django.test.utils import setup_databases, teardown_databases try: os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test" setup_test_environment() print("Called setup_test_environment()") django.setup() old_config=setup_databases(1,False) except: old_config=None def tearDownModule(): try: global old_config if old_config: teardown_test_environment() print("Called teardown_test_environment()") teardown_databases(old_config,1,False) except: pass from unittest import TestCase # This needs to be called after django.setup from konsenser.models import Poll class PollTest(TestCase): @classmethod def setUpClass(cls): print("Setting up class") return super().setUpClass() @classmethod def tearDownClass(cls): print("Tearing down class") return super().setUpClass() def setUp(self): Poll.objects.create(name='Test Poll', description='for testing') def test_content(self): poll=Poll.objects.get(id=1) name=f'{poll.name}' description=f'{poll.description}' self.assertDictEqual({'name':name,'description':description }, {'name':'Test Poll','description':'for testing'}) if __name__ == '__main__': unittest.main() When run by VS Test Explorer, the output is Called setup_test_environment() Creating test database for alias 'default'... … -
how to publish HIT on external http website using mturk?
Actually I create a website using Django in python3.7 and publish my HITs on that website. Now I am trying to publish those HITs to the crowd using mturk. I found some documents, but it seems that the ExternalQuestion of mturk only support the https website. (while my website is http) I am sure there are some solutions, but I need more time to find out them..Dose anybody has any ideas about how to publish HITs on http website with mturk? Any idea will be much appreciated! -
django not starting server
hai i am new to django when i start my project it returns me a error Traceback (most recent call last): File "/home/kid/PycharmProjects/test/myproject/manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kid/PycharmProjects/test/myproject/manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Problems with redirect URI on production domain (django allauth)
I got stacked with django allauth redirect callback (I am begginer in web development and faced troubles with first deployment in production). Long story short: I use django allauth for loggining on the web site through social network instead of regular process of signing up. While development everything was good, I configured social application in vk.com and configured Social Application in django admin. Redirect URI looks like: http://127.0.0.1:8000/accounts/vk/login/callback/ and in development (when server was running on 127.0.0.1:8000) everything was ok and authentication was successful. However, after deploying django server on VPS hosting I faced problems. I associated domain with hosting ip: django server is running on http://188.158.73.151:9000 but is accessible both https://example.com and http://184.154.83.121:9000. But, authentication is successful only from ip:port (http://184.154.83.121:9000) and fails if I try the same from https://example.com (raise error: Social Network Login Failure An error occurred while attempting to login via your social network account.) I noticed that redirect URI for both cases are http://184.154.83.121:9000/accounts/vk/login/callback/ and if I manually change it to https://example.com/accounts/vk/login/callback/ authentication will be successful. However, I don't have any idea how to handle it. What should I do to get redirect with my production domain? Please help, I scrutinized dozens of google pages … -
One to Many options doesn't appear in Model Form Django
I am very new to Django and struggling to figure wrong what am I missing in Django Model Form. I want to display a drop-down with predefined values in the form but for some reason, the options never appear. Following is the code from models.py LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) class Status (models.Model): class Meta: db_table = 'Status' status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', ) class Property(models.Model): def __str__(self): return self.propertyTitle propertyID = models.AutoField(primary_key=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True)` Following is the code from ModelForm class CreateAdvertisementForm(ModelForm): class Meta: model = Property exclude = ['propertyID'] Following is the code from my Template {% block body %} <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form>{% endblock %} Please help me understand what is going wrong. -
How do I send email, to my user's email? (Help Django)
How do I send email to my user's email? Hi, I want to send email to my user, using his email, informing that the user has been updated, I tried something like this in the forms: forms.py @transaction.atomic def update_student(request): try: student = request.user.student except Student.DoesNotExist: student = Student(user=request.user) if request.method == 'POST': form = StudentUpdateForm(request.POST, instance=student) if form.is_valid(): form.save subject = 'Usuario atualizado' from_email = settings.EMAIL_HOST_USER to_email = [student.email] update_message = 'Usuario ativado com sucesso' send_mail(subject,from_email=from_email,recipient_list=to_email,message=update_message,fail_silently=False) return redirect('student_list') else: form = StudentUpdateForm(instance=student) return render('student_list') No problem, but the email is not sent, so I used send_email in students / views.py and the email was sent correctly, however with emails in a 'static' way in the fields "from" and "to" students/views.py class StudentUpdate(UpdateView): model = Usuario form_class = StudentUpdateForm context_object_name = 'student_update' template_name = 'students/student_update.html' success_url = reverse_lazy('student_list') send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) How to use the user's email instead of stating "static" emails using strings? -
how to get celerybeat cron tasks to run in docker container for django app?
I'm trying to run celery beat tasks in my django/nuxt app I have separate frontend and back end directories and I'm using docker-compose to build and run my app. (pycharm professional-mac-oS seria I can run my tasks perfect without using docker containers locally but when I try to containerize to run, both celery and celery-beat wont stay running. I find the documentation is very poor online and even on celery's or dockers official documentation there's no mention of running celery & beat with docker Can anyone tell me if my configuration is wrong or what I need to do in order for my app to accept the cronjobs in my settings.py? I build my containers with docker-compose up-d and run my app with docker-compose exec django bash Can anyone point me in the right direction? settings.py import os from configurations import Configuration, values from datetime import timedelta #print(os.environ) class Base(Configuration): DEBUG = values.BooleanValue(False) SECRET_KEY = '2pj=b#ywty7ojkv_gd#!$!vzywakop1azlxiqxrl^r50i(nf-^' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = values.DatabaseURLValue() ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework.authtoken", "django_celery_results" , "django_celery_beat" , "corsheaders", "djoser", "accounts", "posts", "comments", "events", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF … -
Retrieve data from Models with Foreign Keys
I have a doubt about getting the data from another Model using ForeignKeys. I got a Salesman in a model class Salesman(models.Model): name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) def __str__(self): return "%s" % (self.name) Store model class Store (models.Model): name= models.CharField(max_length=50) phone = models.IntegerField() contactMail = models.EmailField() def __str__(self): return "%s" % (self.name) And a Product Model class Product (models.Model): name = models.CharField(max_length=40) description = models.CharField(max_length=150) price = models.CharField(max_length=7) store = models.ManyToManyField(Store) def __str__(self): return "%s" % (self.name) I was trying to get the name of the Store throught the Salesman because later I need to get Products associated in the Store and i want to use the same process or something similar to populate a HTML table with Products in that specific Store. I already got a Salesman called JohnSmith, in Store named LeBlanc. Pencil and Book are Product associated in LeBlanc In my view: def load_store(request): salesDude = Salesman.objects.filter(name='JohnSmith') print(salesDude) // <QuerySet [<Salesman: JohnSmith>]> <- gotcha Then I try to use the Salesman object to retrieve the ID from the Store but i'm stuck here. Forward, i need the name of the store to be recovered and used as a filter to retrieve the … -
ManyToMany models relationship Django
I have two models: class University(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=30, null=True, blank=True) country = CountryField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) departments = models.ManyToManyField(Department) class Department(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I want to University have many Departments and vice versa which works fine. But I also want to store more departments individually for one university. For instance: University1 has Department1 and Department2. University2 has Department1. I want those departments store individually for each university. Now when I update Department1, ofcourse every University which has that school will see changes. I don't want that. I want to update Department1 but only for the University1 record. Department1 in University2 shouldn't be updated. I assume that adding through option with intermediate model wouldn't help. What's the best solution? -
Display pop-up modal when user not in designated Django group
Currently, I'm redirecting users to the login page when they aren't in the group required by the page they're attempting to view with the below decorator. What I'd like to do is pop up some sort of "you aren't authorized" modal when they try to access a part of the site that requires a group they aren't in, but I'm a little fuzzy on the best way to go about passing the groups / requirements / logic / wiring it all together on the front end. def group_required(group, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user is a member of a specific group, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. Ex: @group_required('group',login_url='login') """ def check_perms(user): if isinstance(group, six.string_types): groups = (group, ) else: groups = group # First check if the user has the permission (even anon users) if user.groups.filter(name__in=groups).exists(): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url) -
How to show (the contents of) a subdomain as a path/subfolder with nginx
I have 2 websites: api.example.com (a Django app) example.com (a blog with Ghost) This is my current nginx setup for my blog (root domain) server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name example.com root /usr/share/nginx/html; index index.html index.htm; # this was created by ghost one click deploy on DigitalOcean location / { proxy_pass http://localhost:2369; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_buffering off; } I'm trying to make it so that I can go to example.com/api and see the contents of api.example.com, but am not redirected and the url in the addressbar should show example.com/api. I don't even know the right term for this.. Proxying? Masking? -
Reordering dropdown list on Modelform in Django
I am using Status table with 3 statuses used for reports. Each report is going through 3 phases (non-numerical), but now I have to implement new phase that has to be between phase 2 and 3 in earlier sequence. Status table has only 2 columns: status_id (pk) and type The problem I got is when I am showing drop down list (in modelForm), values appear sorted by primary key. What is best practice solution for this? p.s. It feels stupid to change the "type" in the database in order to get it right -
django-python3-ldap Sync Users Automatically and Securely
I have a Django app with Active Directory authentication using django-python3-ldap. I need to sync users from AD to auth_user each day so I can assign them to groups. Therefore, I thought I could use the python manage.py ldap_sync_users command. This command works well, but it requires AD credentials to be in the settings.py file like this: LDAP_AUTH_CONNECTION_USERNAME = "username" LDAP_AUTH_CONNECTION_PASSWORD = "password" Having the credentials in cleartext is not ideal, and putting it in an environment variable is also not ideal. Creating an AD account for the express purpose of running this command is not an option. How would I schedule this command to run without exposing credentials somewhere on the server? -
On Django with a MySQL backend, "Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '='"
In a Python 2 Django app, I'm defining a string with a 'money with wings' emoji: # -*- coding: UTF-8 -*- MESSAGE = "Stash some cash 💸" This passes the pylint linter fine. However, I also have a model Message with a content field, and if I try to write to there, I get an error message: Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '=' Below is the full stack trace. How can I fix this? Since utf8mb4_general_ci is MySQL-specific, I suppose that the encoding the database is currently in, and utf8_general_ci is the encoding that I'm defining my string to be. How can I define my string to be in utf8mb4_general_ci instead of utf8_general_ci? /app/venmo_platform/current/venmo/communication/services/notification_service.pyc in get_message_for_notification(message_content) 99 100 def get_message_for_notification(message_content): --> 101 message, _ = Message.objects.get_or_create(content=message_content) 102 return message /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/manager.pyc in manager_method(self, *args, **kwargs) 125 def create_method(name, method): 126 def manager_method(self, *args, **kwargs): --> 127 return getattr(self.get_queryset(), name)(*args, **kwargs) 128 manager_method.__name__ = method.__name__ 129 manager_method.__doc__ = method.__doc__ /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/query.pyc in get_or_create(self, defaults, **kwargs) 403 self._for_write = True 404 try: --> 405 return self.get(**lookup), False 406 except self.model.DoesNotExist: 407 return self._create_object_from_params(lookup, params) /app/shared/virtualenvs/venmo_platform27/local/lib/python2.7/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs) 326 if self.query.can_filter(): 327 clone = clone.order_by() --> 328 num = … -
intermediate pages for a custom admin button
I have made a button in my django admin. template custom_change_form <input type="submit" value="Test Peer" name="_peer-test"> Then in admin.py def response_change(self, request, obj): if "_peer-test" in request.POST: self.message_user(request, "Peer Tested") return HttpResponseRedirect(".") return super().response_change(request, obj) And it works just fine. Now I want to add intermediate page to it. Normally by the standard action from admin you can do this!! def export_selected_objects(modeladmin, request, queryset): selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect("/export/?ct=%s&ids=%s" % (ct.pk, ",".join(selected))) The question is how can I apply this to my custom button. so dat I can redirect to a view made by me and passes the variables. -
How to dynamically update sqlite3 db?
I have a sqlite3 db and I edit it by django-admin panel. Also I have a .py file which handles this db. How to make it so that when the .py is running, if I change the database through the django-admin panel, the program also changed? -
Django models getting data where there is a relationship
I have three Django Models: @python_2_unicode_compatible class GroupInvoice(models.Model): group = models.ForeignKey('Group', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return str(self.invoice.number) + ' ' + self.group.group_name @python_2_unicode_compatible class ProviderInvoice(models.Model): provider = models.ForeignKey('Provider', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) paid=models.BooleanField() created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.invoice.invoice_number + ' ' +self.provider.first_name @python_2_unicode_compatible class Invoice(models.Model): number = models.IntegerField(null=True, blank=True) #NOT THE INVOICE ID might be changed by user total = models.DecimalField(max_digits=11,decimal_places=2) # 10 digit max, date = models.DateField(auto_now=False, auto_now_add=False) paid = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return 'PK: ' + str(self.pk) + ' InvoiceID: ' + str(self.number) + ' ' + str(self.total) I am still a bit fuzzy on relationships in the models, but I WAS sending to a view a list of all invoices: class InvoiceListView(TemplateView): template_name = 'ipaswdb/invoice/list.html' def get(self, request, *args, **kwargs): context = super(InvoiceListView, self).get_context_data(**kwargs) status_requested = None invoices = None if request.GET.has_key('status'): status_requested = request.GET['status'] status_requested = status_requested.split('/')[0] # drop any trailing / (forward slashes) if status_requested: invoices = Invoice.objects.all() invoice_status = 'all' else: invoices = Invoice.objects.all() invoice_status = 'all' context['num_invoices'] = len(invoices) context['invoices'] = invoices context['invoice_status'] = invoice_status return render(request,self.template_name,context) It turns out I would really like to get … -
Python Django 'TypeError: object is not iterable' when trying to iterate over models query set
All, I've read through previous posts of a similiar issues and none seem to solve my problem. I'm making a website for my fantasy football league as my intro to Django. However, I'm running into an error every time I try to insert content from my models into the html template. The error shown is 'TypeError: 'PastSeasons' object is not iterable', with 'PastSeasons' being the model. I know the postgresql table and db is set up properly because I can view it via pgadmin4 and through the django /admin site. I can also run the 'python manage.py shell' and query the model, return a queryset, and then iterate through that queryset using the exact same syntax as the views.py file. Here is the django models.py file: from django.db import models class PastSeasons(models.Model): year = models.IntegerField() place = models.IntegerField() team_name = models.CharField(max_length=100, unique=False) owner = models.CharField(max_length=100, unique=False) wins = models.IntegerField() losses = models.IntegerField() ties = models.IntegerField() points_for = models.FloatField() points_against = models.FloatField() def __str__(self): return str(self.year) Here is the subsequent views.py file: from django.shortcuts import render from .models import PastSeasons def past(request): past_list = PastSeasons.objects.all() past_szn = {'past_szn': past_list} return render(request, 'basic_app/past_seasons.html', past_szn) Lastly, here in the html template (there's additional … -
Django Relation between two models
I am very new to Django. Can you please give a boilerplate of models how to relate two models between each other. --Below is Section model from articles.models import Article # Create your models here. class Section(models.Model): #associations user = models.ForeignKey(settings.AUTH_USER_MODEL) article = models.ForeignKey(Article) #Article --Below is Article model from sections.models import Section User = settings.AUTH_USER_MODEL # Create your models here. class Article(models.Model): owner =models.ForeignKey(User, null=False) sections = models.ManyToManyField( Section ) However. I got the below error: ValueError: Cannot create form field for 'article' yet, because its related model 'articles.models' has not been loaded yet Thanks All B -
Mezzanine Django Cartridge conectar con un servicio de pagos en mexico
Contexto: Uso un servidor local en fisico, con apache 2, el sitio ya tiene productos pero es necesario implementar la recepccion de pagos online. Cartridge 0.13.0 Mezzanine CMS Estoy tratando de agregar un método de pago a Cartridge en México, pero los que están recomendados en la documentación de Cartridge no estan disponibles en mi país. Braintree Egate Authorize.Net Stripe¶ Mi pregunta es si ¿alguien en mexico logro conectar un servicio de pagos con su sitio web? -
Resty Resolver issue Python
I was following a tutorial: https://medium.com/@ssola/building-microservices-with-python-part-i-5240a8dcc2fb from connexion.resolver import RestyResolver import connexion items = { 0: {"name": "First item"} } def search(): return items if __name__ == '__main__': app = connexion.App(__name__, 9090, specification_dir='swagger/') app.add_api('my_super_app.yaml', resolver=RestyResolver('api')) app.run() I keep getting the same error: ImportError: No module named api Does any one know how to resolve this error? I pip installed all the dependencies