Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Removing hardcoded URLs in templates
I know that in a template file I can include this code which will return a list of links {% for q in all %} <ul> <li><a href={% url 'detail' q.id %}>{{ q.question_text }}</a></li> </ul> {% endfor %} Now django will search for the name 'detail' in the urls.py file of my app directory and it will automatically give the value of q.id to that argument. But what if I have a url that contains more that 1 variable. So here I can only give one argument i.e, q.id. But` what if I have to give more than one. Hope I am clear -
Install ODBC Driver heroku
I can not get rid of the error. django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)") Put heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt Create file Aptfile. unixodbc unixodbc-dev python-pyodbc libsqliteodbc https://packages.microsoft.com/ubuntu/16.04/prod/pool/main/m/msodbcsql/msodbcsql_13.1.9.2-1_amd64.deb Create file requirements.txt ... pyodbc django-pyodbc-azure How to fix this error I do not know 4. settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'MARS_Connection': 'True', } } } -
Django How to redirect only example.com to https and *.example.com to http?
I need http://example.com to redirect to https://example.com. Whereas http://www.example.com, http://api.example.com must not redirect i.e, subdomains need not redirect to https. I can understand the configuration here by looking at it. But don't know to move further. Please help me. My configuration so far is: sites-available/default.py upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { server_name example.com www.example.com cloud.example.com api.example.com; # 159.89.161.222; listen 80; return 301 https://example.com$request_uri; } server { server_name example.com www.example.com cloud.example.com api.example.com; listen 443; # <- ssl on; # <- ssl_certificate /etc/ssl/example_cert_chain.crt; # <- ssl_certificate_key /etc/ssl/example.key; # <- #listen 80 default_server; #listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/static/; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; # <- proxy_set_header X-Forwarded-Protocol $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } -
How do I get this url pattern to match?
I'm struggling to match urls with args other than pk. I have a season model that has attributes year and session: class Season(models.Model): season_choices = SEASON_CHOICES current = models.BooleanField(default=False) year = models.IntegerField(_('year'), choices=year_dropdown, default=datetime.datetime.now().year) session = models.CharField(max_length=100, null=True, blank=True, choices=season_choices) and I want to match urls something like season/year/session. I have a listview that lists all seasons: class SeasonList(ListView): model = Season template_name = 'team/season_list.html' def get_queryset(self): s = SeasonModel.objects.filter() return s and a detailview that's supposed to show the season detail. class SeasonDetail(DetailView): model = Season template_name = 'team/season_detail.html' def get_object(self, *args, **kwargs): season = get_object_or_404(Season, year=self.kwargs['year'], session=self.kwargs['session']) return season here are my urls: url(r'^season/$', team_views.SeasonList.as_view(), name='season_list'), url(r'^season/(?P<year>[0-9]{4})/(?P<session>[-\w]+)/$', team_views.SeasonDetail.as_view(), name='season_detail'), and finally my template link: <a href="{% url 'team:season_detail' year=season.year session=season.session %}"> <p>{{ season.year }} {{ season.session }}</p></a> The error I get is get() missing 2 required positional arguments: 'self' and 'request'. It seems almost there... -
Linking information in views with particular records in the HTML page
I have three models: Cars (containing records of the cars): name = models.CharField(max_length=255) Sample records: Car A Car B Car C Features (containing a list with different features that may be of interest): name = models.CharField(max_length=255) primary_feature = models.BooleanField() Sample records: Color, primary_feature = true Number of windows, primary_feature = false Owner, primary_feature = true CarFeatures (containing the features and their values): car = models.ForeignKey(Car, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) value = models.CharField(max_length=255) Sample records: Car | Feature | Value ========================== Car A | color | green Car A | owner | Alice Car B | color | blue Car C | windows | 6 You may wonder about the structure of these models but I'm simplifying here. So let's assume these models make sense. Now the question is: I want to pull up a list with all cars, and I then want to show particular features (those that are primary features) in the table. So my end goal is to get this: Car | Color | Owner ============================= Car A | green | Alice Car B | blue | unknown Car C | unknown | unknown It is important to note that not all features will be available for … -
Django views.py file argument passing
I am using django 2.0.6. My folder structure is like this mysite mysite polls templates polls index.html choice.html Pls consider that all the other files are present. I am not mentioning them here. I have designed a url in the format of 'polls/question/choice'. Here question is a variable which I am passing as a argument. Now I have designed a Question class in models.py from django.db import models from datetime import timedelta from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def recent_publish(self): return self.pub_date >= timezone.now() - timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Now I have pointed my url mapping like this in polls/urls.py path('/choice/',views.choice,name='choice') And in the views file my choice function is like this def choice(request,ques): for q in Question.objects.all(): if q.question_text == ques: break return render(request,'polls/choice.html',{'q':q}) So here I am passing q which is a object of Question class to choice.html Now here is choice.html {% for e in q.choice_set.all() %} <h1>{{e}}</h1>enter code here And this is error I am getting In template C:\Users\Nik\Desktop\mysite\polls\templates\polls\choice.html, error at line 1 Could not parse the remainder: '()' from 'q.choice_set.all()' 1 … -
creating a custom template tags in django
I am new to Django and I am trying to create custom tags in django my custom tag file templatetag/custom_tag.py from django import template from model_file.models import my_Model register = template.Library() @register.simple_tag def get_custom_tag_fn(): return my_Model.objects.all() my html file {% load custom_tag %} {% get_custom_tag_fn as queries %} {% for query in queries %} {{query.val1}} {% endfor %} I am not getting any output or error from this code. Can anyone point where I went wrong. for extra information my model.py looks like from django.db import models from jsonfield import JSONField class my_Model(models.Model): json_my_model_data = JSONField() -
gunicorn: command not found django
Using Docker to install gunicorn, I am unable to to use the gunicorn command. To start Django, I have this line in my docker-compose.yaml: command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn myproject.wsgi -b 0.0.0.0:8000" This results in bash: gunicorn: command not found When I build the Docker images it says gunicorn has been successfully installed. My Dockerfile looks like: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /config ADD requirements.txt /config/ RUN pip install -r /config/requirements.txt RUN mkdir /src; WORKDIR /src I've been using this http://ruddra.com/2016/08/14/docker-django-nginx-postgres/ as a guide. -
Images are not loading all of a sudden in django
I am trying to build a basic blog using django framework. In the posts, i have image field in the Post model. First few posts were added properly. But after i added pagination, the images are not being loaded. Whatever image i add, it is not loading on the screen. models.py: import os from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db import models class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) poster = models.ImageField(upload_to=settings.MEDIA_ROOT); title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_image(self): return os.path.join('/media', self.poster.name) views.py: from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render,get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts_list = Post.objects.filter(status='published') paginator = Paginator(posts_list, 2) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,'blog/post/list.html',{'page':page,'posts':posts}) Template: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1 … -
Please help me to solve MultiValueDictKeyError 'icon'
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Product from django.utils import timezone def home(request): return render(request, 'products/home.html') @login_required def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.POST['icon'] and request.POST['image']: product = Product() product.title = request.POST['title'] product.body = request.POST['body'] product.url = request.POST['url'] product.icon = request.FILES['icon'] product.image = request.FILES['image'] product.pub_date = timezone.datetime.now() product.hunter = request.user product.save() return redirect('home') else: return render(request, 'products/create.html', {'error':'all info is required'}) else: return render(request, 'products/create.html') -
NoReverseMatch (Reverse for ' user_login' not found)
I have a django project called log and an application called basic_app. I created a register form but when I want to create a user_login, I get this error: NoReverseMatch at /basic_app/user_login/ Reverse for ' user_login' not found. ' user_login' is not a valid view function or pattern name. views.py: from django.shortcuts import render from basic_app.forms import UserForm, UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): return render(request, 'basic_app/index.html') @login_required def special(request): return HttpResponse('You are loged in!') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES[ 'profile_pic' ] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username = username, password = password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account Not Active.') else: print('Someone tried to login and … -
Django filter multiple values
Anyone knows why this query_set doesn't return any values for me? Using filter separately, it works perfectly, so it seems .filter().filter() together is the wrong approach to filter for 'either or'. ticket_query = request.event.tickets.filter(status='on-sale').filter(status='paused').prefetch_related('ticket_tax') -
how to setup django haystack queued search with elastic search
I am trying to setup the queued_search but I am unable to find any documentation on how to set this up end-to-end. Here is what I did pip install queued_search Add queued_search to INSTALLED_APPS Here is my serachindex.py class PostCreateModelIndex(indexes.Indexable, QueuedSearchIndex): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/post_text.txt') author = indexes.CharField(model_attr='author__name',faceted=True ) title = indexes.EdgeNgramField(model_attr='title') ... In my settings.py : HAYSTACK_SIGNAL_PROCESSOR = 'queued_search.signals.QueuedSignalProcessor' but on running update_index command its saying raise InvalidBackend("QUEUE_BACKEND not set.") after this error, as I am using elastic search QUEUE_BACKEND = 'elasticsearch' it gives me error raise InvalidBackend("Unable to import QUEUE BACKEND '%s' does not appear to be valid." % BACKEND) queues.InvalidBackend: Unable to import QUEUE BACKEND 'elasticsearch' does not appear to be valid. I don't know what should be QUEUE_BACKEND for elastic search and how to completely setup this. This is the documentation that I found https://github.com/django-haystack/queued_search -
How i may to wrote test for this code?
How i may to wrote test for this code? in views def post(self, request, *args, **kwargs): if 'application/x-www-form-urlencoded' in request.META['CONTENT_TYPE'] and request.is_ajax(): data = request.POST project = feedback.models.Project() auth_group = Group() SUBJECTS = json.loads(data['subjects']) project.project_name = data['project_name'] project.project_domain = data['project_domain'] project.email_support = data['support_email'] project.slack_channel_name = data['slack_channel_name'] project.required_group_id = 3 # TODO if data['teamwork_id']: project.project_id_teamwork = data['teamwork_id'] if data['asana_project_id']: project.asana_project_id = data['asana_project_id'] #TODO have not column if 'project_name' and 'project_domain' and 'support_email' and 'slack_channel_name' in data: auth_group.name = data['project_name'] auth_group.save() project.save() else: HttpResponseServerError() for raw in SUBJECTS: subject = Subjects() subject.name = raw subject.project_id = project.id subject.id_task_list_teamwork = 0000 subject.save() return HttpResponse() Sorry for this question, but i doesn't searched more information, i does'nt use django form, saving data with request. -
django queryset filter with a foreign key of a different model
I am a beginner in DJango ORM and I want to make a queryset as follows this is the model that I have made class Job(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) tags = models.CharField(max_length=255, choices=job_type) recruter_id = models.ForeignKey(User) def __str__(self): return self.title objects = JobManager() class StudentApplication(models.Model): job_fk = models.ForeignKey(Job) student_fk = models.ForeignKey(User) title = models.CharField(max_length = 255) def __str__(self): return self.title in this recruiter can list the job posting and data will be feed in Job Model, and student can apply to the job and that data will be feed in StudentApplication model, with student ID and Job ID as a foreign key.(I have a user model with user_type=1 for student and user_type=2 for recruiter) Now I want to make the query in which I want to show Recruiter the data, that which student have applied for which job posted by him. in the sql, query will be select * from StudentApplication as SA left join Job as j on j.id = sa.job_fk where j.recruiter_id = logged_in_user How can I do similar thing using ORM of DJango -
Django Rest Framework create user profile on creating django user
I have the following models in my CABSERVICE app: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=10) is_rider = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Rider(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE) class Driver(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE) cab = models.OneToOneField('Cab', on_delete=models.CASCADE) class Cab(models.Model): color = models.CharField(max_length=20) rn = models.CharField(max_length=20) available = models.BooleanField(default=True) model = models.CharField(max_length=50) class Booking(models.Model): rider = models.ForeignKey(Rider, on_delete=models.SET_NULL, null=True) driver = models.ForeignKey(Driver, on_delete=models.SET_NULL, null=True) fare = models.IntegerField() src = models.CharField(max_length=100) dest = models.CharField(max_length=100) duration = models.DurationField() Serializers.py from django.contrib.auth.models import User from ca from rest_framework import serializers class UserProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserProfile class RiderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Rider class DriverSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Driver class CabSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Cab class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer() #cab = CabSerializer() class Meta: model = User fields = ('url', 'username', 'email', 'profile') extra_kwargs = { 'password': {'write_only': True}, } def create(self, validated_data): user = User.objects.create_user( username = validated_data['username'], password = validate_data['password'], email = validate_data['email']) profile = validate_data['profile'] user_profile = UserProfile.objects.create(user = user, **profile) if profile['is_rider']: Rider.objects.create(user = user_profile) #else if profile['is_driver']: # cab = validate_data['cab'] # Driver.objects.create(user = user, cab=cab) return user I … -
Django not loading images from media folder
I have written a basic blog code. In that, I am trying to add images which have to be displayed as a cover image on the screen. But The images are not loading. My code: models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db import models class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) poster = models.ImageField(upload_to=settings.MEDIA_ROOT); title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title urls.py: from django.conf import settings from django.conf.urls import url,include from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$',views.post_list,name='post_list'), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) template file: {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} {% for post in posts %} <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8"> <!-- Blog Post --> <div class="card mb-4"> <img class="card-img-top" src="{{ post.poster }}" alt="Card image cap"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text"></p> <a href="#" class="btn btn-primary">Read More &rarr;</a> </div> <div class="card-footer text-muted"> … -
Django 1.8/Python 2.7 to Django 2.0.5/Python 3.6 migration causes broken pipe and apps not ready
I have a Python package that I run from a Django server. The stable version is with Python 2.7/Django 1.8 (master branch in the repo below): https://github.com/shivkiyer/circuit-simulator Everything works fine. I am now trying to migrate to Python 3.6 and Django 2.0.5 (same repo above but branch cli_python3). Things compile and startup without any problems but when I get to the stage where I run my Python function as a multi-thread process, I get the following errors: File "<string>", line 1, in <module> File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "C:\Users\shivk\Documents\misc\electrical\ppe\testing\ppe_webapp_py3\new_env_py3\simulator_interface\simulations\views.py", line 5, in <module> from .models import SimulationCase, SimulationCaseForm, CircuitSchematics File "C:\Users\shivk\Documents\misc\electrical\ppe\testing\ppe_webapp_py3\new_env_py3\simulator_interface\simulations\models.py", line 8, in <module> class SimulationCase(models.Model): File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\site-packages\django\db\models\base.py", line 100, in __new__ Internal Server Error: /new-simulation/ Traceback (most recent call last): File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\shivk\Documents\misc\electrical\ppe\testing\ppe_webapp_py3\new_env_py3\simulator_interface\simulations\views.py", line 2700, in new_simulation simulator_loop.start() File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Users\shivk\Anaconda3\envs\test_py3\lib\multiprocessing\popen_spawn_win32.py", … -
Django: Redirect doesn't work
The checkout time for my event ticket shop is limited to 15 minutes. I now have the issue, once the 15minutes passed, the "timeout" is actually detected and I see "Ticket reservation is too far in the past." as well as the print out in the console "redirect should work". However, the redirect to return redirect('events:index', organizer=organizer, event=event,) doesn't happen. It's somehow just skipped and checkout_page continues to perform all other actions (which it shouldn't). Do you see what I am doing wrong? def check_if_reservation_expired( request, timestamp_of_reservation, organizer, event ): """ * Calculate the latest possible time where tickets are still reserved. * Check that 'created' timestamp of reservation item is not expired. * If expired, error message is being generated and redirect occurs. """ latest_time_before_expired = timezone.now() - timedelta( minutes=settings.MINUTES_TICKET_RESERVATION ) if timestamp_of_reservation < latest_time_before_expired: messages.add_message( request, messages.ERROR, _("Ticket reservation is too far in the past.") ) print("redirect should work") return redirect( 'events:index', organizer=organizer, event=event, ) def checkout_page(request): """ * Check if session and ReservedItem exist. * Generate order_item dict for every ReservedItem entry, that belongs to order_reference. If request.method is 'POST': * Check if ticket reservation is still valid. * Create entries in models OrderItem, Order & ReservedItem. … -
Django - Filter Post System
So I have a model called Blog class Blog(models.Model): tagoptions = ( (u'Project', u'Project'), (u'IT', u'IT'), (u'Robotics', u'Robotics'), . . . (u'-', u'-'), ) user = models.TextField(blank=True, null=True) title = models.CharField(max_length=50, default='') context = models.TextField(max_length=5000, default='') ireceived = models.IntegerField(default=0, blank=True, null=True) personnelneeded = models.IntegerField(default=1) datewritten = models.DateField(default=datetime.date.today, blank=True, null=True) tags = models.CharField(max_length=100, choices=tagoptions, default='-') def __str__(self): return str(self.user) + ": id" + str(self.id) + " - title: " + str(self.title) and a form for filtering the objects using "tags" class FilterOption(forms.Form): tagoptions = ( (u'showall', u'Show All'), (u'Project', u'Project'), (u'IT', u'IT'), . . . (u'-', u'-'), ) tags = forms.ChoiceField(choices=tagoptions, initial="showall") tags.widget.attrs.update({'style' : 'color: black;'}) Then finally in my views I have def posts(request): postshow = Blog.objects.order_by('-id') if request.method == 'POST': form = FilterOption() if form.is_valid(): filteropt = form.cleaned_data['tags'] if filteropt != showall: postshow = Blog.objects.order_by('-id') else: postshow = Blog.objects.filter(tags=filteropt).order_by('-id') else: form = FilterOption() context = {'postshow' : postshow, 'form' : form} return render(request, 'home/posts.html', context) In my mind, when ever I submit the form, It checks if the input says show all or not. If it does then it shows all and if not it filters the object with the inputs. However, the code seems to be stuck at … -
Django Formview & reportlab pdfgen
I have problems with the combination of FormView and pdfgen. In which method do I create the pdf? When I create it in form_valid, I interrupt everything that comes after form_valid. My goal is to save the form, clean the form and then offer the pdf. class SomeView(FormView): form_class = SomeForm template_name = 'appname/someform.html' success_url = reverse_lazy('some-form') def form_valid(self, form): # save in Database form.save() # create PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somepdf.pdf"' p = canvas.Canvas(response) p.drawString(50, 750, "PDF-Content: " + form.cleaned_data['some_field']) p.showPage() p.save() # return super().form_valid(form) return response # returns the PDF but interrupts everything -
NoReverseMatch Django url issue
I am trying to implement a typical url in my django project however i keep getting the error meassage. I have checked my urls, views and html code where i have passed in the KWARGS. I have no clue what went wrong here please help? HTML <div class="sidebar-fixed position-fixed side_nav_bar "> <a class="logo-wrapper waves-effect"> <img src="/" class="img-fluid" alt=""> </a> <div class="list-group list-group-flush"> **<a href="{% url 'userprofile:dashboard' user_profile_detail.slug %}" class="list-group-item {% if request.path == dashboard %}active{% endif %} waves-effect"> <i class="fa fa-pie-chart mr-3"></i>Dashboard </a>** <a href="{% url 'userprofile:profile' user_profile_detail.slug %}" class="list-group-item {% if request.path == profile %}active{% endif %} list-group-item-action waves-effect"> <i class="fa fa-user mr-3"></i>Profile</a> <a href="{% url 'userprofile:watchlist' user_profile_detail.slug %}" class="list-group-item {% if request.path == watchlist %}active{% endif %} list-group-item-action waves-effect"> <i class="fa fa-eye mr-3" aria-hidden="true"></i>WatchList</a> <a href="{% url 'userprofile:blog' user_profile_detail.slug %}" class="list-group-item {% if request.path == blog %}active{% endif %} list-group-item-action waves-effect"> <i class="fa fa-book mr-3" aria-hidden="true"></i>My Blogs</a> <a href="{% url 'userprofile:history' user_profile_detail.slug %}" class="list-group-item {% if request.path == history %}active{% endif %} list-group-item-action waves-effect"> <i class="fa fa-history mr-3" aria-hidden="true"></i>My Browsing History</a> </div> </div> MODELS.PY class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) VIEWS.PY def profile_view(request, slug): user_profile_detail = Profile.objects.get(slug=slug) if request.method == 'POST': form = ProfileForm(request.POST … -
Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp()
I am writing tests where every test case passes except the PUT from django.test import TestCase from rest_framework.test import APIClient class ViewTestCase(TestCase): @classmethod def setUpTestData(cls): cls.client = APIClient() def setUp(self): """setUp() runs before every single test method.""" self.user_data = {'first_name': "John", 'last_name': "Doe", 'email_id': "john@doe.com", 'phone_number': "987654321", 'is_verified': False} self.response = self.client.post( reverse('create'), self.user_data, format='json') def test_api_can_update_user(self): user = User.objects.get() changes = {'first_name': "Johnny"} changed_user_data = {**self.user_data, **changes} response = self.client.put( reverse('details', kwargs={'email': user.email_id}), changed_user_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) This test case fails with response.status_code = 415 whereas if I just move the client initialization from setUpTestData() to setUp() everything passes. def setUp(self): self.client = APIClient() # Test case passed now. ... There are other tests for GET, POST, DELETE all of which pass irrespective of whether client instance is shared(setUpTestData) or not. PS: All api's including PUT works from DRF web api view. -
AttributeError with non-model Field serialization
I have a model: class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30, blank=True) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) phone_number = PhoneNumberField(null=True, blank=True) active = models.BooleanField(default=False) And I nead to serialize creation of User and Model. Idea is to ask User company name while registration, so I have: class CreateUserSerializer(serializers.ModelSerializer): company_name = serializers.CharField(required=True) class Meta: model = User fields = ('id', 'company_name', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] company_name = validated_data['company_name'] user = User.objects.create(username=username, email=email, password=password) Company.objects.create(user=user, name=company_name) return user And i catch error: Got AttributeError when attempting to get a value for field company_name on serializer CreateUserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'company_name'. Anyway objects Company and User are created as i can see it in my admin panel. What am I doing wrong and how can I fix it? Thanks! -
How to store a standing table in Django
I have a World Cup prediction website which is written using the Django framework. Every time a user requests to see the standing table of a particular contest, the standing_stable view looks up all of the users associated with that contest, then loads up all of the associated games as well as users' predictions, then in a for loop compares the predicted result with the actual result and assigns scores based on a rule system. In my experience, when I have more than 10 users signed up in a contest that has at least 30 games or more, the standing_table view gets really slow and it takes more than 5-10 seconds to load the table. I understand that the way I do this is not efficient, and I'd rather do the math once and for all after each game has ended and the users can be referred to those pre-built standing tables. I don't know, however, how to store such table as a Django model. Here's my show_standing view @login_required def show_standing(request, contest): contest = request.user.contests.filter(name=contest).all()[0] users = contest.users.all() rows = [] for user in users: exact_groupstage = utils.get_correct_predictions(user, contest, 'exact', 'groupstage') goal_difference_groupstage = utils.get_correct_predictions(user, contest, 'goal-difference', 'groupstage') winner_only_groupstage = …