Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: 'AnonymousUser' object has no attribute '_meta' from Pinax/Django-User-Account
I have installed django-user-account accordingly to the documentation and when trying to "sign up" I get 'AnonymousUser' object has no attribute '_meta'. I am not sure why I am getting this error my understanding is that this app should just work after providing the templates from pinax-theme-bootstrap. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/signup/ Django Version: 2.1.1 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'apps.accounts.apps.AccountsConfig', 'account', 'django_extensions', 'pinax.webanalytics', 'django_forms_bootstrap', 'bootstrap4', 'pinax_theme_bootstrap', 'bootstrapform'] Installed 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', 'account.middleware.LocaleMiddleware', 'account.middleware.TimezoneMiddleware'] Traceback: File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/Applications/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/account/views.py" in dispatch 151. return super(SignupView, self).dispatch(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Applications/anaconda3/lib/python3.6/site-packages/account/views.py" in … -
How to display only group members in the Django admin interface
I've been developing a school application for allowing the principal and his teachers to analyze data. The principle needs to add his own people to the system. I think using Django's admin panel would be really good choice for that. Here, I am the superuser and the principal is the staff (who can manage things on the admin panel). As a superuser, I can see the following output: And here is the view of the staff: I also have two groups (school one, school two) in the system: The principal (staff user) John Doe belongs to the group "School Two" which has the permissions of add/change/delete/view users. My question is how can I list the users for a staff to see only his group of people? (no superuser and no other groups' people). Let me share some source code I implemented to for this custom user admin view: The forms.py file: class UserAdminCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('email',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't … -
How to give the user options to create new columns in the database
Is there a by the book way of allowing a user to add columns to a sites database table. For example, if the site was about animals, one user might want to have stats like, 'walks per week' and 'type of food' about their breed of dog. but another user might want to keep track of how much milk their goat is producing. So if i have an 'Animal' class with come basic info. like, 'breed', 'animal name', 'DOB', 'DOD'. But then, in the front end have a form that will allow the users to add all the other columns they would like. Is this possible? hope I've explained it well enough. -
Django All POST requests returns TypeError
I have VPS with Ubuntu 16.04 + Nginx + Python3.6 + Uwsgi + Supervisor + Django I have suveral views like this: def login_view(request): data = {} if request.POST: password = request.POST['password'] plogin = request.POST['login'] try: user = User.objects.get(username=plogin) except User.DoesNotExist: data['error'] = 'DoesNotExist!' return render(request, 'error.html', data) except Exception as e: data['error'] = e return render(request, 'error.html', data) else: if user.check_password(password): login(request, user) else: data['error'] = 'Wrong password!' return render(request, 'error.html', data) data['success'] = 'Success!' return render(request, 'error.html', data) return render(request, 'accounts/login.html', data) And html: <form name='formAuth' action='' method='POST'> {% csrf_token %} <input type='text' name='login' required='required'> <input type='password' name='password' required='required'> <input type='submit'> </form> And if I doing get request (opening the url with this view), it's ok. But if i do POST, it returns me a blank page without any html code. When I checks an uwsgi logs, there was it: TypeError: http header must be encodable in latin1 Yes, site contain cyrillic text, but on my local machine it's ok. I think, this problem related to server settings. p.s. cyrillic locales installed and nginx coding is utf-8 -
Unable to deploy Django app in Google App Engine local test server
I have a working Django app, a simple form handler, that works when I deploy it on Django's development server, but when I try to deploy it on Google App Engine's dev server it fails with the error ModuleNotFoundError: No module named 'main' My app.yaml file looks like: runtime: python37 api_version: 1 handlers: - url: /static static_files: static/ upload: /static - url: / script: views.py I don't have a main.py file, all my logic is in views.py I tried setting script: urls.py but got the same error. How can I simply route the / url to my urls.py file, which by the way looks like this: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home') ] -
Count multiple columns with group by in one query using Django ORM
SELECT COUNT(column1),column1 FROM table GROUP BY column1 SELECT COUNT(column2),column2 FROM table GROUP BY column2 SELECT COUNT(column3),column3 FROM table GROUP BY column3 I Need to merge these three queries into one by using Django ORM. In the above queries column1, column2 and column 3 has the same type of data i.e date so after merging it I want a common date and its count. e.g Count(column1) Count(column3) Count(column3) date_column -
Not getting foreign key data in django api views
Currently I have a site, and I want the user to be able to view their liked articles. I want this to be included in the user api view that is already set up. I have tried the tracks = serializers.StringRelatedField(many=True)that is in the drf docs yet this didn't work. I have also tried the following: from rest_framework import serializers from articles.models import Article, CustomUser,FavoriteArticles class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('title', 'content') class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = '__all__' class FavoriteArticleSerializer(serializers.ModelSerializer): class Meta: model = FavoriteArticles fields = '__all__' class UserProfileSerializer(serializers.ModelSerializer): fav_title = FavoriteArticleSerializer(read_only=False) class Meta: model = CustomUser fields = 'username, git, email, fav_article, fav_title, homepage' and my models: from django.db import models # users/models.py from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver import uuid class ProgrammingLanguage(models.Model): programming_language = models.CharField(max_length=120, null=False, primary_key=True, default="React") def __str__(self): return self.programming_language class Article(models.Model): title = models.CharField(max_length=25, primary_key=True) content = models.TextField() usedfor = models.TextField() url=models.CharField(max_length=200, null=True) article_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="article_programming_language", default="react") score = models.IntegerField(max_length=5, null=0) def __str__(self): return self.title class CustomUser(AbstractUser): username = models.CharField(max_length=50, unique=True, primary_key=True) git = models.CharField(max_length=200, null=True) homepage = models.CharField(max_length=250, null=True) user_programming_language = models.ForeignKey(ProgrammingLanguage, on_delete=models.CASCADE, related_name="most_used_programming_language", default="react") def __str__(self): … -
Change theme style django 2.1
For example i have 2 themes on website. With dark background and light. And i have dropdown in menu to change the theme (or toggle or links). How to change BG and save it for all templates? -
How can i create a website which will make the clone of any website and show it on my domain?
I am working on a WebApp which will download the result of about 70 students from a website in HTML just when university result arrives on the website and then upload the data to my server to show on my Domain. Here is the link for my code https://github.com/robinsdeepak/ResultDownloader Now I'm unable to make any Webapp which will Continuously run the code in a fixed time interval and this is just the first part of my complete project Can you provide a solution to run this code on AWS ? -
Getting a 502 Bad Gateway error on live site after digitalocean one click django install
Summary of problem Getting a “502 Bad Gateway - nginx/1.14.0 (Unbuntu)” error when visiting my live site. Only able to access site through a development server port: python3 manage.py runserver 0.0.0.0:8080 I can then access my site via www.myproject.com:8080 and everything works as it should I believe it has to do with gunicorn's inability to serve my project Technologies python3 django version 2.1.2 Digitalocean Workflow up to the point of error Created a droplet on digital ocean - following this guide https://www.youtube.com/watch?v=Y-CT_l1dnVU&t=958s It seems many people in the comment section of that guide are experiencing the same issue Used digital ocean’s one click install for django Before uploading my project files I checked the live site to see that everything was in order, it was. Uploaded my project files and upgraded django Checked live site again, got the ‘502 Bad Gateway’ error The 502 error Tried switching back to the old version of django, that wasn’t the issue Followed this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 and found that my gunicorn daemon is failing to start sudo nano /etc/systemd/system/gunicorn.service gunicorn.service checked status of gunicorn sudo systemctl status gunicorn failed to start Checked error logs: sudo journalctl -u gunicorn The error logs Any help would … -
Scrapy not writing in postgresql columns
I have a django backend with PostgreSQL database I had made a scraper to fill the database but the problem is scarper is printing the result in the console but not in the database because I can't see them in Django admin interface. Probably I have done something wrong, I am a total beginner in scrapy. Django_app/models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, blank=True) created_on = models.DateTimeField(auto_now_add=True, null=True) song_info = models.TextField(blank=True) content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) # status = models.CharField(max_length=10, choices=STATUS_CHOICE, default='1') status = models.IntegerField( default=1, choices=list(STATUS.items()), verbose_name='Status') Scarper models.py class Post(DeclarativeBase): """Sqlalchemy deals model""" __tablename__ = "Post" id = Column(Integer, primary_key=True) title = Column('title', String) song_info = Column('song_info', String) content = Column('content', String) Pipelines.py from sqlalchemy.orm import sessionmaker from .models import Post, db_connect, create_post_table class ScrapersPipeline(object): """Livingsocial pipeline for storing scraped items in the database""" def __init__(self): """Initializes database connection and sessionmaker. Creates posttable. """ engine = db_connect() create_post_table(engine) self.Session = sessionmaker(bind=engine) def process_item(self, item, spider): """Save deals in the database. This method is called for every item pipeline component. """ session = self.Session() post = Post(**item) try: session.add(post) session.commit() except: session.rollback() raise finally: session.close() return item The-Scraper.py from scrapy import Spider import … -
Issue with (?p<album_id>[0-9]+) in Django 2.1 version
Please help me anyone. Quick I cannot get solution of this problem. Actually I am learning from Django tutorial of 1.9 version But I am using version 2.1 so I think this problem has occur. Anyone please help me quick. -
list object has no attribute copy
feed_obj = self.get_feed_obj(request, kwargs.get('feed_id')) ad_ingredient_id = kwargs.get('ad_ingredient_id') adingredient_obj = AdIngredient.objects.filter(feed_id=feed_obj.id, created_by_id=request.user.id, state=1).first() for data in self.data_formating(request, feed_obj): serializer = self.serializer_class(adingredient_obj,data=data,partial=True) if serializer.is_valid(): serializer.save() else: return Response( { 'success': False, 'detail': serializer.errors }, status=status.HTTP_400_BAD_REQUEST ) return Response( { 'success': True, 'detail': 'Feed Ad Ingredients information updated successfully', 'data': feed_obj.id }, status=status.HTTP_200_OK ) It is not updating data, it keeps brining the older data which is added when the object was created. -
Django v1.10: Getting a JSON of all `Country` models stored in the model `Continent`
I have the following models: from django.db import models MNL = 50 MCL = 5 class Continent(models.Model): """ Fields """ name = models.CharField("name", max_length=MNL, unique=True) code = models.CharField("code", max_length=MCL, default="", unique=True) class Meta: ordering = ['name'] """ Methods """ def __str__(self): return "%s, %s" % (self.name, self.code) class Country(models.Model): """ Fields """ name = models.CharField("name", max_length=MNL, unique=True) capital = models.CharField("capital", max_length=MNL) code = models.CharField("code", max_length=MCL, default="", unique=True) population = models.PositiveIntegerField("population") area = models.PositiveIntegerField("area") continent = models.ForeignKey(Continent, on_delete=models.CASCADE, related_name="countries") class Meta: ordering = ['name'] """ Methods """ def __str__(self): return "%s, %s" % (self.name, self.code) I need to be able to retrieve 2 things in JSON(P): individual Country's capital, population and area fields in the form {"area":<area>,"population":<population>,"capital":<capital_name>} and in the case of a Continent, all of the countries in that continent in the form {"code1":"name1", "code2":"name2",...} I've tried implementing the following views to achieve this: from django.http import HttpResponse, Http404, JsonResponse from django.forms.models import model_to_dict import json from .models import Continent, Country def continent_json(request, continent_code): """ Write your answer in 7.2 here. """ try: print("CONTINENT QuerySet: ", Continent.objects.filter( code__exact=continent_code).values("countries")) continent_data = json.dumps( list(Continent.objects.filter( code__exact=continent_code).values("countries.name","countries.code") ) ) print("CONTINENT JSON: ",continent_data) except Continent.DoesNotExist: raise Http404("Requested continent does not exist.") # If JSONP if … -
Apply Multi attribute search in Django
I am trying to implement Search in my list view for multiple attributes. I don't want to use multiple if-else for each attribute. Here is my current code for search in list view: def get_queryset(self): try: city = self.request.GET['city_name'] user = self.request.GET['user_name'] except: city = '' user = '' if (city != '' or user!=''): userqueries = user.split() cityqueries = city.split() if len(userqueries) and len(cityqueries): qset1 = functools.reduce(operator.__or__, [ Q(first_name__icontains=query) | Q(last_name__icontains=query) for query in userqueries]) qset2 = functools.reduce(operator.__or__, [Q(city__name__icontains=query) for query in cityqueries]) object_list = self.model.objects.filter(qset1 , qset2) elif len(userqueries): qset1 = functools.reduce(operator.__or__, [ Q(first_name__icontains=query) | Q(last_name__icontains=query) for query in userqueries]) object_list = self.model.objects.filter(qset1) elif len(cityqueries): qset1 = functools.reduce(operator.__or__, [Q(city__name__icontains=query) for query in cityqueries]) object_list = self.model.objects.filter(qset1) else: object_list = self.model.objects.all() return object_list I want to merge all these condition in one: if len(userqueries) and len(cityqueries): elif len(userqueries): elif len(cityqueries): -
What is PATH_TO_CREDENTIAL_FILE on Running Django on Kubernetes Engine?
On step 8 of Deploying the app to GKE in Running Django on Kubernetes Engine, it asks you to run this command: kubectl create secret generic cloudsql-oauth-credentials --from-file=credentials.json=[PATH_TO_CREDENTIAL_FILE] What is PATH_TO_CREDENTIAL_FILE supposed to be? I'm a bit lost here. -
Execute a non view function from html code
I want to execute a python function to execute some background calculations when I click on a button. But using this way didn't work as it redirects me to a url which i dont want to do. The button will just be hidden and the python function shall be executed. Html <button type="button" id="reportproblem" qid={{question.id}} class="btn btn-md btn-block btn-info"> {% trans "Rapportera Problem"%} </button> <script type="text/javascript" qid="{{ question.id }}" src="/static/js/report_problem.js"> </script> Javacript: $(document).ready( function () { $("#reportproblem").on("click", function(){ document.getElementById("reportproblem").style.display="none"; var url = "{% url 'quiz:report_problem' question_id=pk %}'"; var id = $(this).attr('qid'); document.location.href = url.replace('pk', id); console.log(url.replace('pk', id)) //$.get(url.replace('pk', id), function (data) {alert("counter updated!");}) -> this one as well redirects to a page }) Any help? -
Get related field in django template
I have two models: class Button(models.Model): title = models.CharField(max_length=100,) anchor = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='anchor', blank=True, null=True,) class Section(models.Model): ... transliterate_name = models.CharField(max_length=100, blank=True, null=True) Now I wanna to get transliterate_name in my template. I use this field as id to article. And i want to assign it to the button id in navigation menu. There is my template: <ul class="navbar-nav"> {% for menu_btn in menu_buttons %} <li class="nav-item"> <a href="#{{ ??? }}" class="nav-link"> {{ menu_btn.title }} </a> </li> {% endfor %} </ul> in my views: class SectionView(ListView): queryset = Section.objects.filter(name_visible=True) context_object_name = 'sections' extra_context = { 'articles': Article.objects.all(), 'menu_buttons': Buttons.objects.all(), } template_name = 'sections/sections.html' Any advise please. -
How to implement Like button in Django with Pure Javascript and Ajax
I'm working on a small blog post. I want to make an Ajax call to change my Like link to Liked and add the user to the database in Django using pure JavaScript with Ajax only. I'm very new to JavaScript and Ajax. Can anyone please help me solve this problem? Any sort of help will be really appreciated. Please provide details. Thank you. ... from django.contrib.auth.decorators import login_required @login_required def like_post(request, slug): post = get_object_or_404(Post, slug=request.POST.get('post_slug')) user = request.user if user in post.likes.all(): post.likes.remove(user) else: post.likes.add(user) total_likes = post.likes.count context = { 'post': post, } In my html file I want to have a simple link(not a buttom), when clicked does the work. <a href="#" id="like" value="{{post.slug}}">Liked({{post.total_likes}})</a> -
Visual studio 2017 django project problem
I'm new to visual studio 2017. I created a new django project and download django 2.0 But the syntax of files created by vs is based on django 1.x version. How to get latest django syntax files. -
Django won't install from Command Prompt or PowerShell
I have Python 3.7. installed. I want to create Django app inside virtual environment using cmd or Powershell. As you can see I get the message which says django is successfully installed. And also when I ask for pip list it also shows on list. But inside Scripts folder there's no django files which need to be there, like django-admin.py. Also there's no django folder inside Lib/site-packages. Python Scripts folder is added to PATH. However, this might give you a clue: When I install Django with Pycharm (not with the steps above), it's all good. But when I ask for list of installed packages with pip list inside shell it won't show django even if I'm in same virtual environment. So I can't create new Django project with django-admin startproject nameofproject -
Unwanted Session duplication in Django
We're using cached_db as our SESSION_ENGINE. We have a session duplication issue, this is the scenario: User 1 is browsing the system. User 2 is browsing and modifying his session. User 1 continuing browsing and finds that his session changed to User's 2 session. If we use SESSION_SAVE_EVERY_REQUEST then it works find but we want to fix this problem from the source. We are using Django 1.6 with Redis -
how to make a live video chatting website using django?
I am currently working on a Django crowdfunding project. I want to add features like live face to face chatting in it, just like Skype. Is it possible in Django? what will I need in order to make this kind of a website? if no: why? if yes: please send a github/youtube tutorials link for that. -
why does queryset values() in django do not access @property
I have a model with @property methods in Django 2.0. When I use Object.objects.all().values() I expected to get also the getters of these property models returned, but unfortunately only the class constants (table fields) are returned. Is this a missing feature or is it intended by design? -
How to add django template variable in <img src>?
I have a Photo model with two fields: title = models.CharField() path = models.CharField() When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file: def gallery(request): photos = Photo.objects.all() return render(request, 'gallery.html', {'photos': photos}) This is the tag in gallery.html: {% loadstaticfiles %} <img src="{%static '{{photo.path}}'%}"/> The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that: src="static/%7B%7B%20photo.path%20%7D%7D" What is the problem? How can I use template variables in src? P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like <img src="{static 'images/image_ex.png'%}"> The photo renders normally.