Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /admin/location __str__ returned non-string (type NoneType)
I have a piece of code and each time I want to render the frontend template, it gives just 'None' at every segment such as name, phone etc. When I want to see it from admin page, it throws an error: TypeError at /admin/accounts/student/2/change/ str__ returned non-string (type NoneType) I'm completely new to Django. If anyone could help me, I'll be very grateful. Thanks in advance. Here is my models.py: from django.contrib.auth.models import User # Create your models here. class Student(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Books(models.Model): CATEGORY = ( ('Physics', 'Physics'), ('Chemistry', 'Chemistry'), ('Mathematics', 'Mathematics'), ) name = models.CharField(max_length=200, null=True) author = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Issue(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) student = models.ForeignKey(Student, null=True, on_delete= models.SET_NULL) book = models.ForeignKey(Books, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, … -
Is it possible to use the same database for two Django projects containing different models?
We planned for two Django projects. Say, Project-1 contains Model A and B. and Other Project-2 contains Model C and D. But I am afraid if it possible or not as I am new in the Django World. Your suggestions would be highly appreciated. -
<int: category> shows up as string in url
I was doing endpoint and using two pk in url. But when using <int: category> it still displays as a string path('<int:pk>/categories/<int:category>/', views.Category.as_view({'put': 'update'})) How do I change string to int? -
Deploy Django project on Hostinger VPS [closed]
I have purchased Hostinger VPS plan. I have a django project ready and running on my local host server. How do I setup the environment and run my project online. Any links or tutorials that would guide me step by step are also appreciated. -
How to split django log?
txt = "[28/Oct/2020 00:07:59] INFO [django.vino.f1:597] Watching for file changes with StatReloader\n [28/Oct/2020 00:08:04] INFO [django.vino:154] "GET / HTTP/1.1" 200 30128" want to split above log . any way to [28/Oct/2020 00:07:59] based on this pattern split (using re ) expected output : ["[28/Oct/2020 00:07:59] INFO [django.vino.f1:597] Watching for file changes with StatReloader", "[28/Oct/2020 00:08:04] INFO [django.vino:154] "GET / HTTP/1.1" 200 30128"] -
Creating columns inside column in MongoDB using models in django
Currently i am working with latest versions Python 3 and Django 3. I want to create columns inside column in MongoDB using models in Django. Ex: column name: Emp_name inside Emp_name there should be a first_name and last_name columns. Can anyone please help over here ASAP -
Unable to render a Django view function from React js forms
We usually use Jinja tags to submit forms through Django Templates i.e {% url 'view_name' %} but this does not work in React.This gaves syntax error and hence i tried as below. But this too does'nt work. React Js Code - <form onSubmit = 'form_submit' method = "post"> <DjangoCSRFToken/> <input type = "text" placeholder = "Email" name = "email"></input><br/> <input type = "password" placeholder = "Password" name = "password"></input><br/> <input type = "password" placeholder = "Confirm Password" name = "password1"></input> <input type = "submit"></input> </form> -
In Django REST Framework, Using ModelViewSet with renderers,
I'm using ModelViewSet and struggling to setup a rendering standard. The documentation doesn't show how to use ModelViewSet with drf renderers. I want the output to be of this format: Format : {'message': <custom message>, 'data': <output from ModelViewSet>} Code: class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [permissions.IsAuthenticated] renderer_classes = [GenericAPIRenderer] # How to Override? class GenericAPIRenderer(renderers.JSONRenderer): charset = 'utf-8' def render(self, data, media_type=None, renderer_context=None): pass -
how to make django crispy forms responsive?
I understand that the Djago crispy forms makes the forms look good, but how can we make the forms responsive? {% load crispy_forms_tags %} <form method="POST" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn-purple fa-pull-right">Sign-In</button> <br> </form> -
AWS Elastic Beanstalk [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream
I'm getting this error when trying to use AWS Elastic Beanstalk to connect to my Django code: [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" My log is displayed below: ---------------------------------------- /var/log/nginx/error.log ---------------------------------------- 2020/12/21 03:43:19 [error] 2540#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:22 [error] 2540#0: *3 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:34 [error] 2540#0: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:37 [error] 2540#0: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:49 [error] 2540#0: *9 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.23.63, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "172.31.14.130" 2020/12/21 03:43:52 [error] 2540#0: *11 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.160, server: , request: "GET / … -
how to remove html tags in django template on browser while showing to user
As shown in figure i used {{options|safe}} for rendering options in my django 3.0 polls application even though it is rendering like that and i don't know how to remove the tags from rendered string, thanks for help in advance regarding tag error -
How to change django filter_horizontal filter parammeter
I want to add product to category model in admin page. models.py class Product(models.Model): name = models.CharField(max_length=20) image = models.ImageField(upload_to='product/') def __str__(self): return self.name class Categorymodels.Model): category_name = models.CharField(max_length=20) category_product = models.ManyToManyField(Product, blank=True, related_name='category_product') def __str__(self): return self.promo_name admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): filter_horizontal = ('category_product', ) pass When adding products to category, I can use filtering but it filters only by product name. How do I filter something else. -
What error to raise with wrong post request body?
I am new to Django and have an endpoint that accepts post requests. The endpoint expects a specific set of keys in the post request body. What type of Exception should I raise if they don't provide the right keys? ValueError? Thanks! -
get context data in get_queryset
I have BaseContext and Listview which is for Searching in multiple models, Search Class inherits from BaseContext. I set the current user to context and want to use it in my def get_queryset method, But it doesn't work. I think in Search CBV get_context_data execute after get_queryset that's why, self.user is None. class BaseContext(ContextMixin): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) request = self.request if request.COOKIES.get('token') is not None: ... user = Users.objects.filter(user_id=user_id).first() context.update({'current_user': user}) context.update({'is_logged_in ': True}) else: context.update({'is_logged_in ': False}) return context class Search(BaseContext, ListView): template_name = 'search.html' context_object_name = "results" paginate_by = 15 user = None def get_queryset(self): query = self.request.GET.get('search', None) if query is not None and self.user is not None: ... return queryset_chain return faqModel.objects.none() def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if 'is_logged_in' in context and context['is_logged_in']: self.user = context['current_user'] else: redirect("index") return context My question is how can I get context data in def get_queryset(self)? -
ttributeError: type object '' has no attribute 'get_extra_actions'
I am new to Django , and totally confused about the error I face. i am trying to create a rest api and apply django filtering option to it. here is my view code. @permission_classes([AllowAny]) class op_listView(generics.ListAPIView): serializer_class = op_Serializer queryset = Op.objects.all() filter_backends = (DjangoFilterBackend,OrderingFilter, SearchFilter) filter_fields=('website', 'organization__name', 'sectors__name','countries__name') my model class Op(models.Model): website = models.CharField(max_length=40) op_link = models.CharField(null=True, max_length=200) title = models.TextField(null=True) description = models.TextField(null=True) organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) close_date = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) checksum = models.CharField(max_length=200, null=True) relevancy = models.IntegerField(null=True) mark_relevant = models.IntegerField(null=True) published_date = models.DateField(null=True) language = models.ForeignKey(Language, on_delete=models.DO_NOTHING, default=105) status = models.IntegerField(null=True, default=0) read_status = models.IntegerField(default=0) @property def attachments(self): return self.attachments_set.all() @property def countries(self): return self.country_set.all() @property def sectors(self): return self.sector_set.all() class Meta: db_table = "op" my serializer class op_Serializer(serializers.ModelSerializer) : attachments = attachments_Serializer(many=True , required=False) countries = country_Serializer(many=True , required=False) sectors = sector_Serializer(many=True , required=False) class Meta : model = Op fields = ['id', 'website', 'op_link', 'title', 'description' , 'organization' , 'close_date' , 'created_at', 'relevancy', 'published_date', 'language' , 'status' , 'read_status' , 'attachments', 'countries', 'sectors'] depth = 2 urls from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('op-filter', views.op_listView, basename='op-filter') urlpatterns = router.urls my code does not work and … -
In order to discontinue 3rd party API access, allow to create or reset a password in python-social-auth for already registered users via 3rd part
There are certain 3rd party sites that have a daily cap for API user requests. Case in point, Linkedin which only allows 100k requests a day. Imagine your site grows so much that this wall is hit. I believe the next step would be to disable the linkedin connectivity and only allow via regular email and password. The problem is those users that signed in initially with linkedin - with what password can users try to log in using their regular emails? I've also attempted resetting a password as a user that logged in via linkedin through the reset password default django flow (tokenized link sent to their email) and the link does not even print in the console. However, when I do these steps as a user that signed in with a regular email and password, the workflow works well. What would be the steps to allow for a "resetting" for these users? PS. I wonder if it can be something via the below logic... https://python-social-auth.readthedocs.io/en/latest/backends/username.html Thanks in advance. -
Intermittent Bad Request (400) Spotify API callback using nginx + gunicorn + django
When I use nginx to serve my spotify django app with gunicorn socket handling communication, I would sometimes get Bad Request error during the user authentication callback. If gunicorn is configured as TCP with an ip and port, I don't experience the error, nor if I use django's manage.py runserver; user authenticates successfully. This intermittent issue seems to only occur when I'm using a socket connection. Checked nginx, gunicorn and django logs and didn't really get any info other than the 400 code. Using tekore python library to access spotify's api. Here's my nginx config: upstream app_server { server unix:/home/yg/Documents/projects/app/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 192.168.0.26; client_max_body_size 4G; access_log /home/yg/Documents/projects/app/logs/nginx-access.log; error_log /home/yg/Documents/projects/app/logs/nginx-error.log; location /static/ { alias /home/yg/Documents/projects/app/static/; } location /media/ { alias /home/yg/Documents/projects/app/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_buffering off; if (!-f $request_filename) { proxy_pass http://app_server; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/yg/Documents/projects/app/static/; } } -
I need to access a foreign Key element for populating a ModelForm
I'm building a forum with comment and Reply capabilities. While populating the form I'm facing a issue of Cannot assign "<Post: Post object (10)>": "Reply.comment" must be a "Comment" instance. I can understand the problem but don't know how to morph it into a Comment Instance. I'm using Django 3.1.4 The Models are as follows: class Post(models.Model): headline = models.CharField(max_length = 100) context = models.TextField() author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) class Comment(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) text = models.TextField(max_length = 200) author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) modified = models.DateTimeField(auto_now = True) class Reply(models.Model): comment = models.ForeignKey(Comment, related_name='replies', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) reply = models.TextField() views.py is as follows: class PostDetail(DetailView): model = Post def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['comment_form'] = CommentForm() context['reply_form'] = ReplyForm() return context def post(self, request, *args, **kwargs): comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = Comment( author = request.user, post = self.get_object(), text = comment_form.cleaned_data['comment'] ) comment.save() else: comment = Comment() reply_form = ReplyForm(request.POST) if reply_form.is_valid(): reply = Reply( user = request.user, comment = self.get_object(), # This line is the issue!!! … -
How to direct outside admin page after clicking save button?
is there a way after I click save button on admin page, I direct it outside admin page for example I cannot find the solution on internet http://127.0.0.1:8000/admin/app/add after I click save it open http://127.0.0.1:8000/app/ -
How to display ForeignKey Data in Django Template
I have relation of Project between Tags and a Project can have multiple tags, But I am unable to display the tags data in my template, I am trying to display data according to tag slug. But I ma getting error, Please let me know how I can display Tags data in my Template. Here is my urls.py file... path('tag/<tag_slug>', views.projecttag, name='projecttag'), here is my `models.py file... class Tags(models.Model): project = models.ForeignKey(Project, null=True, blank=True, related_name='ProjectTags', on_delete=models.CASCADE) tag_name = models.CharField(max_length=64, null=True, blank=True) tag_slug = models.SlugField(max_length=64, null=True, blank=True) here is my views.py file... def projecttag(request, tag_slug): tag = get_object_or_404(Tags, tag_slug=tag_slug) project = Project.objects.filter(ProjectTags=tag) context = {'tag':tag, 'project':project} template_name = 'pages/tags.html' return render(request, template_name, context) here is my tags.html file... {% for property in project %} <div class="single-property-box"> {{property.name}} </div> {% endfor % -
Can't send POST request from react method
I am creating a FB like app with Django and react. In the main page there's a feed where users can create posts and post them to the feed. I am trying to implement the delete post functionality but I am running into some difficulties. The logic is: The user clicks on the delete button on a post and the Browser sends and XMLHttpeRequest to the server to delete that post. Here's the react component: class Feed extends React.Component { constructor(props){ super(props); this.state = { profile_pic: profile_pic_url, user: username, posts: posts_from_server, } } handleClick() { const text = document.querySelector('#new_post_text').value; if (text.length > 1) { const data = {author: username, text: text} // send that post to the server to save it const csrftoken = Cookies.get('csrftoken'); const request = new XMLHttpRequest(); request.open('POST', '/create_new_post', true); request.setRequestHeader('X-CSRFToken', csrftoken); request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); request.onload = () => { const response = JSON.parse(request.responseText) this.setState({ posts : [{author: response.author, author_picture: profile_pic_url, text: response.text, date: response.date}, ...this.state.posts] }) document.querySelector("#new_post_text").value = ''; console.log(response) } request.send(JSON.stringify(data)) } } deletePost(post_id, author) { const post = document.getElementById(post_id) post.style.animationPlayState = 'running'; setTimeout(() =>{ this.setState({ posts: this.state.posts.filter(post => post.id != post_id) }) }, 1000) // delete the post from the server const data = {'post_author': … -
How to filter out objects in a related model without filtering out any of the objects from the primary model [Django]
Let's say I have models that look like this: # models.py class Agent(models.Model): name = models.CharField(max_length=30) class Deal(models.Model): agent = models.ForeignKey(Agent, on_delete=models.SET_NULL) close_date = models.DateField() And in my view, I'm wanting to list the deals per agent that have close dates <= 20 days into the future: # views.py class UnderContractListView(ListView): model = Agent context_object_name = 'agents' def get_queryset(self): future_date = (datetime.datetime.now() + relativedelta(days=20)).date() queryset = Agent.objects.filter(deal__closed_date__lte=future_date) return queryset Here's where I'm getting stuck The configuration above works great if I want to filter out the agents that have 0 deals; how can I filter out the deals without filtering out the agents? -
How can I show inlines dynamically in django admin
I want to show inlines dynamically depends on model value. When I override get_inlines like: # ModelAdmin def get_inlines(self, request, obj): if obj.is_show: return [SectionInline] else: return [] I got exceptions when I change the model object: ValidationError: 'ManagementForm data is missing or has been tampered with' Seems it not working. Can anyone help me to figure out the correct way? Thanks! -
Django - Logging - How to get the class name when running function GET inside it?
So I tried to create a logging for my code: views.py class name_of_API(generics.GenericAPIView): @my_logging @swagger_auto_schema def get(self, request): **running something return ... my_logging.py def my_logging(func): @wraps(func) def func_wrapper(request, *args, **kwargs): ex = None try: response = func(request, *args, **kwargs) log = logging.getLogger('main') name_of_class = func.__class__.__name__ log.info(str(name_of_class) + 'called success') except: format in settings.py 'format': '%(asctime)s.%(msecs)03d|%(levelname)s|%(process)d:%(thread)d|%(filename)s:%(lineno)d|%(module)s.%(funcName)s|%(message)s' info.log: 2020-12-21 10:30:04.845|INFO|12560:11868|logger.py:11|logger.func_wrapper| function Called success The problem here: This row below func.__class__.__name__ return function instead of name_of_API -
ModuleNotFoundError: No module named 'api.serlializer'
I've installed Django 3.1.4 and djangorestframework 3.12.2. I am attempting to run makemigrations for a music website I am building and I keep getting this error in the terminal and haven't been able to figure out what is causing it. (Django_React) PS C:\Users\BB_SO\desktop\dev\Django_React\music_site> python .\manage.py makemigrations Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\BB_SO\desktop\dev\Django_React\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\BB_SO\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, …