Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to make a request during field validation
Context I'm trying to save a link to an image in my app. I enforced the "url" format by using a URLField in the DB model but I wanted to go further and validate that the given link really targets an image. To do that, I make a HEAD request to the given url and I check if "image" is contained in the Content-Type header of the response. Issue This works well on my computer but when I upload it to prod it doesn't work anymore. In prod I'm running python 3.5 on Docker, I tried to run it the same way on my computer but I wasn't able to reproduce the bug. When running the incriminated line, the app hangs then crashes and restarts, resulting in a 502 from nginx which is used as a frontend. Here are the logs at the time of the crash : [11] [CRITICAL] WORKER TIMEOUT (pid:14) [14] [INFO] Worker exiting (pid: 14) [20] [INFO] Booting worker with pid: 20 What I tried I tried to do this check in a validator function added to the validators list in the DB model, and I also tried to create a custom form field overriding the … -
How to run OpenEats (Django recipe management) with docker?
I tried to run OpenEats with docker as recommended in the documentation. https://github.com/RyanNoelk/OpenEats/blob/master/docs/Running_the_App.md docker-compose build gives me some warnings: Seeding the database and adding some test data apparently works. But in the browser I get an empty page resulting of the following source: I’m totally new to docker. Could anyone please try to run this container and see if it works? Do you have an idea, what i might be doing wrong? Host system is Lubuntu 16.10 64bit. -
Python - Not able to insert data using python script into sqlite3 db
I have created the 'Sample' table from models.py and i've written script in python to populate some data into the db but the data's are not getting populated in table. Below is the sample python code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','project_name.settings') import os.path import django django.setup() import sqlite3 from abc.models import Sample import requests import json from django.conf import settings base_dir = settings.BASE_DIR URL = "http://xyzasf...." PARAMS = {} r = requests.get(url=URL, params=PARAMS) data = r.json() d_each = {} patterns = ['key1','key2','key3','key4'] for each in range(len(data)): lst = [] for pattern in patterns: lst.append(data[each][pattern]) conn = sqlite3.connect(os.path.join(base_dir, 'db.sqlite3')) print("Opened database successfully") print(lst) c = conn.cursor() sql = ''' INSERT INTO Sample(country_id,country_name,league_id,league_name) VALUES(?,?,?,?) ''' c.execute(sql, lst) conn.commit conn.close -
Sending a post request to a django-server: How to receive the response to a specific method in views.py
I have the following problem. There is a Website using django and I know the source code. In urls.py is a line like: "(r'^test(\d+).html$',test)" and in views.py there is a method: def test(request,id): id = int(id) return HttpResponse("You're looking at the method test with id = %s." % id) How can I send post request, for example with python or javascript, to the website, such that I get the return value of test with an id of my choice? -
Line Chart Template Django
Why does not it show the data? var sin = [], cos = [] for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i)]) cos.push([i, Math.cos(i)]) } <!--start just to show that the data exists--> {% for a in listvalues%} {{a}} -->Data exists {% endfor %} <!--end just to show that the data exists--> var line_data1 = { data : {{listValues}}, color: '#3c8dbc' } var line_data2 = { data : cos, color: '#ff0000' } $.plot('#line-chart', [line_data1, line_data2], { .... if {{listvalues}} is changed by "sin" the data appears correctly. line_data2 appears correctly too. Many thanks -
Django with Sqlite: Q(...)&Q(...) is NOT the same as filter(...).filter(...)
my models.py: class Words(models.Model): sentence = models.ForeignKey(Sentences, related_name='sentence_having_this_word') wordtext = models.CharField( max_length=250) # NOT UNIQUE. words written similarly can appear, as long as the sentences are different. class Sentences(BaseModel): pass Let´s say I have 2 words tree and house. and the sentences: I see a tree and a house. and the tree is in front of the house. I'm looking for the sentences which have these 2 words written inside. I do: Sentences.objects.filter(Q(sentence_having_this_word__wordtext='tree')&Q(sentence_having_this_word__wordtext='house')).all() ==> []. No result but if I do: Sentences.objects.filter(sentence_having_this_word__wordtext='tree').filter(sentence_having_this_word__wordtext='house')).all() ==> I've got the expected result: I see a tree and a house., the tree is in front of the house. I thought Q(...)&Q(...) and filter(...).filter(...) was the same thing? -
Introspection endpoint with django oauth toolkit
Django OAuth toolkit recently added ability to separate the provider and resource servers using Introspection endpoint. However, the documentation is not clear on how to properly achieve this. Anyone who has successfully done this? -
Configure DRF to return errors with an id
Django Rest Framework does it's own validations. For example when creating a user it can return something like this: { "username": [ "A user with that username already exists." ], "password": [ "This field may not be blank." ], "name": [ "This field may not be blank." ] } Is there an easy way to return an id error instead of a text message? And if it is possible where do I find the id errors meanings? For example, if id error 1 is A user with that username already exists. and id error 2 is This field may not be blank.: { "username": [ "1" ], "password": [ "2" ], "name": [ "2" ] } So then in the applications that uses this server can use their own texts (for example, handle different laguages). -
FOREIGN KEY constraint failed delete django
Sorry for my english. I spend 2 days but cant understand why i have error: FOREIGN KEY constraint failed I use pythone 2.7 everething work fine, then i update pythone in pythone 3.5.2 and now when i try delete i have this error. I have model like this: class Auction(models.Model): sealers = models.ForeignKey(User, related_name="sealers", on_delete=models.CASCADE) buyer = models.ManyToManyField(User, related_name='buyer') product_in_auction = models.ForeignKey(Product, related_name='product_in_auction', null=True, blank=True, on_delete=models.CASCADE) name_auction = models.CharField(max_length=64, blank=False, null=False) description = models.TextField(blank=True, null=True, default=None) conf_propose = models.OneToOneField('Propose', null=True, blank=True, related_name='confirm_proposition', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: verbose_name = 'Auction' verbose_name_plural = 'Auctions' def __str__(self): return "%s" % (self.name_auction) class Propose(models.Model): buyer = models.ForeignKey(User, related_name="propositions_of_auction", on_delete=models.CASCADE, null=True, blank=True) auction = models.ForeignKey(Auction, related_name="propositions_of_auction", on_delete=models.CASCADE) bit = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: verbose_name = 'Proposition of the auction' verbose_name_plural = 'Propositions of the auction' def __str__(self): return "%s" % (self.bit) -
Linking one field of a model to another by queryset
I have a session variable that stores the ID of a model. I would now like to filter query sets by the name of the model instead of the id. Currently it only filter by the ID that it compares to the name. How can I get it to use the name instead of ID. Template link <td><a class="btn btn-info" href="{% url 'nodisoapp:select' company.id %}">Working Page</a></td> Urls url(r'^select/(?P<company_id>\d+)/$', views.comp_select, name='select'), view1 def comp_select(request, company_id): request.session['company'] = company_id return redirect('nodisoapp:working',company_id) Filter View class LeadListView(LoginRequiredMixin, generic.ListView): login_url = '/scrty/login/' template_name = "nodiso/leadslist.html" model = models.Leads def get_context_data(self, **kwargs): ctx = super(LeadListView, self).get_context_data(**kwargs) ctx['company']= models.Company.objects.all() return ctx def get_queryset(self): return models.Leads.objects.filter(company=self.request.session['company']) Parent Model class Company(models.Model): user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265, blank=True) tel = models.IntegerField(blank=True, null=True) email = models.EmailField(max_length=265,blank=True) address = models.TextField(blank=True) postal = models.TextField(blank=True) regno = models.CharField(max_length=265,blank=True) vatno = models.CharField(max_length=265,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') Child Model class Leads(models.Model): company = models.ForeignKey(Company) user = models.ManyToManyField(settings.AUTH_USER_MODEL) name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() dateenq = models.DateField(blank=True,null=True) def get_absolute_url(self): return reverse('nodisoapp:leadlist') def __str__(self): return self.name -
Filtering by Foreign model with django-filter
I am trying to display my products on my webpage using django-filter - there are two fields which I would like to filter by: price and product colour. Price is working perfectly however the product colour multiple choice form simply isn't displaying. My models.py: class Product(Page): # My custom fields price = models.DecimalField(max_digits=10, decimal_places=2) product_colours = ParentalManyToManyField('products.ProductColour', blank=True) class ProductFilter(django_filters.FilterSet): product_colours = django_filters.ModelMultipleChoiceFilter(queryset=ProductColour.objects.all(), conjoined=True) class Meta: model = Product fields = ['price', 'product_colours'] My template code: <form action="" method="get"> {{ product_filters.form.as_p }} <input type="submit" /> </form> {% for obj in product_filters.qs %} {{ obj.title }} - &pound;{{ obj.price }} - {% for colour in obj.product_colours.all %}{{ colour }}{% endfor %}<br /> {% endfor %} The result: What am I doing wrong? EDIT I have tried removing the field definition as suggested in this other post, however it still isn't working. -
How I can print python variable to html from django view
If I have some view in django with function def show(request): my_list = listModel.objects.all() return render(request,'template.html', {'newsDetail': my_lis,}) I work in remotehost and can't use terminal. How I can prit may veriable my_list, in order to see what is in it. -
iam new to python getting following error TypeError: must be str, not Tag
program https://imgur.com/uUdqfx1 error https://imgur.com/uUdqfx1 F:\aaa\1\homerun>python hometrial.py product_name: Sunrise Simulator Alarm Clock Traceback (most recent call last): File "hometrial.py", line 33, in print("desc: " + desc) TypeError: must be str, not Tag -
Django. Empty Query list while adding a model object through the shell
I have made a class in my apps models.py file looking like this: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text Through the shell i want to add and instance of this class to the database i enter the shell through the command line using python manage.py shell Then I create the object >>> from polls.models import Question >>> Question <class 'polls.models.Question'> >>> from django.utils import timezone >>> q = Question (question_text='Million Dollar Question', pub_date=timezone.now()) >>> q <Question: Million Dollar Question> When looking to see all objects for Question is get an empty query list, how come? >>> Question.objects.all() <QuerySet []> -
from django templating to full rest?
I want to make my django/html/css website completely in REST (json). The site was developed using django templating to render and send answers to the frontend (html/css). My questions are: how can I handle the url redirection, use json data in the html templates since there will be no django variables. -
django doesnt add users upon submit
Im really stumped on why my models.py wont submit users email and pass to the database when I hit login . It doesnt show up in the Django admin page. Any help will be appreciated. Thank you !! This is what I have so far: views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): print("TESTINGGINGIGNGING") form.save() password=raw_password) #login(request, user) #return HttpResponse("success") return redirect('login.html') else: #this means the form is not valid #so you need to provide the varibles as they were submitted, so the user can change it to proper values form = UserCreationForm(request.POST) else: form = UserCreationForm() return render(request, 'signup_form.html', {'form': form}) signupform.html (form) {% extends 'signup.html' %} {% block body %} <form method = "post" action = "."> {% csrf_token %} {{ form.as_p}} </form> {% endblock %} -
Django Multiple Auth Models
I am working on a project where i need to have 3 types of Users. Admin Vendor Customer I want to be having seperate Models for all three of them Vendor & Customers instead of having a type field in a common User Model. My first approach to this problem was to define all models by sub-classing the AbstractUser model # models.py from django.contrib.auth.models import AbstractUser class Customer(AbstractUser): pass class Vendor(AbstractUser): pass And add a custom Authentication backend to handle the authentication of users based on the request object. # settings.py AUTHENTICATION_BACKENDS = ['backends.CustomAuthBackend'] And my backends.py file will contain the logic to authenticate users and use different models for each one based on the request object. # backends.py from __future__ import print_function class CustomAuthBackend(object): def authenticate(self, request, username=None, password=None): # authenticate user based on request object def get_user(self, user_id): # logic to get user However this does not work and looks like i also need to specifiy the AUTH_USER_MODEL in settings.py which is used for authentication. Is it possible at all.Does Django allow to authenticate from 3 different tables. How can i go ahead with this ? Is there any other approach to this and what should i change … -
Saving a Serializer in Django
When I'm trying to save a model object (its name here is 'RSS) in the view's post() it doesn't get saved, how can I save the model instance 'rss' from the view's post()? In the Serializers class: class RSSSerializer(serializers.ModelSerializer): class Meta: model = RSS fields = ('feed_url', 'website_url', 'description', 'title') def create(self, validated_data): rss = RSS(**validated_data) rss.created_at = datetime.now() rss.last_scan_time = '2001-01-01 00:00:00' rss.id = None return rss In the View class: class RSSList(APIView): def post(self, request): serializer = RSSSerializer(data=request.data) if serializer.is_valid(): print("saving rss post") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Page Not Found django
Why is this happening? I do everything according to the instructions. I study. urls.py from django.conf.urls import url,include from django.contrib import admin from . import views urlpatterns = [ #url(r'^$',views.main,name="main"), url(r'^post/(?P<id>[0-9]+)/', views.post_detail, name='post_detail'), ] views.py from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 # Create your views here. def post_detail(request,id): post = get_object_or_404(Post, pk=id) return render(request, 'main/post_detail.html', {'post': post}) post_detail.html {% extends 'main/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} What to do? Even instead of id put pk, but nothing helps. -
How to show database element after push of a button
I have stored the answers to a test in a database, and I would like the answer of a specific question to appear on the same page, via an alert, after the user pressed the button. What should I do? {% extends 'polls/base.html' %} {% block title %}{% endblock %} {% block content %} {% if prova.questao_set.all %} <h2>Questões do {{prova.tipoProva}} {{prova.anoProva}}</h2> <ul id="questoes"> {% for questao in prova.questao_set.all %} <hr id="linha" /> {% if questao.statusQuestao == '1' %} <h3>Questão {{questao.idQuestao}}</h3> {% if questao.textoQuestao is not None %} <p>{{questao.textoQuestao}}</p> {% endif %} {% if questao.imagemQuestao %} <div class="col-xs-15" align="center"> <img class="img-responsive" id="img1" src="/{{questao.imagemQuestao}}"> <br> </div> {% endif %} {% if questao.imagem2Questao %} <div class="col-xs-15" align="center"> <img class="img-responsive" id="img2" src="/{{questao.imagem2Questao}}"> <br> </div> {% endif %} {% if questao.perguntaQuestao is not None %} <p>{{questao.perguntaQuestao}}</p> {% endif %} {% if prova.questao_set.all %} <ul> {% for opcao in questao.opcao_set.all %} {% if questao.tipoQuestao == '2' %} <form action="" id="opcoes"> <script> function getInputValue(name){ var resposta = document.getElementsByName("respostas"); for(var i = 0; i < resposta.length; i++){ if(resposta[i].checked){ return resposta[i].value; } } return null; } </script> <input type="radio" name="opcao_escolhida" value="A"><label for='{{opcao.aOpcao}}'>a) {{opcao.aOpcao}}</label><br> <input type="radio" name="opcao_escolhida" value="B"><label for='{{opcao.bOpcao}}'>b) {{opcao.bOpcao}}</label><br> <input type="radio" name="opcao_escolhida" value="C"><label for='{{opcao.cOpcao}}'>c) {{opcao.cOpcao}}</label><br> <input type="radio" name="opcao_escolhida" … -
Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations
Django 1.11.7 I installed the python3.6 in the virtual environment. why is it Python/3.5.2 here? and I cannot visit the web 127.0.0.1 (500 internal server error) [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] mod_wsgi (pid=61905): Target WSGI script '/home/ubuntu/.../wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] mod_wsgi (pid=61905): Exception occurred processing WSGI script '/home/ubuntu/.../wsgi.py'. [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] Traceback (most recent call last): [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] File "/home/ubuntu/.../wsgi.py", line 32, in [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] ImportError: No module named 'django' how to solve above problem? Help! thks!!! -
Error while running migrate for django-hordak
I want to use django-hordak in my application for accounting purpose and have followed the official tutorial at http://django-hordak.readthedocs.io/en/latest/. I add the applications "mptt" and "hordak" in INSTALLED_APPS and when I run ./manage.py migrate, it throws following error on the console: Please help! Thanks -
Django - unable to get a foreign key attribute displayed
I am writing a Django webapp. I need some help on why my sidebar is not showing "company.name" which is a foreign key attribute. https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/base.html <h4>{{ request.user.get_full_name }}</h4> <--- can display <h5>{{ request.employee.company.name }}</h5> <--- cannot display https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company) <--- this is the foreign key Here you can see the problem, its not showing the "company name" below https://imgur.com/a/noMoA -
Nginx blocks Apache2 on different port
I have my virtual host on CentOS 6 I've installed Apache2 going through this tutorial And then I've prepared /conf.d/vhost.conf file : <VirtualHost *:8000> ServerAdmin myEmail.gmail.com ServerName testApp ServerAlias 127.0.0.1 DocumentRoot /home/myUser/testApp WSGIScriptAlias /home/myUser/testApp/testApp/wsgi.py ErrorLog /home/myUser/testApp/testApp/error.log CustomLog /home/myUser/testApp/testApp/access.log combined </VirtualHost> and don't know why, but if I try to execute sudo service httpd start Then I see a message: Address already in use: make_sock: could not bind to address 0.0.0.0:443 The 443 port is using by nginx, in Apache2 httpd.conf i selected Listen 8000 So everything should be okay. Does anyone know, what I am doing wrong ? Thanks in advance, -
Django app on apache server with VPS
I've installed mod_wsgi on my apache server. And when I configure WSGIScriptAlias to hello.wsgi to test, it works. But to my Django wsgi.py, it gives 500. In error log it says 'End of script outpt before headers: wsgi.py' What am i missing?