Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-taggit - use added tags
I am trying to get the django-taggit incoporated into my code. Must mention, I am an infant when it comes to Django framework. What I am looking to do is, when a user creats a post, he/she also adds tags to it ( in the long run I am hopint that these will be populated by suggested pre-defined tags. django-taggit is well added to the admin side of the project. I am having a very hard time to implement the user side. The error: AttributeError at /posts/create/ 'Post' object has no attribute 'save_m2m' Request Method: POST Request URL: http://127.0.0.1:8000/posts/create/ Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'save_m2m' Exception Location: C:\Users\internit\Dropbox\Python\codepython\codepython\posts\views.py in create, line 26 Python Executable: C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\Users\internit\Dropbox\Python\codepython\codepython', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python36.zip', 'C:\Users\internit\Dropbox\Python\codepython\env\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env\lib', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts', 'c:\program files (x86)\python36-32\Lib', 'c:\program files (x86)\python36-32\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env', 'C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages'] Server time: Sun, 12 Nov 2017 21:50:26 +0000 Views.py @login_required(login_url='/accounts/login/') def create(request): if request.method == 'POST': if request.POST['title']:#check that the title and the url is included in the request post=Post() post.title= request.POST['title'] post.author= request.user post.pub_date=timezone.datetime.now() post.assignment_body = request.POST['assignment_body'] post.solution_body = request.POST['solution_body'] post.solution_comment = request.POST['solution_comment'] post.tags = request.POST['tags'] post.save() post.save_m2m() return redirect('home') else: return render(request, 'posts/create.html', {'error':'ERROR: Title and URL … -
KeyError when using Django Sessions in deployed application
I am trying to check if there is a logged in user on the home page of my Django app with the following code in my views: def index(request): my_user = request.session.get('currentUser') if my_user: this_user = User.objects.filter(email = request.session['currentUser'])[0] userSearchs = Search.objects.filter(userlist =this_user) context = { 'userMessage' : "Welcome " + request.session['currentUser'], 'userSearch' : userSearchs } else: context = { 'message' : 'Want to save your search history? Click here to login.' } return render(request,'main/index.html',context) I have no issue with program when I run it locally but my deployed version displays a keyError every time new users navigate to the home page. You can check out the exact error by visiting the deployed app here http://54.190.44.1/ If the user logs in and then logs out the error no longer displays and the site functions as expected. Here is my login function in my views: def login(request): response = User.objects.login_user(request.POST) request.session['error'] = False if not response['status']: for error in response['error']: messages.error(request, error) request.session['error'] = True return redirect('login/loginPage') request.session['currentUser']=response['user'][0].email return redirect('/') And here is the logout function: def logout(request): request.session['currentUser'] = '' return redirect('/') I am currently at a loss on where to go from here and would appreciate any suggestions. Thanks! -
In Django Admin, Can I Specify for A New Foreign Key to be Automatically Added When Using a Text Area vs. the Default Dropdown?
I've got two models in my Django app's models: app/models.py class Source(models.Model) name = models.CharField(max_length=255, unique=True) class Relationship(models.Model) first = models.ForeignKey(Source, related_name='first') second = models.ForeignKey(Source, related_name='second') In my app/admin.py I have as follows: # Register Source admin.site.register(Source) # Define Admin View class RelationshipAdmin(admin.ModelAdmin): raw_id_fields = ('source', 'destination') # Register Relationship, Admin View admin.site.register(Relationship, RelationshipAdmin) This creates the classes and registers them in the Django admin, and the raw_id_fields = ('source', 'destination') line is replacing the default dropdown menu for attributes using a ForeignKey within the model. I'm doing this for preference of workflow. I'd like the following functionality to be achieved: When adding a value into one of the Relationship text areas within the Django admin, for that value to be automatically adding to the Source ForeignKey table if the value is unique (like the + button does in the default dropdown). However, Django obviously needs me to tell it I want this done—and I have no idea how to do that. Currently, when I add a value into the text area I've created I get the following error: Select a valid choice. That choice is not one of the available choices. This is clearly indicating that values entered into … -
2 ajax calls at the same time causing issues in views
I'm using django-el-pagination to render 2 querysets (Post and Comment) with ajax. So when I click more posts or more comments, it loads the next batch of objects in the respective queryset. Here is the JS function showing this: $('body').on('click', '.endless_more', function() { console.log($(this).html()); var user_queryset; if ($(this).html() === 'more posts') { console.log('POSTS'); user_queryset = 'user_posts' } else if ($(this).html() === 'more user comments') { user_queryset = 'user_comments'; console.log('COMMENTS'); } else { console.log('none'); } $.ajax({ type: 'GET', url: window.location.href, data: { 'user_queryset': user_queryset } }) }); and here is the view which receives the data from the function (user_posts or user_comments depending on what was clicked). def profile(request, user, extra_context=None): ... page_template = 'profile/profile.html' print('LOAD') if request.is_ajax(): print('Requests:', request.GET) user_queryset = request.GET.get('user_queryset') print('Queryset:', user_queryset) if user_queryset == 'user_posts': page_template = 'profile/user_posts.html' elif user_queryset == 'user_comments': page_template = 'profile/user_comments.html' elif user_queryset == 'user_inbox': page_template = 'profile/user_inbox.html' else: pass else: pass print('Template:', page_template) context = {'user_posts': user_posts, 'user_comments': user_comments, 'page_template': page_template} return render(request, page_template, context) Now, the JS works fine - it sends the correct data depending on what was clicked. So the page_template in the view is successfully updated during the ajax call, however it renders the parent template (profile.html) instead … -
Development Server won't render HTML image
I'm creating a web application using Django in IntelliJ. My HTML file wants an image but somehow my development server will not show the image at all. If I'm directly opening the HTML file and not using the server, I can see the image. I somehow feel it's an IntelliJ issue. I marked the folder as resources root and tried a bunch of things: creating an images folder at the root level and marking the folder as resources root, putting the image in same folder as HTML file; nothing works. HTML Code: {% extends 'base.html' %} {% block head %} <title>Page</title> {% endblock %} {% block body %} <br><br><br> <center><img src="1.png" height="200" width="200"></center> {% endblock %} Project Structure Please help! -
Django - redirect to a view after edit
I have a view that allows me to edit/update a post. The post is the result of filling out a form. This is similar I'm guessing to redirecting to a CMS post after editing. Here's the post view: class PostUpdateView(UpdateView): model = Product form_class = ProductForm template_name = 'edit_product.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return redirect ('products') @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(PostUpdateView, self).dispatch(request, *args, **kwargs) After updating the details in the form it redirects to the 'product' page, whereas I want to redirect to the item just edited. The URL for the items is: url(r'^([0-9]+)/$', views.detail, name = 'detail'), Each post is then a number in the url, such as http://127.0.0.1:8000/13/. I can redirect to the previous page, but takes me back to the edit view, whereas, I want to go back to the actual post view, showing the edit. Hopefully this isn't clear as mud. I get the sense I need to grap the orginating url, then use it once the form is updated so I'm researching that right now. Any guidance gratefully received. -
Why is my makemigrations not creating table
I know this question has been asked before ,but not resolved .When ever i run django makemigrations and migrate, it does not create a my table in the data base .I have done research but yet, do not understand why this is happening and how i can resolve it .Any one has faced such a problem before and resolved it .Please share your solution thanks in davance -
Error in adding django-axes to project
I have installed django axes with this command in cmd : pip install django-axes Then i addes to my setting.py file this parts : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post_app', 'axes', ] 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', 'axes.middleware.FailedLoginMiddleware', ] AXES_LOCK_OUT_AT_FAILURE = False AXES_USE_USER_AGENT = True AXES_COOLOFF_TIME = 1 AXES_LOGIN_FAILURE_LIMIT = 50 Now i want to runserver with this command : python manage.py runserver But i have this error in cmd : Unhandled exception in thread started by <function wrapper at 0x0000000004AA4908> Traceback (most recent call last): File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "D:\python\data\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "D:\python\data\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "D:\python\data\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.ready() File "D:\python\data\lib\site-packages\axes\apps.py", line 9, in ready from axes.decorators import watch_login File "D:\python\data\lib\site-packages\axes\decorators.py", line 3, in <module> from socket import inet_pton, AF_INET6, error ImportError: cannot import name inet_pton Is there any mistake?or any missed work? -
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 …