Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset to retrieve objects which include all of many-to-many relation
Does anyone could help me with the following: I have the following models: class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() tag = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=50, unique=True) Pretty simple. Now I want to make queryset which will give me all Posts which include all given tags. For example. I have Post1 with tags: 'tag1', Post2 with 'tag2', and Post3 with tags: 'tag1' and 'tag2'. I want to get only Post3. I figure out that it can be achieved by consequent filters like: queryset = Post.object.filter(tag=1).filer(tag=2) However, it is quite unacceptable if I want to retrieve the Post object passing a lot of tags(there will be a lot of chained filters) Please let me now if some better approach exists. Thank you in advance. -
Unable to import another python module same level
I have a file called server.py another called constants.py constants.py is on the same level as server.py Here is what I am doing: server.py import constants def hello_world(): print(BUCKET_NAME) constants.py BUCKET_NAME = 'uw-note-share' I am getting the error: NameError: global name 'BUCKET_NAME' is not defined Even though I am properly importing. What is the issue? -
Django request.GET.get() truncating url string
I am sending a message from chrome extension to django app running locally using chrome.runtime.sendMessage. I am able to capture the message in the url but somehow the whole GET parameter is not being captured. For example, "GET /sensitiveApi/?text=%20%20%20%20The%20Idiots%20-%20Rainbow%20Six%20Siege%20Funny%20Moments%20&%20Epic%20Stuff%20%20We%27re%20back%20with%20some%20Rainbow%20Six%20Siege%20funny%20moments!%20All%20clips%20were%20streamed%20live%20on%20my%20Twitch:%20https://www.twitch.tv/teosgameMore%20Siege%20funny%20moments:%20https://www.youtube.com/playlist?list...Discord:%20https://discord.gg/teoTwitter:%20https://twitter.com/LAGxPeanutPwnerInstagram:%20https://www.instagram.com/photeographPeople%20in%20video:Alex:%20https://twitter.com/AlexandraRose_GKatie:%20https://www.twitch.tv/katielouise_jKatja:%20https://www.twitch.tv/katjawastakenPaddy:%20https://twitter.com/Patward96Smii7y:%20https://www.youtube.com/user/SMii7YSnedger:%20https://www.twitch.tv/snedgerStefan:%20https://twitter.com/lagxsourTortilla:%20https://twitter.com/Tortilla_NZColderMilk:%20https://www.youtube.com/user/ColderMilkColderMilk%20Twitch:%20https://www.twitch.tv/colder_milkColderMilk:%20Twitter:%20https://twitter.com/colder_milkMusic%20used:Outro:%20Come%20Back%20from%20San%20Francisco%20(Instrumental)%20by%20Rameses%20B%20https://www.youtube.com/watch?v=fBWac...%20Go%20check%20out%20his%20music!%20:)%20https://www.youtube.com/RamesesB2 HTTP/1.1" 200 2 this is one response that I want to capture and I a doing request.GET.get('text', '') but all it returns is this, The Idiots - Rainbow Six Siege Funny Moments How do I capture the whole GET parameter? This is how I use chrome.runtime.sendMessage, chrome.runtime.sendMessage({ method: 'GET', action: 'xhttp', url: "http://127.0.0.1:8000/sensitiveApi/?text=", data : text }); -
How to migrate existing table using Django and Python
I need one help. I have one existing mysql table in my localhost database and I need it to migrate using Django and Python. I am explaining my code below. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangotest', 'USER': 'root', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } I am giving my table structure below. Person: id name phone age models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=15) age = models.IntegerField() Actually I am new to Django and Python and here i need to know command which can migrate the existing table. -
Django Allauth modify emails url from 127.0.0.0 to server domain name
Django Allauth modify emails url from 127.0.0.0 to server domain name There is Nginx running on a Ubuntu server. The Django contrib Sites has domain. The emails sent by Django allauth are: Account activate http://127.0.0.1:8080/accounts/confirm-email/Ng:1dJZDR:VG7ds1v0HnQKHKzdgXLHRqfL1w4/ Password reset http://127.0.0.1:8080/accounts/password/reset/key/3-4ms-081fe4fdd341442cd244/ Of course, I would like use domain example.com instead of 127.0.0.1:8080 Could find any thing related to Domain at http://django-allauth.readthedocs.io/en/latest/configuration.html -
Django not posting values from database
I am a beginner at django and python. I am trying to post values from the database to my html template but not able to do so Here is my models file from __future__ import unicode_literals `from django.db import models `class post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField()` `from django.db import models` urls file `from django.conf.urls import url,include from . import views from django.contrib.auth.views import login from django.views.generic import ListView, DetailView from personal.models import post` `urlpatterns = [ url(r'^projects/',views.projects, name='projects'),` while this created a table personal_post in mysql when i reference it in my template projects.html by {{post.title}} or {{projects_post.title}}, it does not return any value. ] Also i have used python the hard way and django unleashed 2017 as part of learning django, any other books for comprehension -
Django POST method in relational database model
I would like to create Object2 for defined user ID in url. GET method in the example shown below works fine, but I can't create POST method. I will be grateful for help. Let's assume I have free sample objects in database: User: id Object1: id user_id Object2: id object1_id In urls.py it looks in this way: url(r'^users/(?P<user_id>[0-9]+)/object2$', views.UserObject2), In models.py: from django.contrib.auth.models import User class Object1(models.Model): user = models.ForeignKey(User) class Object2(models.Model): object1 = models.ForeignKey(Object1) In views.py: @api_view(['GET', 'POST']) def UserObject2(request, user_id): if request.method == 'POST': object2 = Object2.objects.filter(object1_id__user_id=user_id) serializer = Object2Serializer(object2, many=True) if serializer.is_valid(): serializer.save(user_id=user_id) if request.method == 'GET': object2 = Object2.objects.filter(object1_id__user_id=user_id) serializer = Object2Serializer(object2, many=True) I'm trying in this way, but I get error Cannot call .is_valid() as no data= keyword argument was passed when instantiating the serializer instance. -
Getting error while running my APP using python and Django
I am facing one issue. I am new to django and python. While I am running my APP I am getting the below error. __import__(name) File "/opt/lampp/htdocs/mysite/polls/urls.py", line 2, in <module> from . import views File "/opt/lampp/htdocs/mysite/polls/views.py", line 40 ^ SyntaxError: invalid syntax I am explaining my code below. view.py: from __future__ import unicode_literals from django.shortcuts import get_object_or_404, render from django.shortcuts import render from .models import Choice, Question from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,)) My another file url.py is given below. from django.conf.urls import url … -
django - cannot test individual file
As the title, I can run: python manage.py test but I can't run each test file: python manage.py test test.test_abc. AttributeError: 'module' object has no attribute 'test_user_api' Please give me a hand. Thanks -
how to import app.models to sites.py (django)
How Can I Import app.models To sites.py In Django Contrib Folder I Need Use Models In admin Page -
Unit testing django serializers
I'm trying to unit test serializers but I have an issue in getting the expected error messages when I do serializers.is_valid(). Code: serializer.py class RandomSerializer(serializers.Serializer): sno = serializers.IntegerField(required=True) description = serializers.CharField(required=True) def __init__(self, *args, **kwargs): super(RandomSerializer, self).__init__(*args, **kwargs) .... test_serializer.py def test_random_serializer(): val_dict = {'sno': 1, 'description':'test'} serializer = RandomSerializer(val_dict) At this point when I check serializer.is_valid(), this evaluates to False and I get the following error when I check serializer.errors {u'non_field_errors': [u'No input provided']} How can I fix this? Any thoughts? Thanks in advance PS: I also tried serializer = RandomSerializer(data=val_dict) but this does not even populate values to serializers.data -
Open local pdf file in Django
I am new to Django, I am using Windows 7, Django 1.11 and Python 2.5.2, I need to open a PDF file from the local disk, when a button is clicked How can I achieve that? -
Error TemplateDoesNotExist at /
After trying to fix this and looking at every solution I could find for hours, I couldn't fix this problem. I am using Django version 1.11.2. Here is my settings.py: ` import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'climateChange.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'climateChange.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' ` Here is my project setup: project setup -
Django Model Design: User Owned Object Instances, Name Not Unique
I'm relatively new to Django model design and now I want to do something like this. Suppose Alice has three dogs named Road-runner, Pinky, and Kiwi. Bob has one cat called Spinner and also owns Pinky with Alice together. So the name of the object Pet is not unique. A pet can have more than one owner. I think this is many-to-many relationship. Now in my views I would like to list out their own pets. How do I implement it? I know it's related to user auth and foreign keys and stuff, if someone could point out some directions or clear explanation that will be great. I have now: class Pet(models.Model): name = models.CharField(max_length=100) class Owner(models.Model): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) name = models.CharField(max_length=100) Should I put owner = models.ForeignKey(Owner, on_delete=models.CASCADE) in Pet object instead? What if the website is all about pets and owners is just information attached to the pet. Intuitively either way I'm leaning toward putting owner = models.ForeignKey(Owner, on_delete=models.CASCADE) in Pet object is the right way. And then how to restrict users to their own object? If the pet is renamed, it has to be filtered out by it's owner info so that we don't rename … -
django multi-field custom model
Thank you for your help! I'm building a django app on top of Mezzanine, a CMS, and considering ways to build a custom page with multiple sections that a user will be able to edit individually through the admin panel, that would allow them to update each section without having to do it manually in the rich text editor. A way to imagine it would be like this: ./ProjectPage ├── Section 1 │ ├── Image │ └── Text │ ├── Section 2 │ ├── Image │ └── Text │ ├── Section 3 └── Section 4 models.py I created a super simple custom model: from django.db import models from django.utils.translation import ugettext_lazy as _ from mezzanine.pages.models import Page, RichText class ProjectPage(Page, RichText): """ A template for project pages """ include_page = models.BooleanField(_("Include Page"), default=False, help_text=_("Include this page?")) section01_hed = models.CharField('Field One', max_length=255, blank=True) section01 = RichTextField(_("section 01"), blank=True, default=("section 01")) section02_hed = models.CharField('Field Two', max_length=255, blank=True) section02 = RichTextField(_("section 02"), blank=True, default=("section 02")) section03_hed = models.CharField('Field Three', max_length=255, blank=True) section03 = RichTextField(_("section 03"), blank=True, default=("section 03")) section04_hed = models.CharField('Field Four', max_length=255, blank=True) section04 = RichTextField(_("section 04"), blank=True, default=("section 04")) class Meta: verbose_name = _("Project Page") verbose_name_plural = _("Project Pages") But being … -
In django1.8, how can I send Email and see the result?
I would like to implement sending Email functionality in Django1.8. I have posted this question a few hours ago, but there is no answer. This is my snippet code in settings.py file. EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is the code in views.py file. from django.conf import settings from django.core.mail import send_mail from django.shortcuts import render from .forms import SignUpForm, ContactForm def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): form_email = form.cleaned_data.get('email') form_message = form.cleaned_data.get('message') form_full_name = form.cleaned_data.get('full_name') subject = 'Site contact form' from_email = settings.EMAIL_HOST_USER to_email = [from_email] contact_message = "%s: %s via %s"%( form_full_name, form_message, form_email) send_mail(subject, contact_message, from_email, to_email, fail_silently = False) context = { "form" : form } return render(request, "forms.html", context) This is forms.py file. class ContactForm(forms.Form): full_name = forms.CharField(required = False) email = forms.CharField() message = forms.CharField() I have filled the input box with my another yandex mail and Full name, Message. When I click send button, the browser seems to send email to yandex mail. But when I go to the yandex mail box, there is nothing to receive email from gmail. What's the error and how can I handle it? -
How to transition line graph in d3.js ver4 when triggered by selection from dropdown list
I am trying to make a simple web app/dashboard that displays a simple line graph for a specific school that is selected from a dropdown list. It currently works, except when you try to switch back to a school that was already selected. When that happens, the line disappears. I am able to print the data to the console. More generally, I'm unsure that I'm structuring this the best way. For example, should the update() function really be wrapped in the d3.json() method? If it matters, my data is being returned by a Django view that sends a JsonResponse with all school data (i.e. the data filtering to the specific school happens in d3, not Django. Again, is this the right way of approaching this?) // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var parseDate = d3.timeParse("%Y-%y"); // for dates like "2016-17" // set the ranges var x = d3.scaleTime().range([0, width]); var y = d3.scaleLinear().range([height, 0]); // define the line var projection_line = d3.line() .x(function(d) { return x(d.year_short_format); }) .y(function(d) { return y(d.projection); }); … -
Django POST method in relational database model
GET method in the example shown below works fine, but I can't create POST method. I will be grateful for help. Let's assume I have free sample objects in database: User: id Object1: id user_id Object2: id object1_id In urls.py it looks in this way: url(r'^users/(?P<user_id>[0-9]+)/object2$', views.UserObject2), In models.py: from django.contrib.auth.models import User class Object1(models.Model): user = models.ForeignKey(User) class Object2(models.Model): object1 = models.ForeignKey(Object1) In views.py: @api_view(['GET', 'POST']) def UserObject2(request, user_id): if request.method == 'POST': # ??????????????????????????????????? if request.method == 'GET': object2 = Object2.objects.filter(object1_id__user_id=user_id) serializer = TransactionSerializer(object2, many=True) -
Django filter returning 404
I'm trying to get the products that contains a specific word This is my view class DetailProductAPIViewName(generics.RetrieveAPIView): serializer_class = ProductNestedSerializer lookup_field = 'description' def get_queryset(self): description = self.kwargs['description'] print(description) return Product.objects.filter(description__contains=description) And this is my url url(r'^api/product/search/(?P<description>\w{0,50})/$', DetailProductAPIViewName.as_view(),name='list_productsearch_details'), When im printing the description obtained from kwargs, its returning the parameter typed in the url, but in the view its returning HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Thanks for the help -
Call php function in Python
I have this php code: function geraReferenciaMB($chave_api, $nota_de_encomenda, $valor_da_encomenda) { $client = @new SoapClient('https://seguro.eupago.pt/eupagov3.wsdl'); // chamada do serviço SOAP - produção //$client = @new SoapClient('http://replica.eupago.pt/replica.eupagov3.wsdl'); // chamada do serviço SOAP - sandbox $arraydados = array("chave" => $chave_api, "valor" => $valor_da_encomenda, "id" => $nota_de_encomenda);//cada canal tem a sua chave $result = $client->gerarReferenciaMB($arraydados); // verifica erros na execução do serviço e exibe o resultado if (is_soap_fault($result)) { //trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faulstring})", E_ERROR); } else { if ($result->estado == 0) { //estados possíveis: 0 sucesso. -10 Chave invalida. -9 Valores incorretos //colocar a ação de sucesso return $result; // retorna 3 valores: entidade, referência e valor } else { //acao insucesso } } } I need call php function 'geraReferenciaMB' in my Django App. Also I want to pass the three parameters. It's possible? How can i do this? -
Docker Container Shell Tab Hell
Richard Hendricks has infected my Docker container and is adding tabs to every new line of output even after just hitting enter repeatedly , example below. Please help stop this madness! (devops)Daves-MacBook-Pro:database-manager dave$ docker exec -it devops-api sh /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # /var/devops # exit (devops)Daves-MacBook-Pro:database-manager dave$ -
Passing kwargs to Django URL and views
I would like to pass kwargs to my view function through URL. urls.py urlpatterns = [ # ------------- set relations -------------------- url(r'^approve-form/$', views.approve_form, {'content_type':None, 'form_id':None,}, name='approve-form'),] views.py def approve_form(request, content_type=None, form_id=None): return HttpResponse('Working') Now I am using reverse_lazy function to call the url from on of the model instance models.py class FormStatus(models.Model): content_type = models.ForeignKey(ContentType) form_id = models.IntegerField(verbose_name='Form Ref ID') def __str__(self): return "{}".format(self.content_type) def get_approve_link(self): return reverse_lazy("flow-control:approve-form", kwargs={'form_id':self.form_id, 'content_type':self.content_type})' ERROR Reverse for 'approve-form' with arguments '()' and keyword arguments '{'content_type': <ContentType: admin sanc model>, 'form_id': 12}' not found. 1 pattern(s) tried: ['flow-control/approve-form/$'] Is something wrong with the approach or is there any better approach for this ? Thanks in advance. PS: I tried the url documentation but couldn't figure it out. -
Template blocks not appearing in extended templates in Django App
I'm going through the Tango with Django book and came across an error I can't seem to fix. In my Django web app in the templates that extend base.html my title block and side bar block aren't rendering but my body block is. I can't seem to figure out what the problems. Is there something more I need to implement blocks in my project? here is my base.html <!DOCTYPE html> {% load staticfiles %} {% load mango_template_tags %} <html> <head> <title> Mango - {% block title_block %} How to Tango with Django {% endblock %} </title> </head> <body> <div> {% block sidebar_block %} {% get_category_list category %} {% endblock %} </div> <div> {% block body_block %} {% endblock %} </div> <br /> <div> <ul> {% if user.is_authenticated %} <li><a href="{% url 'restricted' %}">Restricted Page</a></li> <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'register' %}">Sign Up</a></li> <li><a href="{% url 'login' %}">Login</a></li> {% endif %} <li><a href="{% url 'add_category' %}">Add New Category</a></li> <li><a href="{% url 'about' %}">About</a></li> <li><a href="{% url 'index' %}">Index</a></li> </ul> </div> </body> </html> here is one of the templates that extends base.html, about.html {% extends 'rango/base.html' %} {% load staticfiles %} {% block title_block %} About … -
In Django 1.8, [Errno -3] Temporary failure in name resolution
I would like to implement sending Email functionality in Django1.8. This is my snippet code in settings.py file. EMAIL_HOST = 'smtp.gmail.com' EMAIL_USER_HOST = 'yourgmail@gmail.com' EMAIL_USER_PASSWORD = 'yourpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is the code in views.py file. from django.conf import settings from django.core.mail import send_mail from django.shortcuts import render from .forms import SignUpForm, ContactForm def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): form_email = form.cleaned_data.get('email') form_message = form.cleaned_data.get('message') form_full_name = form.cleaned_data.get('full_name') subject = 'Site contact form' from_email = settings.EMAIL_HOST_USER to_email = [from_email, 'youotheremail@email.com'] contact_message = "%s: %s via %s"%( form_full_name, form_message, form_email) send_mail(subject, contact_message, from_email, to_email, fail_silently = False) context = { "form" : form } return render(request, "forms.html", context) This is forms.py file. class ContactForm(forms.Form): full_name = forms.CharField(required = False) email = forms.CharField() message = forms.CharField() But when I click submit button, I get message like as follows. gaierror at /contact [Errno -3] Temporary failure in name resolution I have attached img file that shows error. I would like to know how I can handle this issue. Thanks in advance. -
Update quantities in one model with sum of quantities in another
I have two models that need to match on 2 fields using a .filter method. Model B only has 1 unique code, while Model A can have that code multiple times with multiple quantities. So Model B quantity should be the sum for every occurrence of the code in Model A I believe I found the right way to match the fields and get the quantity_sum, but I am unsure of how to add the quantity_sum to the related code in Model B class ModelA(): code = models.IntegerField(default=0) department = models.CharField(max_length=100) quantity = models.IntegerField(default=0) class ModelB(): code = models.IntegerField(default=0) department = models.CharField(max_length=100) quantity = models.IntegerField(default=0) def update_quantity(self): #calculate sum of quantity from ModelA() sum_quantity = ModelA.objects.filter( department=self.department, code=self.code ).aggregate( quantity_sum=Sum(F('quantity')) ) #define save ??