Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to replace ALL django "Status Code Exception" pages
Any Status Code exceptions like 404, 403, 405, 500, CSRF and more return their own "Django" specific pages, a few are HTML. handler403, handler404, and handler500 exist and can be easily overridden, but there are a lot of these "hidden" Django pages that are being returned upon error, an example is 405 (method does not exist) or CSRF (if no CSRF token is in the request) and probably many more. Is it possible to have a custom view (such as just a generic 404 return) for ALL of these "hidden" Django HTML pages? -
Django Cannot Connect to Remote MySQL Server
I am running a Django and attempting to connect to a MySQL server at my university. First of all: In order to connect the database, I normally SSH into a remote server (with authentication) of theirs, and then run MySQL and enter my MySQL authentications. This works without an issue, in Terminal as well as DataGrip. Now, using PyCharm, I have installed mysqlclient in the intepreter and changed my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '[DB_NAME]', 'USER': '[DB_USERNAME]', 'PASSWORD': '[DB_PASSWORD]', 'HOST': '[REMOTE SERVER ADDRESS HOSTING MYSQL]', 'PORT': '3306', } } Also using PyCharm, I have even opened up a data source in the Data Sources Tool Window and connected through SSH tunnel and MySQL authentication to the database. This is successful, and it is possible to make queries. However, I try to run: manage.py check and I receive: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site- packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '[REMOTE SERVER … -
django/rest: User registration API shows""Authentication credentials were not provided."
I'm trying to create an API for user registration in django 1.11.5 and python 3.5. When I write http://127.0.0.1:8000/users/:register/ in my browser I get the message: HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Authentication credentials were not provided." } If I run the rest-api user registration from rest-auth/registration it's working. But I want to configure my own API. Do you know how to fix this and make my API to work properly? This is my serializers.py: from users.models import User from rest_framework import serializers class RegisterUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['user_id', 'firstname', 'yearofbirth', 'lastname','othernames'] def create(self, validated_data): user = User.objects.create( user_id=validated_data['user_id'], firstname=validated_data['firstname'], yearofbirth=validated_data['yearofbirth'], lastname=validated_data['lastname'], othernames=validated_data['othernames'] ) user.set_password(validated_data['password']) user.save() return user This is my views.py: class UserRegister(CreateAPIView): serializer_class = RegisterUserSerializer token_model = TokenModel def create_auth(request): serialized = RegisterUserSerializer(data=request.data) if serialized.is_valid(): User.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'] ) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) This is my models.py: class User(models.Model): user_id = models.CharField(max_length=255, default="00") firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255, blank=True) othernames = models.CharField(max_length=255, blank=True) yearofbirth = models.SmallIntegerField(validators=[MinValueValidator(1900), MaxValueValidator(2018)]) And this is my urls.py: url(r':register/$', views.UserRegister.as_view(), name='register-user'), -
Saving many-to-one data from form Django
I am creating a job board site. I have the following models.py: 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 # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) details = models.TextField(max_length = 2000) salary = models.CharField(max_length = 20) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name A user can register as an employer just fine, but I am having problems getting Jobs to save to the database. Once a user registers/logs in as an employer they are redirected to employer_home.html, where an employer can post a job: {% extends 'core/base.html' %} {% block body %} <h1>Post a Job</h1> <form> {% csrf_token %} {{ form.as_p }} <button type="submit">Post</button> </form> {% endblock %} Here is my forms.py: from django.forms import ModelForm from .models import Job from django.contrib.auth.models import User … -
django authorization using a many to many table
Here are the docs and an example of a many to many relationship in a different post How to add column in ManyToMany Table (Django) now in order to use a many to many relationship in django must we specifiy a many to many relationship in one of the fields? Example: User permissions in my app are below. But First many to many code example. Extra fields on many-to-many relationships class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) now my use I have a user permissions and venue. Multipule users can have Multipule permissions on Multipule venues. so create permissions table: class VenuePermissions(models.Model): Venue = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True) create user table: class User(AbstractBaseUser): email = models.EmailField(unique=True) firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) avatar = models.ImageField() #add to datejoined = models.DateTimeField(auto_now_add=True) isauthenticated = models.BooleanField(default=False) is_active = models.BooleanField(default=True) isactingclient = models.BooleanField(default=False) isonlyclient = models.BooleanField(default=False) venuepermissions = models.ManyToManyField(VenuePermissions, through='Authorization') # fields required by django when extending user model USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['email', 'firstname', 'lastname'] EMAIL_FIELD = 'email' def get_full_name(self): """ Returns: The … -
How to Make Django Rest Framework work with CASSANDRA ENGINE?
How can I use DRF to send data (JSON) to Cassandra and receive needed? -
Multiple inheritance and deleting an object in Django
I've got a multiple-inheritance scenario that includes polymorphic base classes, and deleting has become a real headache. Here are the relevant models: class Stimulus(PolymorphicModel): stimulus_id = models.AutoField(primary_key = True) #prevent name clashes in multiple-inheritance scenarios class Meta: verbose_name_plural = "Stimuli" class Vitals(models.Model): vitals_id = models.AutoField(primary_key = True) #prevent name clashes in multiple-inheritance scenarios name = models.CharField(max_length=255) dob = models.DateField() species = models.ForeignKey(Species, on_delete=models.CASCADE) sex = EnumField(Sex, max_length=1) portrait = FilerImageField(null = True, blank = True) bio = models.TextField(null = True, blank = True) def __str__(self): return self.name + "(" + self.species.common_name + ")" class Meta: verbose_name_plural = "Vitals" class Human(Stimulus, Vitals): user = models.OneToOneField(User, on_delete=models.CASCADE, blank = True, null = True) phone_number = PhoneNumberField(null = True, blank = True) def get_name(self): return self.vitals.name def __str__(self): return self.name class Ambassador(Stimulus, Vitals): social_group = models.ForeignKey(SocialGroup, on_delete=models.CASCADE, null = True, blank = True) home_containment = models.ForeignKey(HomeContainment, on_delete=models.CASCADE) handlers = models.ManyToManyField(Human, through='HandlerClearanceRecord', related_name='handlers') def __str__(self): return self.name I can create Humans and Ambassadors with impunity, but if I try to delete one of them via the admin interface (either through Vitals or Humans/Ambassadors), I get: type object 'Vitals' has no attribute 'base_objects' OK, so after Googling around, I found this, which suggests that I … -
Django - template build-in filter tags {% url %}
I am a new coder with Django. So, first apologize for it if this question is too easy. <form action = "{% url 'post:comment' the_topic=topic user_id=1 %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> I am trying to use url tag to call a function is views.py. topic is a variable I passed in when this page is created. this is my code in urls.py url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"), then this is how I do in views.py def comment(request, the_topic, user_id): # 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 = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': the_topic} # save the data in database save_comments_into_database(the_topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': the_topic}) I get the NoReserveMatchException: exception screenshot I really don't get where it goes wrong. … -
Django: The SECRET_KEY setting must not be empty even if it exists in settings
I'm using python 3.5 and django 1.11.5 in windows 7. I have settings folder that contains base.py, mysql.py and sqlite.py manage.py contains: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GuardianAngel.settings") When I try python manage.py makemigrations I get the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 206, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\Python35\lib\site-packages\django\core\management\__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "c:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "c:\Python35\lib\site-packages\django\core\management\commands\migrate.py", line 15, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "c:\Python35\lib\site-packages\django\db\migrations\autodetector.py", line 13, in <module> from django.db.migrations.questioner import MigrationQuestioner File "c:\Python35\lib\site-packages\django\db\migrations\questioner.py", line 12, in <module> from .loader import MigrationLoader File "c:\Python35\lib\site-packages\django\db\migrations\loader.py", line 10, in <module> from django.db.migrations.recorder import MigrationRecorder File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module> class MigrationRecorder(object): File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "c:\Python35\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration app = models.CharField(max_length=255) … -
MultiValueDictKeyError when getting a Post Value in Django
I'm trying to create an online store in Django. In the views file, I'm looping through the list to see if the product id matches what the user submitted. However, I keep getting "MultiValueDictKeyError". Is there a way I can fix this? VIEWS FILE def index(request): products = { "items" : items } return render(request, "app_main/index.html", products) def buy(request): for item in items: if item['id'] == int(request.POST['i_id']): ##<<--THIS IS WHERE IT ERRORS amount_charged = item['price'] * int(request.POST['quantity']) try: request.session['total_charged'] except KeyError: request.session['total_charged'] = 0 try: request.session['total_items'] except KeyError: request.session['total_items'] = 0 request.session['total_charged'] += amount_charged request.session['total_items'] += int(request.POST['quantity']) request.session['last_transaction'] = amount_charged HTML FILE <table> <tr> <th>Item</th> <th>Price</th> <th>Actions</th> </tr> <tr> {% for i in items %} <td>{{ i.name }}</td> <td>{{ i.price }}</td> <td> <form action='/buy' method='post'> {% csrf_token %} <select name='quantity'> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <input type='hidden' name='{{ i.id }}'/> <input type='submit' value='Buy!' /> </form> </td> </tr> {% endfor %} </table> -
Django inline model form edit
Using twitter as an example (on the settings / profile edit page) they have a lot of fields where you can edit and then hit save and update things without having to go through an entire form or display an entire form. Instead it's broken down by susection. How would I implement something similar for a django model? -
Is it possible to assign django channels group in connection?
I hope you're all right: my question is whether I can make a connection to web socket from the client to a specific group, I'm currently connecting customers as follows: //connecting client with js var ws_scheme = window. location. protocol == "https:"? "wss":"ws"; //var ws_path = ws_scheme +': //' + window. location. host + "/sync/"; var ws_path = ws_scheme + ": //localhost: 8001"; console. log ("Connecting to " + ws_path); var socket = new ReconnectingWebSocket (ws_path); Okay, that's how it works, The problem is that I want each client to connect to a group created previously example: def ws_connect (message): for x in users: Group (x). add (message. reply_channel) and so sent the message to the respective group Group ("group1"). send ({' text': json. dumps (msg)}) Group ("group2"). send ({' text': json. dumps (msg)}) -
Django multiple database ProgrammingError
I'm trying to fetch data using raw query from mysql. cursor = connections['database2'].cursor() try: cursor.execute("select * from blog") finally: cursor.close() But It throwing following error ProgrammingError at /api/blog/ relation "blog" does not exist LINE 1: select * from blog -
Django - built-in templates tags with variables
I am a new coder with Django. <form action = "{% url 'post:comment' topic=topic user_id=1 %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> I am try to use this code to make a comment function for my website. The following is some relevant functions: def comment(request, topic, user_id): # 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 = CommentForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required text = form.cleaned_data['comment'] args = {'form': form, 'text': text, 'topic': topic} # save the data in database save_comments_into_database(topic.id, user_id, text) # redirect to a new URL: return render(request, 'post/detail.html', args) # if a GET (or any other method) we'll create a blank form else: form = CommentForm() return render(request, 'post/detail.html', {'form': form, 'topic': topic}) the namespace is already be named as "post" in urls.py However, I get this exception Exception Type: NoReverseMatch Exception Value: Reverse for 'comment' not found. 'comment' is not a valid view function or pattern name. Why the comment function cannot be matched? -
Django template custom form using text area not working
I am using custom template for django form, so i loop over the form fields and create hidden textarea boxes. On hitting the submit button i call the function save code which fills in value of textarea. Earlier i was using input html instead of textarea and it was working fine but I need multiple line value in my form (html input is only single line) so i had to change it to textarea But now probably i am getting 'this field is required' error! (the procedure is same, when i had input tag i did performed document.getelementbyid('id-name').value = required stuff) So i am confused why is it not working with textarea <form method="post" action="{% url 'problem' problem.problem_ID %}"> {% csrf_token %} {% for field in code_form %} <textarea id="{{ field.id_for_label }}" value="{{ field.value }}" style="visibility:hidden;"></textarea> {% endfor %} {% buttons %} <button onclick="save_code()" type="submit" class="btn btn-success center-block">Submit editor</button></td></tr> {% endbuttons %} </form> -
Generating Table of Contents in a Django Blog
How do I dynamically generate table of contents for every post in a Django blog? Thanks in anticipation! -
Running "coverage html" crashes
I'm new to the coverage library for python. But I've immediately encountered a problem and I can't find mention of it on google.. In my virtual environment (pipenv) I do: pipenv install coverage==3.6 coverage run manage.py test <app-name> coverage report coverage html All of them work nicely, I get a nice text report in my shell, but when I run coverage html it crashes... Traceback (most recent call last): File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\parser.py", line 571, in _arcs ch = byte_chunks[byte] KeyError: 22318 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "d:\programming\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\programming\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Win7\.virtualenvs\app-87mb2psT\Scripts\coverage.exe\__main__.py", line 9, in <module> File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 710, in main status = CoverageScript().command_line(argv) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\cmdline.py", line 452, in command_line **report_args) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\control.py", line 615, in html_report return reporter.report(morfs) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 90, in report self.report_files(self.html_file, morfs, self.config.html_dir) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\report.py", line 84, in report_files report_fn(cu, self.coverage._analyze(cu)) File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\html.py", line 164, in html_file missing_branch_arcs = analysis.missing_branch_arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 127, in missing_branch_arcs missing = self.arcs_missing() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 88, in arcs_missing possible = self.arc_possibilities() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\results.py", line 76, in arc_possibilities arcs = self.parser.arcs() File "c:\users\win7\.virtualenvs\app-87mb2pst\lib\site-packages\coverage\misc.py", line 73, in _wrapped setattr(self, … -
Module Not Found Error: No Module Named 'my_project.settings' django gunicorn
I am trying to deploy on heroku but first I am trying to run on my machine but I keep getting the Module Not Found Error. My directory structure looks like this: To make it more clear, I have a folder called 'imperialtheatre' that holds the venv and requirements and inside that folder i have a folder called 'imperialtheatre' which holds the django project with manage.py etc. Why am I getting this error? I am running this command: gunicorn imperialtheatre.imperialtheatre.wsgi:application -t 120 -w 8 -k gevent --max-requests 250 --log-level debug wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "imperialtheatre.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) -
Django Mongoengine leading whitespace being stripped
I have a small issue that I'm struggling to find a solution on. Currently when I recieve the result from a POST with JSON data all leading whitespaces in some of the values as completely gone but all in between the words saved. Is there a setting for MongoEngine that stops this on StringFields? -
Django fail to use data from setting.ini [Errno 11001] getaddrinfo failed
When I set in setting.py the folowing paramters EMAIL_HOST ,EMAIL_PORT , EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_USE_TLS, DEFAULT_FROM_EMAIL And call send_mail every thing works fine but, when I move does paramters to setting.iniI I get error. I am able to see does param correct in my code when I try to view them: raise Exception('EMAIL_HOST -> ' + settings.EMAIL_HOST + 'EMAIL_PORT -> ' + str(settings.EMAIL_PORT) + 'EMAIL_HOST_PASSWORD -> ' + settings.EMAIL_HOST_PASSWORD + 'EMAIL_HOST_USER -> ' + settings.EMAIL_HOST_USER + 'EMAIL_USE_TLS -> ' + str(settings.EMAIL_USE_TLS) ) But when I try to send mail I get the folowing error [Errno 11001] getaddrinfo failed Any suggestion Why when I use does paramters in setting.py it works fine and when I put then in setting.ini I am able to see them but fail to send mail ,what am I doing wrong? I use: Django Version: 1.11 Python Version: 3.5.0 and I call send_mail as folow send_mail("this is the subject", "this is the content", settings.EMAIL_HOST_USER, ["eran3216@gmail.com","eran3216@gmail.com"]) Thanks for the help -
How to use LetsEncrpyt with Nginx and Gunicorn?
I deployed Django to DigitalOcean with the Gunicorn and the Nginx successfully. I want to switch to HTTPS then I have installed LetsEncrpyt with the Digitalocean's tutorial. This my Nginx confguration file: (/etc/nginx/sites-available/[MY_DOMAIN] ) server { listen 80; listen 443; server_name [MY_DROPLETS_IP_ADDRESS]; return 301 $scheme://[MY_DOMAIN].com$request_uri; } server { server_name www.[MY_DOMAIN].com; return 301 $scheme://[MY_DOMAIN].com$request_uri; } server { server_name [MY_DOMAIN].com; access_log off; listen 80; listen 443 ssl; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_certificate /etc/letsencrypt/live/[MY_DOMAIN].com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/[MY_DOMAIN].com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; if ($scheme != "https") { return 301 https://$host$request_uri; } location /static/ { alias /opt/data/static/; } location / { proxy_pass https://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } This is the sudo ufw status verbose output: Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From -- ------ ---- 22/tcp (OpenSSH) ALLOW IN Anywhere 80,443/tcp (Nginx Full) ALLOW IN Anywhere 22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6) 80,443/tcp (Nginx Full (v6)) ALLOW IN Anywhere (v6) This is the sudo systemctl status gunicorn output: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-10-21 16:46:22 UTC; 19min ago The … -
Django Posts on homepage
I am new to Django and I'm stuck on how to display latest blog articles on the homepage. I'm trying to insert them through a snippet which includes {{post.title}} but no luck. Any ideas? -
get No module named urls while rendering template in celery task
The site works ok, but when a celery task is called which renderes template for EmailMultiAlternatives, I get ImportError: No module named urls. If I comment out just one app in settings.py (modal_announcements), it works. The app itself runs ok in the site. This is the urls.py (which could not be found, thoght it apparently exists): from django.conf.urls import patterns, url from mezzanine.conf import settings from modal_announcements.views import announcement urlpatterns = patterns('', url("^announcement/(?P<pk>.*)%s$" % ("/" if settings.APPEND_SLASH else ""), announcement, name='announcement') ) here are the project's urls: if settings.USE_MODELTRANSLATION: urlpatterns += patterns('', url('^i18n/$', 'django.views.i18n.set_language', name='set_language'), url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^chaining/', include('smart_selects.urls')), ) urlpatterns += i18n_patterns("", url("^$", home, name='home'), url(r'^inliner$', inliner, name='inliner'), url(r'^autocomplete/', include('autocomplete_light.urls')), ("^orders/", include("orders.urls", namespace="orders")), ("^shop/", include("shop.urls", namespace="shop")), ("^programs/", include("programs.urls", namespace="programs")), ("^prices/", include("prices.urls", namespace="prices")), ("^tour/", include("tour.urls", namespace="tour")), ("^misc/", include("misc.urls", namespace="misc")), **("^announcements/", include("modal_announcements.urls", namespace="announcements")),** ("^%s/" % settings.EVENT_SLUG, include("mezzanine_agenda.urls")), # ``mezzanine.urls``. ("^", include("mezzanine.urls")), ) urlpatterns += patterns('', url('', include('social.apps.django_app.urls', namespace='social')), ) # Adds ``STATIC_URL`` to the context of error pages, so that error # pages can use JS, CSS and images. handler404 = "mezzanine.core.views.page_not_found" handler500 = "mezzanine.core.views.server_error" if settings.DEBUG: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), ) -
Django form validation not working after adding IntegerField with Radio Widget
I had my form set up and working with no errors, but after I added an IntegerFIeld with a RadioSelect widget the form no longer validates. (Before this I only had CharFields in the model and no widgets) I've searched other similar questions but haven't been able to find anything to solve this issue. At present I just keep getting the error message I coded in views.py. My set up is as follows: views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.utils import timezone from .forms import DiaryEntryForm from .models import DiaryEntry def new_entry(request): if request.method == "POST": form = DiaryEntryForm(request.POST) if form.is_valid(): entry = form.save(commit=False) entry.author = request.user entry.created_date = timezone.now() entry.save() messages.success(request, "Entry created successfully") return redirect(entry_detail, entry.pk) else: messages.error(request, "There was an error saving your entry") return render(request, 'diaryentryform.html', {'form': form}) else: form = DiaryEntryForm() return render(request, 'diaryentryform.html', {'form': form}) forms.py from django import forms from .models import DiaryEntry, FORM_CHOICES class DiaryEntryForm(forms.ModelForm): body = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES) mind = forms.ChoiceField(widget=forms.RadioSelect(),choices=FORM_CHOICES) class Meta: model = DiaryEntry fields = ('body', 'mind', 'insights') models.py from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.conf import settings from django import forms … -
Django Create Comment View pass Subject pk
I'm learning Django and have been beating my head against a wall trying to make a comment form work correctly. Basically what I'm building is a recipe app. This is just practice but the idea would be that someone posts a recipe and other people can comment on it. I have it basically working but I cannot work out how to have the redirect go back to the recipe detail view after the comment has been submitted. If I hard code in the pk it works, I just need to get a hold of that pk! Here is my stuff: Portion of Recipes views.py: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView, View from django.views.generic.detail import SingleObjectMixin from django.core.urlresolvers import reverse_lazy #from comments.models import Comment from .models import Recipe from comments.models import Comment from .forms import RecipeCreateForm from comments.forms import CommentFormTrial from comments.views import CommentCreateView class PersonalRecipeListView(LoginRequiredMixin,ListView): def get_queryset(self): return Recipe.objects.filter(owner=self.request.user) class RecipeDetailView(View): def get(self, request, *args, **kwargs): view = RecipeContent.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentCreateView.as_view() return view(request, *args, **kwargs) class RecipeContent(DetailView): model = Recipe template_name = 'recipes/recipe_detail.html' context_object_name = 'recipe_data' def get_context_data(self, *args, …