Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'NoneType' object has no attribute 'get' when the object is not type None
I am trying to make an application that allows a view of all of a customer's financial portfolio (in this case that's various stocks, mutual funds, and "other" like a 401k) I have a QuerySet of mutual funds filtered by customer created in my views.py file that I am trying to pass to the html template and render the list. I am running into the error in the title, though: 'NoneType' object has no attribute 'get'. I have verified via print statements that the QuerySet is not of type None, and all the data I want to use is returned correctly when I store it in a variable in my view. I have a everything working for stocks, and it has identical functionality that works just fine, so I can't figure out the difference and why one works but the other doesn't. What would be causing this error? models.py class Stock(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='stocks') symbol = models.CharField(max_length=10) name = models.CharField(max_length=50) shares = models.DecimalField(max_digits=10, decimal_places=1) purchase_price = models.DecimalField(max_digits=10, decimal_places=2) purchase_date = models.DateField(default=timezone.now, blank=True, null=True) def created(self): self.recent_date = timezone.now() self.save() def __str__(self): return str(self.customer) def initial_stock_value(self): return self.shares * self.purchase_price def current_stock_price(self): symbol_f = str(self.symbol) main_api = 'https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=' api_key … -
solve this django problem i saw in heroku when i was deployoing
self.stop() 2019-07-19T20:44:36.871606+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2019-07-19T20:44:36.871764+00:00 app[web.1]: time.sleep(0.1) 2019-07-19T20:44:36.871769+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 245, in handle_chld 2019-07-19T20:44:36.871953+00:00 app[web.1]: self.reap_workers() 2019-07-19T20:44:36.871958+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2019-07-19T20:44:36.872299+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2019-07-19T20:44:36.872338+00:00 app[web.1]: gunicorn.errors.HaltServer: -
Many-to-many relationship based on two optional fields in Django
I have these two objects (left out the irrelevant fields): class Item(models.Model): id = models.BigAutoField(primary_key=True) group_id = models.IntegerField(blank=True, null=True) class Observation(models.Model): item_id = models.IntegerField(blank=True, null=True) group_id = models.IntegerField(blank=True, null=True) Joining them is based on either the Observation's item_id or group_id: SELECT o.* FROM observations o JOIN items i ON (i.id = o.item_id OR i.group_id = o.group_id) ... Can such type of many-to-many relationship be described in the models or do I need to write a custom field? -
Django GraphQL documentation explorer encoding
I have a problem with GraphQL documentation explorer. As you can see on the picture, it has problems with russian text, it shows some, I guess, twice encoded strings like "\\u041c\\u043e\\u0441". How to fix this? -
How do something when i change a field on the django admin for a model
I have currently a boolean field called "is_active" on a model. Whenever i set this field manually in the django admin to True (Initially it it's false) i want it to do a certain action. How can i trigger this field on django to do this certain action when it is set to true? I heard about a save_model() method but i don't know how it works. class Company(models.Model): name = models.CharField(max_length=100, unique=True) is_active = models.BooleanField(default=False) def __str__(self): return self.name -
Django - Connect Users as "Friends"
I am trying to implement the concept of "connected users" in my project. The project I am working on is cfe's 'tweetme' - course on udemy. I changed the below to: accounts/models.py def friends(self, user, limit_to=1): profile = user.profile following = profile.following.all() following = profile.get_following() qs = self.get_queryset().order_by("?").filter(user__in=following).distinct().exclude(id=profile.id)[:1] return qs . So if a user follows another user, he will see him in his friends_list. It works for the users, but not for the posts associated to them. How can I change it so that both users must follow each other to get connected and see the posts of the other user? Can't I just do for user in... infollowing + getfollowing = friends? def toggle_follow(self, user, to_toggle_user): user_profile, created = UserProfile.objects.get_or_create(user=user) # (user_obj, true) if to_toggle_user in user_profile.following.all(): user_profile.following.remove(to_toggle_user) added = False else: user_profile.following.add(to_toggle_user) added = True return added def is_following(self, user, followed_by_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if created: return False if followed_by_user in user_profile.following.all(): return True return False . Is there any way that this toggle_follow function notifies both users? Doesn't need to be async, a pop-up after the next refresh/login would be nice too, for a start. Thank you for any help / resource on this topic -
Is this a good approach to structure my models?
A little bit of info. I want the user to be able to view their feed which contains friends' posts, group posts, etc. I am using django rest framework and providing this feed endpoint to a frontend. My initial thought was just making separate models(tables) per items I needed. Like a UserPost, GroupPost, EventPost, but I feel when trying to consolidate the data it will just be doing a lot of joins and having to stitch together the data. ex) class UserPost(models.Model): # GroupPost, EventPost content = models.TextField(blank=True, default='') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) This didn't seem like a good approach in case we wanted to add post type functionality for other models. My other approach is using intermediate models. Post model is the base and UserPost, GroupPost, EventPost being the intermediate models having a OneToOne relationship to post and GroupPost would have a foreign key (OneToMany) relationship to a Group model. ex) class Post(models.Model): content = models.TextField(blank=True, default='') created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class UserPost(UUID_PK, models.Model): post = models.OneToOneField( Post, null=True, blank=True, related_name='_uPost', on_delete=models.CASCADE) class Group(models.Model): name = models.CharField(max_length=64) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='_groups') members = models.ManyToManyField(settings.AUTH_USER_MODEL) class GroupPost(models.Model): post = models.OneToOneField( Post, null=True, blank=True, related_name='_gPost', on_delete=models.CASCADE) group = … -
Automatic log in to Neo4j on page render
I have Neo4j 3.5.7 Community Edition installed on a server, which will be used for demo purposes. I also have a Django front end. Since Neo4jCE doesn't allow to remove authentication, I would like to automatically log in when rendering the Neo4j browser page. In Django's settings.py I use a bolt URL that has the URL of the DB, the username and password, but when the Neo4j browser page is displayed, the log in form appears, populated with the URL and username. Any help is highly appreciated. -
Should I define get_absolute_url() if the url is not unique?
In the Django framework, models can define a get_absolute_url() method. The method is used to create urls for instances of the model and it is considered a good practice to define and use this method. Is it still a good practice to define this method even if the generated urls are not unique? Example: class Project(models.Model): name = models.CharField(max_length=128) def get_absolute_url(self): return reverse('xxx:project_details', args=(self.id,)) class Item(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=128) def get_absolute_url(self): return reverse('xxx:project_details', args=(self.project.id,)) Currently, the Item instances can only be seen in a list on the project_details page and I intend to keep it that way. The get_absolute_url() method returns the project details url. This means that all Items of the same project return the same url. Is that okay? I found it useful, because some generic views use get_absolute_url() and automatically redirect to the correct page. However, I am new to Django and want to know whether this will cause problems later. -
Handle Microsoft authentication response when application can not be accessed externally
I'm following this tutorial to build a Python Django app that uses Microsoft Graph. I need to authenticate with Azure AD to do that and I have already set up an app registration. The problem is that I'm under a company network that does not permit access from external sources and because of that the Redirect URI used when returning authentication responses (tokens) after successfully authenticating users can not be reached. How can I get the authentication token in that case? Is the callback URL really necessary? -
How to allow user to create an additional option for new question form
I currently have a form to allow a user to post a new question to my site. Currently, the user can only select a category for their question if the category already exists. I would like to allow the user to be able to add a new category for their question if one doesn't already exist. My models class Question(models.Model): title = models.CharField(max_length=200, help_text='Enter a question here') description = models.TextField( max_length=5000, help_text='Type your question description here') date_posted = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) times_favorited = models.PositiveIntegerField( default=0, help_text='Enter the number of times this question has been favorited') category = models.ManyToManyField( "Category", help_text='Enter the category for this question') class Category(models.Model): name = models.CharField( max_length=100, help_text="Chose a category for your question.") My views @login_required def add_new_question(request): from core.forms import QuestionForm from django.views.generic.edit import CreateView # question = get_object_or_404(Question) if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid(): question = form.save(commit=False) question.owner = request.user question.post = Question form.save() return redirect('question-list') else: form = QuestionForm() return render(request, 'core/question_form.html', {'form': form}) My form class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('title', 'description', 'category',) Currently, if there are no existing categories, a user cannot post their question since category is a required field. I … -
I need to make a view counter
I have several articles, and when viewing them, it is necessary to calculate the number of these views for each article. And show how many views on the article For example, I wanted to do this by clicking on the link so that it was added to "view = models.Integerfiels" 1 my models.py from django.db import models from taggit.managers import TaggableManager class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value") tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') font_size = models.IntegerField() def __str__(self): return self.title views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' class ArticleDetail(DetailView): model = Articles template_name = 'news/post.html' urls.py urlpatterns=[ path('', ArticleIndex.as_view(), name='articles_list'), path('<int:pk>/', ArticleDetail.as_view(), name='article_detail'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How does the Count() Method work in this code?
I have this piece of code from the book, I currently go through, don't know how but it works. I would love if someone could explain to me how Count('tags') know that it should only count tags that are connected to post. def post_detail(request, year, day, month, post): post = get_object_or_404(Post, slug = post, publish__year = year, publish__month = month, publish__day = day) comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() post_tags_pks = post.tags.values_list('pk', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_pks).exclude(pk=post.pk) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'comment_form': comment_form,'similar_posts': similar_posts}) -
TinyMCE shows HTML tags, inline CSS codes after saving data
So, I am using TinyMCE as a text editor in my Django application. It shows all HTML tags and inline CSS codes after saving and reloading data. I've used also 'encoding':'xml', then I am getting something like this. -
MultiValueDictKeyError: GET works, POST does not. Why?
I’m trying to process files uploaded by the user in Django 2.2 and it appears GET requests are working however POST is throwing MultiValueDictKeyError. I’m following Vitor Freitas’ glorious Django File Upload Tutorial on YouTube. At roughly 5 minutes in, the instructor begins adding the POST request method. My project is slightly different in terms of some of the names and other apps I am working with. I am running Django 2.2 in my local dev environment and have no intention of deploying this project in the future. I've meticulously checked checked every line several times. When I swap out "POST" for "GET" the MultiValueDictKeyError error disappears and the webpage runs without an error but my Django shell does not print file name and size, as I am expecting. views.py: from django.shortcuts import render from django.views.generic import TemplateView class Home(TemplateView): template_name = "home.html" def upload(request): if request.method == 'POST': uploaded_file = request.FILES['document'] print(uploaded_file.name) print(uploaded_file.size) return render(request, 'upload.html') My upload.html: {% block content %} <h1> Eureka! </h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload file</button> </form> {% endblock %} urls.py: from django.contrib import admin from django.urls import path, re_path # from . import views from posts.views import … -
docker-compose + django + redis - Error 111 connecting to 127.0.0.1:6379. Connection refused
I've looked through this answer and can't figure out how to apply it to my problem, so if the answer is there, clarification would be appreciated. I'm also a noob to docker and docker-compose. I have a simple docker-compose.yml version: '3' services: redis: image: "redis:alpine" web: build: . # current directory command: bash -c "python /app/src/manage.py migrate && python /app/src/manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" When I run this with: docker-compose up everything seems ok: $ docker-compose up Starting hackerspace_redis_1 ... Starting hackerspace_redis_1 ... done Starting hackerspace_web_1 ... Starting hackerspace_web_1 ... done Attaching to hackerspace_redis_1, hackerspace_web_1 redis_1 | 1:C 19 Jul 2019 16:49:10.644 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 19 Jul 2019 16:49:10.644 # Redis version=5.0.5, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 19 Jul 2019 16:49:10.644 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf redis_1 | 1:M 19 Jul 2019 16:49:10.645 * Running mode=standalone, port=6379. redis_1 | 1:M 19 Jul 2019 16:49:10.645 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. redis_1 | 1:M 19 Jul 2019 … -
How to ensure a user tag number (like discord) is not already taken for a given username
I am trying to implement a user tagging system like the number tags that discord users have. I have a randomly generated tag number for each user, and in the event the user decides to change their name I have to make sure that the tag the user already has does not conflict with another user that has the same name and coincidentally same tag. I also was not sure if I should be building the tag checker within my manager or my models file. I was thinking of doing a filter for each user with the same name and query for all the tags of the users with the name and pick a number that isn't taken, but I feel like there might be a more obvious solution to this than that. Heres my models.py for the user from django.db import models from django.contrib.auth.models import User from random import randint class CustomUser(models.Model): email = models.EmailField() alias = models.CharField(max_length=15) user_tag = models.IntegerField(max_length=4) password = models.CharField(max_length=128) profile_pic = models.ImageField() def __str__(self): return f"{self.alias}#{self.user_tag}" def generate_new_tag(self): self.user_tag = randint(1000, 9999) Heres the manager.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ from random import randint class CustomUserManager(BaseUserManager): """ Custom user … -
django_project' is not recognized as an internal or external command, operable program or batch file
I'm trying to make a blog using Django. I created Django project called "django_project" from cmd line and was able to open it in browser, through localhost. in CMD i did -> cd django_project and it worked fine. Then I did python manage.py runserver and it worked too. And after that I couldn't type anything into CMD. I tried typing django_project in new cmd and it read "'django_project' is not recognized as an internal or external command, operable program or batch file". I added django project in environmental variables but it didn't work. Can someone recommend what to do? Thanks a lot -
Refresh field's value periodicly with a background thread
First of all , the title is not 100% accurate since I don't really mind if the solution is going to be with a thread or not. In my django project I have a model with some fields . One of the fields is calculated by a function . So in my models.py it looks like that : class Feed(models.Model): name = models.ForeignKey(Name, on_delete=models.CASCADE, default=0) source = models.ForeignKey(Source, on_delete=models.CASCADE, default=0) def set_status(self, _status=None): # code that i have to implement if status is None: return 'ACTIVE' else: return _status status = property(set_status) What I am trying to do is to be able to re-set the value of the status field periodically and after that to refresh the page so that the user will have the updated status. My main idea was to somehow call a background thread that it is going to wait for a socket message , something like: def wait_for_status_change(self): #setting the socket while True: # socket wait to receive and edit the message accordingly self.set_status(socket_message) Obviously I will have to specify in what specific object of this model I want to change the status field . I tried to use Celery , but I think it is … -
Create a pivot table with ORM Django
I'm working on Django project. This is my model. From that model i would like to display a pivot table. [1]: https://imgur.com/8LXdjer I want to do a pivot table with Django ORM -
F() expression not working with foreign key comparison when None
I'm trying to compare Foreign Keys across a join via F() expression. The QuerySet I've built returns expected results, except when one of ForeignKey's values is None. I'm writing a simple PTO Requesting system. All PTORequests have a profile (the person taking the request) and an approver (assigned at creation, the person who is tasked with approving the request). All profiles have a "manager" who they report to. My goal is to query all PTORequests where the approver is not the profile's manager. class PTORequest(models.Model): profile = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL, related_name='pto_requests') approver = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL, related_name='employee_pto_requests') class Profile(models.Model): manager = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name="reports") My query is: PTORequest.objects.exclude(approver=F("profile__manager")) It should be simple enough, but the results are confusing. >>>pto = PTORequest.create(profile=profile_1, approver=profile_2) >>>profile_1.manager = profile_3 >>>profile_1.save() >>>PTORequest.objects.exclude(approver=F("profile__manager")) # returns 'pto', as expected <QuerySet [<PTORequest: 1>]> >>>profile_1.manager = None >>>profile_1.save() >>>PTORequest.objects.exclude(approver=F("profile__manager")) # returns empty queryset, unexpected <QuerySet []> When setting the manager to None, and the PTORequest's approver to profile_3, the manager is different than the approver, but is not returned in the queryset. Am I misunderstanding something about F() expressions or foreign keys? -
Whats the most efficient way to get posts from groups a user follows?
I'm trying to get post objects from all the groups a user follows. I was able to get a list of groups the user follows and a queryset of all the posts but I'm having difficulty passing the objects to a template. My models: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT) title = models.CharField(max_length = 120, default = '', blank = False) body = models.TextField() class Community(models.Model): title = models.CharField(max_length = 50, default = '', unique = True) followers = models.ManyToManyField(Account, related_name = "community_followers") posts = models.ManyToManyField(Post, blank = True, related_name = "community_posts") def __str__(self): return self.title The view: user = request.user user_communities = user.community_followers.all() queries = [] for community in user_communities: queries.append(community.posts.all()) context['posts'] = queries return render(request, "home/index.html", context) None of the posts get rendered in the template and I cant seem to order them either. I figured there must be something wrong in my implementation. -
General params in Django templates
Django==2.2.3 In some of my cases this is a correct code: {% comment %}First example{% endcomment %} {{ set.name }} {{ set.id }} But for more general use I'd like to use param_a and param_b. Something like this: {% comment %}This will not work. It is just a wish.{% endcomment %} <p>{{ set.param_a }}</p> <p>{{ set.param_b }}</p> And then I'd like to transfer values to the context. Something like this: class SomeListView(TemplateView): template_name = "general_list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["param_a"] = "name" context["param_b"] = "id" return context Is it possible to use context in this case or I'll have to write a custom filter? Anyway, what is the most elegant solution for making an analogue for code in the first example? -
Add placeholder to Django2's AutocompleteSelect widget
I want to add additional attributes to an autocomplete field. # File: admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): search_fields = ['name'] @admin.register(Work) class WorkAdmin(admin.ModelAdmin): autocomplete_fields = ['persons'] The autocomplete widget uses Select2 and I want to add the placeholder attribute (see: select2 data-attributes) to the select element. Where or how do I configure additional attributes for a autocomplete field? Can I do this with a formfield_overrides or do I need to insert JavaScript via class Media in admin.py? I tried to add a form and use it in my admin model. I used this Django test as a template: test_autocomplete_widget.py. This had no effect on the field behavior. I except to see a placeholder text in the autocomplete widget. -
Mail sending through python file
Is there any limit to send mail through outlook using python file?. Like limit on number of mail sent?. After some tries I'm getting error of unsuccessful authentication.