Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework does not intercept 404 exceptions and outputs HTML instead of JSON
When using Django REST Framework, the documentation mentions that the Http404 exception is intercepted and handled by DRF. However, when I try this in practice, I still get an HTML response from Django: $ curl http://127.0.0.1:8000/foo <h1>Not Found</h1><p>The requested URL /foo was not found on this server.</p> Curiously, method-not-allowed exceptions are caught and turned into JSON correctly. Why isn't it working for 404s? -
Why I have this errror in django
It is following the Django tutorial process I am currently located on par6 I get an error when I click on the list from my web page I looked up where the problem occurred, but I could not find it This is a message from a web browser Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/1// Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:pk>/ [name='detail'] polls/ <int:pk>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] admin/ The current path, polls/1//, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. traceback "GET /polls/1// HTTP/1.1" 404 2703 mysite/polls/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Choice, Question # ... class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): """ Excludes … -
Django connect company with contracts list over VAT?
How can I connect some company with contract list without using pk since when I insert contract they get different pk id. Both models have VAT number but dunno how to connect them... What I have to do, to list all contracts over VAT number for company? Vat number is unique in Company but in Contracts will have more then one VAT number since it can have more then one contract. from company.html <p><a href="{% url 'contracts-detail' company.pk %}">Contracts</a> </p> models.py class Company(models.Model): company = models.CharField(max_length=255) VAT= models.CharField(max_length=11) def __str__(self): return self.company def get_absolute_url(self): return reverse('company-detail', args=[str(self.id)]) class Contracts(models.Model): company = models.CharField(max_length=255) VAT= models.CharField(max_length=11) contractNumber = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.VAT) def get_absolute_url(self): return reverse('contract-detail', args=[str(self.id)]) views.py class CompanyListView(generic.ListView): model = Company context_object_name = 'company_list' queryset = Company.objects.filter() paginate_by = 10 class ContractsListView(generic.ListView): model = Contracts context_object_name = 'contract_list' queryset = Contracts.objects.filter() paginate_by = 10 class ContractsDetailView(generic.DetailView): model = Contracts def contracts_detail_view(request, pk): try: company_id = Contracts.objects.get(pk=pk) except Exception as e: print(str("contracts_detail_view",str(e))) return render( request, 'contracts_detail.html', context={'contract': company_id, } ) urls.py urlpatterns = [ path('', views.index, name='index'), path('com/', views.CompanyListView.as_view(), name='companies'), path('com/<int:pk>', views.CompanyDetailView.as_view(), name='company-detail'), path('cont/', views.ContractsListView.as_view(), name='contracts'), path('cont/<int:pk>', views.ContractsDetailView.as_view(), name='contracts-detail'), ] -
How do we add an extra field with using values from a separate list using django orm in table?
Below is the sample list from which I want to get names of person using their id's. Sample_list = [{'name': 'Name 1', 'id': 1154}, {'name': 'Name 3', 'id': 1156}, {'name': 'Name 3', 'id': 663}] How do we create an extra field in another existing table which has the only id of the user in it? In the end, using this, I want to extract the id, name and few other details. I am using Django=1.9.1 for this. -
Using django context data in vuejs components?
I have a django template where I mounted the vuejs minified js file. If I want to send some data from django to vuejs file, how can I do that? -
django page redirect using jquery ajax with parameters
i want redirect page with ajax how can i do that? // foo.html <button onclick=myFunction()></button> // foo.js myFunction(){ $.ajax({ data:{ foo: bar }, url: {% url 'foo:foo' %}, dataType: 'json', Type: 'GET' }); } # views.py def redirect_page(request): if request.method == 'GET': data = request.GET.get('data') return render(request, 'bar.html', data) this code return string html code how can i do that? -
Coreapi field showing wrong name(data) in swagger
I'm implementing the schema fields by using the method get_schema_fields in DRF. On the swagger UI for the form field instead of the name which ["metrics"] I have given it is displaying the data as the name. Also the model example is also not coming. This is the code def get_schema_fields(self, view): return [ coreapi.Field( name='metrics', location='form', required=True, schema=coreschema.Object(), description='metrics type', ), How can rename that field name to data to metrics also how to display the model sample? -
How to invoke a python selenium script on a button click
On selecting a particular script from drop-down and then click on run, The selenium scripts runs in the server. index.html <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" id="menu1" type="button" data-toggle="dropdown">Lockbox Scripts <span class="caret"></span></button> <ul class="dropdown-menu" role="menu" aria-labelledby="menu1"> <li role="presentation"><a role="menuitem" tabindex="-1" "{% url 'update:index' %}">Commerce Bank</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">BOKF</a> </li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Machias</a></li> <li role="presentation" class="divider"></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">US Bank</a></li> </ul> <br> <br> </div> <div class="container" align="center"> <button type="button" class="btn btn-success">Run</button></div> view.html def lockbox(request): return render(request,'automation/lockbox.html') -
how to do select_related from multiple table
I have 3 models connected in this way: class book(models.Model): id = models.AutoField(primary_key=True) publisher= models.ForeignKey(Publisher, related_name='publisher') class reader(models.Model): publisher= models.ForeignKey(Publisher) class publisher(models.Model): date = models.DateTimeField() and i'm trying to get all the reader of specific book. I tried to do: Reader.objects.select_related(publisher__id='some_id') ang got err: Unable to get repr for <class 'django.db.models.query.QuerySet'> I cant change this model, there is way I can get this information with that models? thanks. -
wsgi.py fails with "No module named 'django'" in virtualenv on apache
I am running a Django webapp on an Amazon Linux EC2 server and have properly installed and verified Apache and mod_wsgi. I configured the Apache config file as shown below and verified that the proper paths are loaded in Python by printing sys.path (shown in error log), however, I keep getting a 500 error with the wsgi.py file failing with a ModuleNotFoundError: No module named 'django' error. I get the same error when using daemon mode in the apache config file. What am I missing? My virtualenv is at /var/www/html/test and my webapp is at /var/www/html/ai_demo_webapp/webapp (this is the location of my manage.py file). I am using Apache 2.2.34 with the pip version of mod_wsgi, and have loaded the wsgi module in the apache config file as LoadModule wsgi_module "/home/ec2-user/.local/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so". wsgi.py import os import sys print(sys.path) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapp.settings") application = get_wsgi_application() Apache Config File WSGIPythonHome /var/www/html/test WSGIPythonPath /var/www/html/ai_demo_webapp/webapp <VirtualHost *:80> WSGIScriptAlias / /var/www/html/ai_demo_webapp/webapp/webapp/wsgi.py <Directory /var/www/html/ai_demo_webapp/webapp/webapp> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </VirtualHost> Apache Error Log when apache is restarted and site is accessed [Mon Jun 11 05:01:46 2018] [notice] SIGHUP received. Attempting to restart [Mon Jun 11 05:01:46 2018] [notice] Digest: generating secret … -
Django view didn't return an HttpResponse object though I added render
The following view method is returning a None and not a HttpResponse object. def upload(request): def get(self, request): photos_list = Images.objects.all() return render(self.request, 'rango/view.html', {'photos': photos_list},) def post(self, request): form = ImagesForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) Even though I am returning a render, why am I getting this? -
highcharts export server json with duplicated key
I am using highcharts in my django project. Chart options are applied in two separate places in my code. There is one theme json that is applied to all charts (Highcharts.setOption(theme)) and while rendering each specific chart, I have a separate json for each chart type that is applied to it separately while rendering. Now I want to use export server to get a png or jpg. because I need both theme and chart-specific options both be sent to server as one single json, I concat the strings, which causes to have two chart or yAxis that the second one overrides the first one. I cannot convert them to python json type because I get following error: {JSONDecodeError}Expecting property name enclosed in double quotes: line 2 column 5 (char 6) because keys in highchart options are not in double quotes. as an example in my theme I have: yAxis: { title: { margin: 20, useHTML: true, style: { color: '#6B6D6E', fontSize: '14px' } }, labels: { useHTML: true, style: { color: '#888888' } }, gridLinesWidth: 1, plotLines: [{ value: 0, width: 1, dashStyle: "Dash", color: "#acacac", zIndex: 4 }] }, and in my chart-specific options I have yAxis: { title: … -
Suppress django signal
I have been struggling with this for a couple of weeks now and I can't seem to get it to work. As you sign up on my website, you are able to create a userprofile and a company. Then, you are able to add members to your company, however the signal just fires everytime and creates empty companies. How do I stop django from doing this? model.py class Companyname(models.Model): company_name = models.CharField(max_length=100, default = '', null=True, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=10000, default = '', null=True, blank=True) def __str__(self): return self.company_name @receiver(post_save, sender=User) def update_user_company(sender, instance, created, **kwargs): if created: Companyname.objects.create(user=instance) if instance.companyname.company_name is '': print("just print this") else: instance.companyname.save() the company gets stored on the userprofile class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default = '', null=True, blank=True) company = models.ForeignKey(Companyname, null=True, on_delete=models.CASCADE) role = models.ForeignKey(Role, null=True, on_delete=models.CASCADE) team = models.ForeignKey(Team, null=True, on_delete=models.CASCADE) company_admin = models.BooleanField(default=False) view.py def add_user(request): if request.method == 'POST': form = AddUserForm(request.POST) if form.is_valid(): company = request.user.userprofile.company_id form.save() user = form.save() user.refresh_from_db() user.userprofile.company_id = company user.userprofile.role = form.cleaned_data.get('role') user.is_active = False user.save() Hope someone can help :) thanks! -
"best" way to get size of a list
My question is, if I have a list list = [1,2,3,4,5,6,7] if I want to know the number of elements in this list, is len(list) or list.count the better option? or does .count only aplies to queries from model by object.filter(id = "HI").count? hope I make myself clear. -
Django migrations does not set default values for Inlinepanel id
I used PostgreSQL with Django,currently i can't insert values to any inline panels in my project because, it throws null value in column "id" violates not-null constraint but it works correctly for two days before Not working table Column | Type | Modifiers --------------+-----------------------+----------- id | integer | not null Expected behaviour Column | Type | Modifiers -----------------+--------------------------+------------------------------------------------------------ id | integer | not null default nextval('highlights_id_seq'::regclass) How to resolve this issue? -
In Django how do I set a certain requests session using angularjs?
I am trying to implement a shopping-cart and hence require to set my requests session using angularjs. For example if I have a number of products and once the user clicks on a certain products 'Add To Cart' button I want to add that product in the session's cart object. The main objective of opting for sessions is that I want this cart to be accessible on the other requested view. Is there any possible solution? Lets consider I have a view named products_list:- def products_list(request): // Somehow set session using Angularjs like below // request.session['cart'] = selected_products_list products = Product.objects.all() return render(request, "browse_products.html", {'products': products}) So that I can access those selected products in an another view like this:- def checkout(request): selected_products = request.session['cart'] return render(request, "checkout.html", {'selected_products': selected_products}) -
PIP Upgrade Permission Denied Windows 10
Python 3.6.5 and (currently) pip 9.0.3 trying to upgrade to 10.0.1. I've checked through various SO threads and nothing quite got me there. When trying to pip install anything and upgrading pip itself, I keep getting this: This is when I tried to install Django which then told me I needed to upgrade pip. Exception: Traceback (most recent call last): File "c:\program files\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files\python36\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files\python36\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36\lib\site-packages\pip\utils__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Access is denied: 'c:\program files\python36\Lib\site-packages\pytz' This is after I tried upgrading pip with 'python -m pip install --upgrade pip' Exception: Traceback (most recent call last): File "C:\Program Files\Python36\lib\shutil.py", line 544, in move os.rename(src, real_dst) PermissionError: [WinError 5] Access is denied: 'c:\program files\python36\lib\site-packages\pip-9.0.3.dist-info\description.rst' -> 'C:\Users\johns\AppData\Local\Temp\pip-f8ej9z71-uninstall\program files\python36\lib\site-packages\pip-9.0.3.dist-info\description.rst' During handling of the above exception, another exception occurred: Traceback (most recent … -
How to populate a django form in a POST request with data from an ajax call?
I'm sending form data via an ajax call after user hits submit button and then handling this request in my views, but the form is empty. How can I populate the form? This is my code: My JS file: var csrftoken = getCookie('csrftoken'); //getCookie is a csrf_token generator var form = $(this).closest('form') $.ajax({ url: form.attr("action"), data: { // if I change this line to data: form.serialize(), it works fine! csrfmiddlewaretoken : csrftoken, form: form.serialize(), }, type: form.attr("method"), dataType: 'json', success: function (data) { //Do a bunch of stuff here } }) My views: def task_edit(request, pk): task = get_object_or_404(Task, pk=pk) if request.method == 'POST': task_form = NewTaskForm(request.POST) # This is empty! else: task_form = NewTaskForm(instance=task) # This for populating the edit modal, works fine! I'm not doing the data: form.serialize() because I need to send additional data with the ajax request. How do I get this working? -
The symbolic link /env/.Python targets a file which does not exist within your site's repository.
Hi guys I'm trying to push my django site to github. I keep getting that error. The repository is viewable here: https://github.com/purplemilk/CLFAKESITE https://github.com/purplemilk/purplemilk.github.io I feel really dumb because I don't exactly know what I'm doing here or if my django site is even actually compatible with github pages. I'm fairly certain /env/ is necessary to build the site. I tried to create a submodule and I also added .nojekyll The commits are all sorts of f****d. If someone could explain what I'm doing wrong and what I should be doing ELI5 style, I would greatly appreciate it. Apologies for formatting errors. -
Django send mail get STARTTLS extension not supported by server (exchange server mail)
I have settings of django.core.mail as below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.mysite.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 25 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I got the error of STARTTLS extension not supported by server when I change EMAIL_USE_TLS = True to EMAIL_USE_TLS = False, I got error as below: SMTP AUTH extension not supported by server -
Django ORM verification of a row in the database
In my site, the buyer search for a product and once he found it he can contact the seller by pressing on a contact button. If the conversation between the two concerning this product exists he should be redirected to the existing conversation, else, we create a new conversation. The conversation is hence defined by two users and a listing. When I try to implement the logic, I am not able to verify both conditions of the existance of the conversation, if the listing exists OR the users exists Django returns that the conversation exists. Here is my code: def create_conversation(request, user_pk1, user_pk2, results_pk): user1 = get_object_or_404(get_user_model(), pk=user_pk1) user2 = get_object_or_404(get_user_model(), pk=user_pk2) results= get_object_or_404(Listing, pk=results_pk) existing_conversation = Conversation.objects.filter(users__in=[user1, user2]).filter(listing=results).values_list('id', flat=True) if existing_conversation.exists(): return HttpResponseRedirect(reverse('conversation:conversation_update', kwargs={'pk':existing_conversation[0]})) else: conv=Conversation() conv.save() conv.listing = results conv.save() conv.users.add(*[user1,user2]) return HttpResponseRedirect(reverse('conversation:conversation_update', kwargs={'pk': conv.pk})) Here is the model of the conversation: class Conversation(models.Model): """ Model to contain different messages between one or more users. :users: Users participating in this conversation. :archived_by: List of participants, who archived this conversation. :notified: List of participants, who have received an email notification. :unread_by: List of participants, who haven't read this conversation.]\[' listing: the listing the conversation is about. read_by_all: Date all … -
django too many redirects after login
I am running: Django==2.0.6 / python==3.6.5 / django-allauth==0.36.0 I have not touched this project in several weeks. I upgraded a number of packages before starting this round of development. I can currently create a new user account and verify the email address used as the username. The user model is "extended" in that I use the email address for the username and have a "Profile" class to hold additional interesting fields. I was once able to create a new account, verify the email address and be taken to a form to fill out that additional interesting info. Now, after email verification there is a noticable pause and then I am told that I have ben redirected too many times. My urls.py looks like: from django.urls import path, re_path from .views import index from .views import profile urlpatterns = [ re_path(r'^', index, name='index'), path('Profile/<uuid:account_number>/edit', profile.Update.as_view(), name="profile-update"), path('Profile/<uuid:account_number>/delete', profile.Delete.as_view(), name="profile-delete"), path('Profile/create', profile.Create.as_view(), name="profile-create"), ] The Profile CBV is: import django.contrib.messages as messages from allauth.account.decorators import verified_email_required from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic import CreateView, UpdateView, DeleteView from Members.forms.profile import ProfileForm from Members.models.profile import Profile import datetime … -
How can I change order of user form?
I'm start first django project. I create user model, but it was not aligned as intended. How can I change order form? and can I cover password with *? Thanks for kind attention :) enter image description here -
def Save(self,*args.**kwargs) method is looping
models.py class Post(models.Model): name = models.CharField(max_length=10) choice = ( ('pending','pending'), ('approve','approve'), ('reject','reject') ) def get_status(self): if self.choice == 'pending': return 'its pending' elif self.choice == 'approve': return 'its approved' else: return 'its rejected' def save(self, *args, **kwargs): k = self.leave_to - self.leave_from print(k) self.leave = k.days super(Post,self).save(*args, **kwargs) but save method is looping twice and subtracting twice from self.leave while i need one loop! Can it be done so! -
Where/how can I execute this function contained in models.py?
I need to execute the get_result() function for every Bet instance models.py class Bet(models.Model): user = models.ForeignKey(User, related_name='bets', blank=True, on_delete=models.CASCADE) match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='bets') team1_score = models.PositiveIntegerField(default=0) team2_score = models.PositiveIntegerField(default=0) result = models.PositiveIntegerField(default=0, null=True) def get_result(self): if (self.match.get_endscore() == self.match.team1) and (self.team1_score > self.team2_score): self.result = 3 elif (self.match.get_endscore() == self.match.team2) and (self.team2_score > self.team1_score): self.result = 3 elif (self.match.get_endscore() == "tie") and (self.team1_score == self.team2_score): self.result = 3 elif (self.match.team1_score == self.team1_score) and (self.match.team2_score == self.team2_score): self.result = 6 else: self.result = 0 return self.result I thought this function out: range = Bet.objects.all() for bet in range: bet.get_result() bet.save() The part that I'm not entirely sure about is where to execute it, or if I can insert the function into a script and with an additional tool execute it a given time (such as an asynchronous process for example). *I'm fairly new at this and I may not have enough expertise to solve it, I'm not even sure if it can be done.