Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to log every request and response if 500 error occurs in django rest framework?
I am using django for rest APIs. I do have a logging code in settings.py. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(asctime)s %(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/tmp/OAuthLog_Production.log', 'formatter': 'simple' }, }, 'loggers': { 'oauth': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, } }, } In the views.py it is being used like this whenever any exception occurs. import logging logger = logging.getLogger("oauth") except Exception as ex: logger.exception(ex) response = helper.generateStandardResponse(ResponseCodes.exception_in_finding_user, "Exception in finding user", data, False); logger.info("get_profile_details : Exception in finding user") return Response(response, status=status.HTTP_200_OK) Since, I am using Elastic beanstalk to host the application I am not returning 500 status code. I am returning custom responses. Even after this there are few 500 errors returned by application. And those are causing environment to "Degrade". I checked my log file but it has errors like this. 2019-11-23 23:53:10,600 ERROR UserProfile matching query does not exist. Traceback (most recent call last): File "/opt/python/current/app/profiles/views.py", line 514, in get_profile_details user_profile_detail = UserProfile.objects.get(mobile1=mobile, account_type=account_type) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/models/query.py", line 385, in … -
Custom Template Tag Render Method Receiving Request Context Instead of Context
This book - https://github.com/PacktPublishing/Django-2-Web-Development-Cookbook-Third-Edition - provides a number of useful custom template tags (except I can't get each to work for the same reason). For example here is the 'try_to_include' custom template tag - class IncludeNode(template.Node): def __init__(self, template_name): self.template_name = template.Variable(template_name) def render(self, context): try: # Loading the template and rendering it included_template = self.template_name.resolve(context) if isinstance(included_template, str): included_template = get_template(included_template) rendered_template = included_template.render(context) except (template.TemplateDoesNotExist, template.VariableDoesNotExist, AttributeError): rendered_template = "" return rendered_template @register.tag def try_to_include(parser, token): """ Usage: {% try_to_include "sometemplate.html" %} This will fail silently if the template doesn't exist. If it does exist, it will be rendered with the current context. """ try: tag_name, template_name = token.split_contents() except ValueError: tag_name = token.contents.split()[0] raise template.TemplateSyntaxError( f"{tag_name} tag requires a single argument") return IncludeNode(template_name) The line - rendered_template = included_template.render(context) throws the error - context must be a dict rather than RequestContext So naturally I checked the django docs - https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#writing-the-renderer Where it doesn't really mention the 'context' parameter. But it seems obvious enough - at least you'd have thought: the 'context' object is the context passed to the template. Indeed later on at section - https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/#setting-a-variable-in-the-context - it gives the example of adding a variable to the … -
'ManyToOneRel' object has no attribute 'verbose_name' error after searching
I have an app where I created a relation between Offer and the Contractor in the Offer model: contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE) Everything works fine except one thing. When I am trying to search through Contractors model using verbose name, I am receiving an Atributeerror: 'ManyToOneRel' object has no attribute 'verbose_name' Searching code below (contractors/views.py): def get(self,request): contractors = self.model.objects.all() if 'search' in request.GET: search_for = request.GET['search'] if search_for is not '': filter = request.GET['filterSelect'] search_in = [field.name for field in Contractor._meta.get_fields() if field.verbose_name==filter] kwargs = {'{0}__{1}'.format(search_in[0], 'contains'): search_for} contractors = self.model.objects.all().filter(**kwargs) Why Am I receiving and error if searching is performed on Constructor model and Constructor model have no fields related to Offer model? How can I fix that? Or how to create searching bar where user can choose where to search from drop down list containing all verbose names of the model fields? -
Django middleware get dynamic url param value
path('<int:id>/', views.client), I have a middleware and I need to get from url. I have try to put inside of __call__(self, request, id), but its not working. anyone know how to achieve this class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request, id): <---error from django.http import HttpResponse return HttpResponse('before middleware' + id) <----error response = self.get_response(request) from django.http import HttpResponse return HttpResponse('after middleware') return response -
How to filter out objects and only show ones where the user is in a ManyToMany field associated with the object Django
So I have this system where my Post object has a ManyToMany field and it's called Saves. So like for example on Reddit you can save a post. So I got it working and users can save posts, and it adds them to the ManyToMany field. However, I want to filter out these posts and only show the posts where said user is in the ManyToMany field. Here is my models.py class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) saves = models.ManyToManyField(User,blank=True,related_name='post_saves') I have the saves field connected to the User model Django provides. And here is my views.py class PostSaveRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): pk = self.kwargs.get("pk") slug = self.kwargs.get("slug") obj = get_object_or_404(Post,pk=pk,slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.saves.all(): obj.saves.remove(user) else: obj.saves.add(user) return url_ So this is all working fine, it adds the user to the ManyToMany field, but now I want to know how I can filter out posts and only display ones where the user is in the ManyToMany field. Here is my saved posts view. class PostSaveListView(ListView): model = Post template_name = 'mainapp/post_saved.html' paginate_by = 10 queryset = models.Post.objects.all() def get(self,request): posts = Post.objects.all() return render(request, self.template_name) def get_queryset(self): return Post.objects.filter().order_by('-published_date') So with Post.objects.all(), how … -
Django redirection malfunctioning behind a load balancer
I have to deploy my Django based app behind a load-balancer that I can't control. E.g https://example.com/loadbalancer/django/. It means all requests targeted to that url (and subsequent additional ones) will be diverted to my Django app. So I worked on the urls.py main file to add a variable named URL_PREFIX = "loadbalancer/django/" : from django.conf import settings from django.contrib import admin from django.urls import include, path, re_path from django.views.generic import TemplateView from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), re_path(r"^api-auth/", include("rest_framework.urls")), re_path(r"^accounts/", include("allauth.urls")), path("", TemplateView.as_view(template_name="landing.html"), name="landing"), ] if settings.URL_PREFIX: urlpatterns = [path(r"{}".format(settings.URL_PREFIX), include(urlpatterns))] So far I deployed the application using Nginx, Supervisor and Gunicorn. Everything works perfectly except when I try to use the confirmation dialog for django-allauth. When the user clicks on the link for confirming his signup e-mail e.g: https://example.com/loadbalancer/django/accounts/confirm-email/MQ:1iYsGH:_O-2PyGzd_FiqrpP-2HvI-pmy2s/ , the form generate a new url https://example.com/loadbalancer/django/accounts/confirm-email/MQ:1iYsGH:_O-2PyGzd_FiqrpP-2HvI-pmy2s/loadbalancer/django/beaver/accounts/login/ where the form try to send data. And that produce an error. What solution would you advise me to take ? I have tried to use an adapter : from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter from decouple import config class BeaverAdapter(DefaultAccountAdapter): def get_email_confirmation_redirect_url(self, request): path = config("URL_PREFIX", default="/giews/food-prices/beaver/") + "accounts/login/" return path But it hasn't worked so … -
How to add auto increment in postgreSQL?
I am new to PostgreSQL. I was trying to create a table and tried to add a primary key and auto increment in same column and came up with an ERROR ERROR: syntax error at or near "SERIAL" LINE 2: upID int SERIAL primary key Below is my Query create table tblIK( upID int SERIAL primary key, upName varchar(100) NOT NULL, upMin varchar(100) NOT NULL, upMax varchar(100) NOT NULL, upYEAR Date NOT NULL, upMi varchar(100)NOT NULL, upIK varchar(100)NOT NULL ) -
how to implement tinymce in django form
Iam making blog app in django and trying to add blog using template and i have implemented front end view as the tinymce text area is showing but on the submission of django form its not being submit so please kindly help , and tell me how can i add blog content using tinyMCE the form is not submitting when iam trying to submit it doesn't do any action enter image description here My template {% extends 'index-base.html' %} {% load static %} {% block content %} <script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"> </script> <center> <h1>ADD BLOG</h1> <form method="POST" action="{% url 'blog:createblog' %}" enctype="multipart/form-data"> {% csrf_token %} {{creationform}} <button type="submit">Add</button> </form> </center> <script> tinymce.init({ selector: 'textarea', plugins: 'print preview fullpage paste importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap quickbars emoticons', imagetools_cors_hosts: ['picsum.photos'], menubar: 'file edit view insert format tools table help', toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen preview save print | … -
AWS Elastic Beanstalk deploy error, PermissionError: [Errno 13] Permission denied
I'd like to ask you a question. I've created an app server with Django and now it's working well in the local. I want to deploy to AWS Elastic Beanstalk, and the server works well until I specify environment variables after eb create. container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: True 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" 03_wsgireplace: command: "cp .ebextensions/wsgi.conf ../wsgi.conf" at .extensions/10_python. eb deploy after entering contact_commands as shown in the code, the server stops working If I check the server log, I will see PermissionError as shown below, but I don't understand what the problem is. If you know how to solve this problem, I'd really appreciate it. 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 674, in exec_module File "<frozen importlib._bootstrap_external>", line 780, in get_code File "<frozen importlib._bootstrap_external>", line 832, in get_data PermissionError: [Errno 13] Permission denied: '/opt/python/current/app/balance10_server/common/urls.py' -
Templating in Django
I am new to Django development and stuck over a issue. From views.py I am sending one list return render(request, 'InsertPage/About.html' , {'list1': list1}) and want to able to perform operations on this list in the html page. Eg list contains 6 items, 3 index per product. I wish to create operations like get the length of the list divide it by 3 and the quotient would be the number of products. And using the same variable (no of products) I was planning to make a for loop to create bootstrap cols and dynamically load the data to the html page. here is the html code - {% for i in list1 %} <h1> {{ k }} </h1> {% endfor %} Would really appreciate the help, also open for suggestions if there is a better way to achieve what i am trying to do. -
How to get author and text from textarea python django? (without javascript)
I should get text from textarea and save code and author this is a link of project https://github.com/AggressiveGhost/python_contester.git I would be grateful if you help solve the problem. thanks in advance -
How do I change requested password to two parameters named as `salt` and `pwdhash` and save it to database in django?
I have a model named as userspasswords. model definition is sth like this: pice of code in models.py class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) I also write a serializer in serializers.py: class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) pwd_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) class Meta: model = UsersPasswords fields = ( 'pk', 'user', 'salt', 'pwdhash', 'inserted_timestamp', 'pwd_creator' ) And also I create a view in views.py: class UserPasswordsDetail(generics.RetrieveUpdateDestroyAPIView): queryset = UsersPasswords.objects.all() serializer_class = UsersPasswordsSerializer name = 'userpasswords-detail' But what is the problem? I intended to change received JSON data from POST method and save it to database like this. received data : user, password manipulate data and save with these fields: pk, user, salt, pwdhash, inserted_timestamp, pwd_creator I have some functions to create hash and salt values and also check password validation using hash and salt. here is all my functions located in myCryptography.py: from hashlib import pbkdf2_hmac from flask import jsonify import jwt import datetime import secrets from app import salt, pwdhash, token def pbkdf2_hmac_sha512(password, salt, iters=2048): # Create hash return pbkdf2_hmac(hash_name='sha512', password=password, … -
Pinax-referrals, how to remove the the domain name from generated referral link and connect it to a view
Hellow guyz, am working on pinax-referrals intergrating it with my Django app. SO far i have managed to generate referral code for every user that has signed up. my problem is that, when i output those refferal link generated for a user, it brings a domain name that is http://example.com/referrals/iqtK4SBNWcE59TN2E2oCbRZcS4ui1sadtO8iHyB3/. How can i remove that domain name(example.com) and replace it with the domain name of my local host domain(127.0.0.1:8000). Also from the above, i have created a view which welcomes a user who has joined using a referral link. i want the view to display the name of the referrer, something like, "welcome, you have been invited by {{ the username of the referrer }} ". But am having a challenge to connect that referral link to my welcome view for the referred users. i have tried to search the pinax-referral documentation but it is not bringing it out clearly for a newbee like me to understand well. any help so please signals.py from allauth.account.signals import user_signed_up from .models import Profile from pinax.referrals.models import Referral @receiver(user_signed_up) def save_profile(sender, **kwargs): request = kwargs['request'] user = kwargs['user'] print(user) referral = Referral.create( user = user, redirect_to = reverse("Home:afterlogin") ) profile = Profile.objects.create(user= user, … -
Django ORM make a relation with tables depending on eah other (circular reference)
Firstly sorry if this question has already been made somewhere (I really couldn't find nothing after 1 hour of research). How can I make a relation with tables depending in each other with Django ORM? e.g. The users belong to a shop and one of those users is the shop boss. Relation Image -
How to fix "abort" issue in Django?
I am doing a project in Django. I have installed python 3.7.5 and Django 1.11. When I try to run the command python manage.py migrate I am getting [1] abort python manage.py migrate The same thing is happening for python manage.py runserver I have been brainstorming for the last 2 days on how to fix this issue but no luck. Can someone help me out here in fixing this issue? -
How to render links in a template for database filtering in django
I am using the "keyone" column in the database to filter entries. So far in the code i have written i am successfully able to render template with "keyone = 2" values. what should i write in a new template file, and how should i modify existing views.py so that when the template file renders it contains a list of links , each link for each value of "keyone" , when i click on the link say "keyone = 2", the selected entries should get rendered in home.html models.py # app/models.py from django.db import models from django.urls import reverse # new class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] keyone = models.IntegerField(default = '777') def get_absolute_url(self): # new return reverse('post_detail', args=[str(self.id)]) views.py def HomePageView(request): key2select = Post.objects.filter(keyone=2) return render(request, 'home.html', { 'key2select': key2select, }) home.html <ul> {% for post in key2select %} <li>{{ post.keyone }}&nbsp &nbsp{{ post.text }}</li> {% endfor %} </ul> -
Add Cart to Order
I want to make a website with Python-Django, in my case i want to add Item in Cart to Order information. Order model contain User information and OrderItem model contain the Item refer to Order information. and after that i want to clear the Cart model.py class Order(models.Model): full_name = models.CharField(max_length=50) address = models.CharField(max_length=50) city = models.CharField(max_length=15) state = models.CharField(max_length=15) postcode = models.CharField(max_length=10) phone = models.CharField(max_length=15) email = models.EmailField() class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='item', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) quantity = models.PositiveIntegerField(default=1) admin.py from .models import Member, Product, Image, Category, Order, OrderItem class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product'] class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'full_name', 'address', 'city', 'state', 'postcode', 'phone', 'email'] inlines = [OrderItemInline] admin.site.register(Order, OrderAdmin) form.py class OrderCreateForm(forms.Form): full_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) address = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) city = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) state = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) postcode = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=True) phone = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=True) email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) views.py from .models import Member, Product, Image, User, OrderItem from .forms import * def checkout(request): cart_items = request.session # Create an empty cart object if it does not exist yet if not cart_items.has_key("cart"): cart_items["cart"] = {} item_ids = cart_items["cart"].keys() products = Product.objects.filter(pk__in=item_ids) cart_total = 0 for item in products: cart_item = … -
No module named 'future'
I'm not good at English, so I'm sorry if you couldn't ask questions well in English. I'm having trouble with deploying Django apps on Heroku. I ran git push heroku master.The result is as follows Enumerating objects: 1020, done. Counting objects: 100% (1020/1020), done. Delta compression using up to 8 threads Compressing objects: 100% (1002/1002), done. Writing objects: 100% (1020/1020), 3.24 MiB | 164.00 KiB/s, done. Total 1020 (delta 92), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.7.5 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting ansicolors==1.1.8 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/53/18/a56e2fe47b259bb52201093a3a9d4a32014f9d85071ad07e9d60600890ca/ansicolors-1.1.8-py2.py3-none-any.whl remote: Collecting cachetools==3.1.1 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/2f/a6/30b0a0bef12283e83e58c1d6e7b5aabc7acfc4110df81a4471655d33e704/cachetools-3.1.1-py2.py3-none-any.whl remote: Collecting certifi==2019.9.11 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 3)) remote: Downloading https://files.pythonhosted.org/packages/18/b0/8146a4f8dd402f60744fa380bc73ca47303cccf8b9190fd16a827281eac2/certifi-2019.9.11-py2.py3-none-any.whl (154kB) remote: Collecting chardet==3.0.4 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 4)) remote: Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) remote: Collecting cycler==0.10.0 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 5)) remote: Downloading https://files.pythonhosted.org/packages/f7/d2/e07d3ebb2bd7af696440ce7e754c59dd546ffe1bbe732c8ab68b9c834e61/cycler-0.10.0-py2.py3-none-any.whl remote: Collecting decorator==4.4.1 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 6)) remote: Downloading https://files.pythonhosted.org/packages/8f/b7/f329cfdc75f3d28d12c65980e4469e2fa373f1953f5df6e370e84ea2e875/decorator-4.4.1-py2.py3-none-any.whl remote: Collecting dj-database-url==0.5.0 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 7)) remote: Downloading https://files.pythonhosted.org/packages/d4/a6/4b8578c1848690d0c307c7c0596af2077536c9ef2a04d42b00fabaa7e49d/dj_database_url-0.5.0-py2.py3-none-any.whl remote: Collecting Django==2.2.7 (from -r /tmp/build_365f03de11037b944e5a8b3a3b35c4c5/requirements.txt (line 8)) remote: Downloading https://files.pythonhosted.org/packages/a0/36/463632a2e9161a7e713488d719a280e8cb0c7e3a66ed32a32e801891caae/Django-2.2.7-py3-none-any.whl (7.5MB) remote: Collecting django-heroku==0.3.1 … -
Unable to run docker with django cookiecutter
I created a project using django cookiecutter. And when I run docker-compose -f local.yml up, "Waiting for PostgreSQL to become available ..." Continues to come out. Starting apasn_postgres_1 ... done Starting apasn_django_1 ... done Attaching to apasn_postgres_1, apasn_django_1 postgres_1 | 2019-11-24 09:33:36.516 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2019-11-24 09:33:36.516 UTC [1] LOG: listening on IPv6 address "::", port 5432 postgres_1 | 2019-11-24 09:33:36.520 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2019-11-24 09:33:36.536 UTC [22] LOG: database system was interrupted; last known up at 2019-11-24 09:30:25 UTC postgres_1 | 2019-11-24 09:33:36.724 UTC [22] LOG: database system was not properly shut down; automatic recovery in progress postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: redo starts at 0/1651070 postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: invalid record length at 0/1651150: wanted 24, got 0 postgres_1 | 2019-11-24 09:33:36.726 UTC [22] LOG: redo done at 0/1651118 postgres_1 | 2019-11-24 09:33:36.739 UTC [1] LOG: database system is ready to accept connections django_1 | Waiting for PostgreSQL to become available... django_1 | Waiting for PostgreSQL to become available... django_1 | Waiting for PostgreSQL to become available... "Waiting for PostgreSQL to become available ..." is repeated. What … -
Deploy django project in own PC using only Apache not Wamp
I am new python developer. I build a web api service using django. I can run the project using pycharm. Now, i want to run the project using Apache. I do not want to use wamp. I searched but everywhere but there is no suitable source. Everyone suggest to do that using wamp server. But i want to use only apache using mod_wsgi. How can i do that ? -
Sorting A Drop Down Menu in Django With Hard-Coded Choices
I have a few drop down menus that are hard-coded into my model. For example: CITIZENSHIP_CHOICES = { (u'Canada', u'Canada'), (u'USA', u'USA'), (u'United Kingdom', u'United Kingdom'), (u'None', u"None of the above"), } COUNTRY_CHOICES = { ('USA', 'USA'),('Canada', 'Canada'),('Israel', 'Israel'),('UK', 'UK'),('Afghanistan', 'Afghanistan'),('Albania', 'Albania'),('Algeria', 'Algeria'),('Andorra', 'Andorra'),('Angola', 'Angola'),('Antigua and Barbuda', 'Antigua and Barbuda'),('Argentina', 'Argentina'),('Armenia', 'Armenia'),('Australia', 'Australia'),('Austria', 'Austria'),('Azerbaijan', 'Azerbaijan'),('Bahamas', 'Bahamas'),('Bahrain', 'Bahrain'),('Bangladesh', 'Bangladesh'),('Barbados', 'Barbados'),('Belarus', 'Belarus'),('Belgium', 'Belgium'),('Belize', 'Belize'),('Benin', 'Benin'),('Bermuda', 'Bermuda'),('Bhutan', 'Bhutan'),('Bolivia', 'Bolivia'),... } SERVICE_LENGTH_CHOICES = { (6, "6"), (12, "12"), (18, "18"), (21, "21"), (24, "24"), (28, "28"), (30, "30"), (32, "32"), (32, "36"), (42, "42") } All of my fields are in the same model in models.py. Each one of the drop down fields looks like this: citizenship = models.CharField(max_length=100, choices=CITIZENSHIP_CHOICES, null=True, blank=True) For some reason though, in my form, the drop downs are in a strange order. I'd like it either to be in the order I entered it in models.py or to order it alphabetically/numerically. 321 Everything I've found online discusses foreign keys, but I'm not using any foreign keys. Any help is much appreciated. -
How to connect MSSQL Server 2008 with Django
I try to connect my local SQL Serer 2008 with Django, when i try to run the django server then shown this error my connection string is- DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 11 for SQL Server', }, } } -
name 'get_object_or_404' is not defined
I am following this tutorial: https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/ Which i am adding onto a simple blog I made so i can add comments Me error: name 'get_object_or_404' is not defined From this method in views.py def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) # post = Post if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'add_comment_to_post.html', {'form': form}) As you see the #hashed out line. This allows me to get to the comment view but then then I get the error that Cannot assign "<class 'blog.models.Post'>": "Comment.post" must be a "Post" instance. That makes sense but wanted to point that out. I assume this is a database issue? my models.py: from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): comment = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') def __str__(self): return self.comment class Meta: ordering = ['created_on'] Everything in … -
Materialize css adds ::after to input labels and does not display them
Screenshot of the form and inspect page I'm making forms with django for user input. I added materialize css styles. However, the latest removes labels from several inputs in the form as on screenshot. When i disable materialize css, labels display normally. As i've seen, materialize css adds "::after" to some labels. I've tried specifying labels directly in django, however it didn't help. Whan can i do to display them? Django template: {% load static %} {% block content %} <div class="container"> <form method="post"> <h3>Add a new appointment</h3> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} <div class="right-align total"> <button type="submit" class="waves-effect waves-light btn green submit">Submit</button> </div> </form> </div> <script> $(document).ready(function() { $('select').material_select(); }); </script> {% endblock content %} in layout.html i specify <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> -
Alternative to apt-get install packages on pythonanywhere?
I'm trying to deploy a django project to pythonanywhere. I'm using this package in my project: https://github.com/algoo/preview-generator In order for preview-generator to work it has the following requirements: apt-get install zlib1g-dev libjpeg-dev python3-pythonmagick inkscape xvfb poppler-utils libfile-mimeinfo-perl qpdf libimage-exiftool-perl ufraw-batch ffmpeg Is there any way for me to install these required packages on the pythonanywhere server? I read that the best you can do is make a request to the pythonanywhere team to have the packages added in future versions. If this is still the case can anyone recommend a host that allows you to install these kinds of modules?