Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I would like to divide my page in 2 columns with bootstrap on 2 news articles for my django home template
I have created my django home template for my scraper and I would like to divide the page in 2 columns with the scraped stories appearing side by side. I have loaded bootstrap on my Base template with CSS and HTML. This is my code so far {% extends 'base.html' %} {% block title %} <div class="container"> Home </div> {% endblock title %} {% comment %} {% endcomment %} {% block content %} <div class="container"> <div class="p-3 mb-2 bg-dark text-white"> <h1>JSE News</h1> {% for item in jse_articles %} <h3><a href="{{ item.Link }}" target="_blank" rel="noopener noreferrer">{{ item.Headline }}</a></h3> {{item.Text}} <!-- <img src ="{{item.Image}}"> --> {% endfor %} <hr> <br> <h1>Coin Desk News</h1> {% for item in coindesk_articles %} <h3><a href="{{ item.Link }}" target="_blank" rel="noopener noreferrer">{{ item.Headline }}</a></h3> {{item.Text}} {% endfor %} </div> </div> {% endblock content %} -
django: Manager isn't accessible via username_and_password instances
I am facing a error in Django. Here is my code. Also I am working with databases here. Here is my code in models.py: from django.db import models from django.db.models.fields.related import ForeignKey # Create your models here. class username_and_password(models.Model): user_name = models.CharField(max_length=300) password = models.CharField(max_length=300) def __str__(self): return self.password And then I went to the cmd and made migrations. then opened the shell. So far everything worked. In shell I did In [2]: from main.models import database, username_and_password In [3]: data = username_and_password(user_name="Databasetest",password="Runningtest") In [4]: data.save() Everything worked but then when I typed: data.objects.all() It showed me an error: AttributeError Traceback (most recent call last) <ipython-input-4-d33a4311e29a> in <module> ----> 1 data.objects.all() ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py in __get__(self, instance, cls) 177 def __get__(self, instance, cls=None): 178 if instance is not None: --> 179 raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) 180 181 if cls._meta.abstract: AttributeError: Manager isn't accessible via username_and_password instances Please help me on this, I am new to the library Django, Any help is appreciated . -
How do I cross reference two databases in Django?
I have a Django server running where I have two apps: Flowers, and Shops. I would like to do a query where I get information back from both tables at the same time. With SQL, I would say SELECT * FROM flowers, shops WHERE flowers.flowerID=shop.flowerID. How would I do this for Django? I currently have serializers for both individual apps, but cannot seem to combine them. The flowers.models.py is set up like this: class Flowers(models.Model): flowerID = models.IntegerField() flowerName = models.TextField() flowerSpecies = models.TextField() flowerColour = models.TextField() The shop.models.py is set up like this: class Shop(models.Model): flowerID = models.IntegerField() quantity = models.IntegerField() cost = models.TextField() comments = models.TextField() Any help is appreciated - even if it is pointing to specific online resources. -
Django + MongoDB + Djongo: can't json serialize ObjectId
I'm creating a Django APP with MongoDB using Djongo. When I try json.dumps(my_queryset, cls=DjangoJSONEncoder) I get the following error. Object of type ObjectId is not JSON serializable The model class Productos(models.Model): _id = models.ObjectIdField() id_anwen = models.IntegerField(help_text="Pedido Mínimo", blank=True, null=True, default=1) codigo_kinemed = models.CharField(max_length=100, blank=True, null=True) codigo_barra = models.CharField(max_length=100, blank=True, null=True) codigo_inner = models.CharField(max_length=100, blank=True, null=True) codigo_master = models.CharField(max_length=100, blank=True, null=True) item_number = models.CharField(max_length=100, blank=True, null=True) objects = models.DjongoManager() Some test If I remove _id = models.ObjectIdField() json dumps works fine but I don't get the object's ID info in the JSON. How can I serialize MongoDB's _id field for a JSON? Any clues welcome. Thanks in advance! -
how to correctly connect models in django quiz app
I am creating google form like quiz app,is this model fine that create 4 column for every answer. when i create Question also i create Answer's model 4 object it's good? How to connect better so that not many objects are created in the database and are well sorted class Quiz(models.Model): name = models.CharField( max_length=90, verbose_name=_('ქვიზის სახელი') ) image = models.ImageField( upload_to='images', verbose_name=_('ქვიზის სურათი') ) played = models.IntegerField(verbose_name=_('რამდენჯერაა ნათამაშები')) author = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name=_('ქვიზის ავტორი') ) def __str__(self): return self.name class Meta: verbose_name = _('ქვიზი') ordering = ['-id'] class Question(models.Model): question = models.CharField( max_length=200, verbose_name=_('კითხვა') ) quiz = models.ForeignKey( Quiz, on_delete=models.CASCADE, verbose_name=_('ქვიზი') ) def __str__(self): return self.question class Answer(models.Model): probable_answer = models.CharField( max_length=150, verbose_name=_('სავარაუდო პასუხი') ) correct = models.BooleanField( default=False, verbose_name=_('სწორი პასუხია?') ) question = models.ForeignKey( Question, on_delete=models.CASCADE, verbose_name=_('რომელი კითხვის სავარაუდო პასუხია?') ) -
I am using a converter type in my URLs to capture a string paremeter in Django. Will it affect SEO?
I am using this URL pattern in Django to pass a string parameter for location: path('location/<str:locs>/', LocationView, name='location'), The website is a directory to more than 90 locations. I cannot add content to each location to improve the SEO performance of my site. Will it hurt the SEO performance of my website for pages that do not have content at some point? If yes, what can I do to add content to URL for location. For example, I want specific content to appear on "location/Washington" and not be repeated for other locations. -
Django address input field that updates google map and can be uploaded to data base
I'm creating a Django blog style application that involves a user inputting a few fields, one of which is an address. What I want to do is when the user begins typing their address, address options begin to show up, like you'd see if you were to type on google maps. When the user then decides on the correct address and clicks the post button I want the address to be stored into the data base. This is because when another user clicks on the blog post I want a google map to show up with a marker on the address that the post creator submitted. I've tried to achieve this using Mapbox but couldn't quite get it to work so I'm trying to do it using google map JavaScript API. I found something that I think will help me on https://developers.google.com/maps/documentation/javascript/examples/places-searchbox but for some reason when I copy the javascript code onto my Django Project I get errors like 'Unresolved variable or type google' and 'Deprecated symbol used, consult docs for better alternative ' and nothing shows up on the page, which leads me to believe that I should have installed some package or should have added something to … -
getting url slug django
i am wanna get url slug to show selected category by user on breadcumb. how can i get it? i found only wordpress and php solves. template <div class="breadcumb_area bg-img" style="background-image: url({% static 'img/bg-img/breadcumb.jpg' %});"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <div class="page-title text-center"> <h2>dresses</h2> </div> </div> </div> </div> </div> -
I cant seem to push code to heroku on vsc
I'm reading Django for Beginners and in the book you need to push your code to heroku but when I try to push it to heroku im getting an error that looks something like this Enumerating objects: 26, done. Counting objects: 100% (26/26), done. Delta compression using up to 4 threads Compressing objects: 100% (25/25), done. Writing objects: 100% (26/26), 3.85 KiB | 171.00 KiB/s, done. Total 26 (delta 2), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! remote: ! We have detected that you have triggered a build from source code with version 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! remote: ! … -
How to get multiple select values from my own Django form
I would like to know how to get values from a jquery plugin from select multiple. This is my form. <form action="{% url 'agregar_solicitud' %}" method="post"> {% csrf_token %} <select name="producto[]" class="form-control" multiple="multiple" > {% for row in rows %} <option value="{{row.nombre}}">{{row.nombre}}</option> {% endfor %} </select> {% load static %} <script src="{% static 'js/BsMultiSelect.min.js' %}"></script> <script> $("select").bsMultiSelect({cssPatch : { choices: {columnCount:'3' }, }}); </script> <input type="submit" name="agregar" value="Agregar Productos" class="btn btn-success"> </form> [That is the image of the form] 1 And this is my view. def agregar(request): pr= request.POST["producto[]"] data = request.POST.get('producto[]') print(pr,data) return redirect('inicio_solicitud') But by none of the methods I can obtain the value of the product field by its position, such as: request.POST["producto1"]. In Laravel I had no problem doing the following: $request->producto1. Beforehand thank you very much. -
How to implement extended auth-User model in SignUp form in Django?
I want to add more fields in auth-User model. So, according to this docs(https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model) I created a 'UserProfile' model in one-to-one relation with auth-user. But it's not working in forms.py. Actually, I couldn't implement it in forms.py Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) profile_picture = models.ImageField() forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): up = user.userprofile user.userprofile.profile_picture = self.cleaned_data['profile_picture'] up.profile_picture = self.cleaned_data['profile_picture'] user.save() up.save() return user Even after SignUp I don't get any object in 'UserProfile'. -
Apply two humanisers to number
How do you apply to humanisers to a number. For example, intcomma and ordinal. This would convert 1000 to 1,000nd. -
Authenticate Django from url without login
I am trying to log my user with a link generated from me, basically this is the workflow, a user wants to fill a form from my site, but they comunicate through whatsapp, so i will generate a link for them, but the catch is they have to log in once they go into the page, since they will fill some sensitive data , plus, id like them to get logged into the system and use other functionalities if they want. Security wise, i will always know if the user is who they say when they message me bc i can recognize the phone number, so i dont need them to log in again once they click the link and go into the browser. Dont get me wrong i want the user to be able to log in if they want from their computer, but it makes it a lo easier if they dont have to do that form mobile. Based on the phone number i will know the user, so what i need is generate a link where they will click and it will be self authenticating, meaning they will be logged with this link and forwarded to where … -
'User' object has no attribute 'encode' while signing up
I am building a BlogApp and Today i tried to signup and then this error is keep showing 'User' object has no attribute 'encode' AND Then i tried to register in all my previous versions then this error is showing them all. BUT it was working before few days. Then i restarted my pc but still same error. views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=200) password1 = forms.CharField(widget=forms.PasswordInput()) username = forms.CharField(help_text=False) class Meta: model = User fields = ( 'email', 'username', ) models.py @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() When i click on register then this error is raising . When i check in admin then user is created BUT profile is not created, BUT it should show me User has no object Profile BUT it is showing something different. Any help would be much Appreciated. Thank You in Advance. -
Is there a way to modify model data on a button press?
I was wondering if there is a way to change the values of an object on a button press. I am making a to-do list application, and next to each item I would like there to be a button that sets the 'completed' value of the ToDo object to True. I think that you'd call a function in views.py that changes the data, but I don't really know how to do that. index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>To Do List</title> </head> <body> <h1>To Do List</h1> <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Add</button> </form> {% for todo in todolist %} {{ todo.content }} {{ todo.completed }} <br> <!-- The button/link would go here, but I don't know what to do --> {% endfor %} </body> </html> views.py: from django.shortcuts import render, redirect from .models import ToDo from .forms import ToDoForm def index(request): if request.method == 'POST': form = ToDoForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = ToDoForm() context = {'todolist': ToDo.objects.all(), 'form': form} return render(request, 'main/index.html', context) models.py: from django.db import models class ToDo(models.Model): content = models.CharField(max_length=100) completed = models.BooleanField(default=False) Thanks! -
How to run test fixtures in across multiple classes in Django?
I have three python packages with multiple classes all containing multiple tests and i am running all the testcases at once using 'python manage.py test' command. Each class has the annotation of TestFixture. Fixtures is loading only once for the first class and for all the other classes fixtures are not loading. I need fixtures to be loaded when each test class ran. (e.g. TextFixture1 loaded when class 1 runs, then TestFixture2 loaded when class 2 runs, and finally TestFixture3 loaded when class 3 runs.). example: class Class1(APITestcase): fixtures= ['abc.json', 'cba.json'] #fixture1 class Class2(APITestcase): fixtures= ['123.json', '456.json'] #fixture2 class Class2(APITestcase): fixtures= ['xyz.json', 'zyx.json'] #fixture3 In the above example one fixtures 1 is loading and the other two fixtures are not loading when i use the command 'python manage.py test'. How can i solve this? -
Is caching helpful in the web app by django?
I've made my first project app with Django Framework. Now I'm trying to use local memory based caching since I'm just testing its functionality and latency. As most part of my site contains dynamic web pages with different contents for different users, I'm trying to bring in efficiency using template fragment caching. I'm enclosing all the static part of templates of my pages in {% cache %} and leaving dynamically generated part outside using many cache blocks. I don't seem to understand if it's really going to help my pages to be rendered fast because the part going to be cached is already static. When template engine compiles and executes a template to give response, its running time is directly proportional to number of jinja statements. Right? So if I'm avoiding static part being gone through by template engine, by caching, I'm still leaving most of statements for engine, is it going to help with speed or waste efforts? P.S. Excuse me for poor framing of question. Really bad at it -
How to combine querysets based on fields that have the same value
I have two querysets. queryset[{'name': B, 'size': 8}] queryset['name': A, 'name': B, 'name': C, 'name': D}] the result I want is this. queryset[{'name': A, 'size': 0}, {'name': B, 'size': 8}, {'name': C, 'size': 0}, {'name': D , 'size': 0}] I've tried combining both querysets, but I don't get the results I want. ('|', union) How to combine if values of one field in two querysets are the same? I've been thinking about it for a few days. urgent please help -
Merging Json response Django python
I am writing a django server api,where I have two request to fetch data from two other apis. list1 = requests.get(f"www.test.com/list/") list2 = requests.get(f"www.test.com/list2/") this two lists have json as response.I want to merge this two and put it in a json object like below {"list1":list1,"list2":list2} and return the result -
add an `a` tag with `href` linking to the next part in a django form HTML
I have a django form and I am trying to create a step up form where when you finish one section you click next to the go the next section in the same HTML template: I have created everything fine but I am stuck with the button for the next button. I have set an id and linked it to an href but is not opening the next form as required. Here is what I have tried to make it easier for explaining: <ul class="nav nav-pills mb-3" id="ex-3" role="tablist"> <!-- General Information --> <li class="nav-item" role="presentation"> <a class="nav-link active" id="ex-3-tab-1" data-mdb-toggle="pill" href="#generalInformation" role="tab" aria-controls="pills-1" aria-selected="true" >General Information</a> </li> <!-- Contact Information --> <li class="nav-item" role="presentation"> <a class="nav-link" id="tab_contactInformation" data-mdb-toggle="pill" href="#contactInformation" role="tab" aria-controls="pills-2" aria-selected="false" >Contact Information</a > </li> </ul> In the General info part I have added an a tag to link to href="#contactInformation" same as the nav-pill showing in the top but it is not leading to it. It is just saying in the same location. <a href="#contactInformation" >Contact Information</a > My question How to add an a tag with href linking to the next part? What am I doing wrong and how can I fix it? Thanks for the … -
Registration of a user and subsequent activation by the admin with django-rest-framework and djoser
I would like to create a user that is activated by the system admin with djoser and django-rest-framework. The sequence of operations that I would like to obtain is the following: a user sends the registration request the user is saved in the database but remains inactive an email is sent to the admin informing that a new subscription has been requested the admin activates the user from django admin panel when the user has been activated, an email confirming the activation is sent to him. I can do this with django in the following way: signals.py @receiver(post_save, sender=User, dispatch_uid='register') def register(sender, instance, **kwargs): if kwargs.get('created', False) and not instance.is_active: mail_admins('User registration request', f"A registration request was made by the user:\n\n{ instance.username }\n{ instance.email }", fail_silently=False, ) @receiver(pre_save, sender=User, dispatch_uid='active') def active(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists(): subject = 'Account activation' mesagge = '%s your account has been successfully activated!' %(instance.username) from_email = settings.EMAIL_HOST_USER send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False) views.py class UserRegisterView(CreateView): form_class = UserRegisterForm template_name = 'users/register.html' success_url = reverse_lazy('login') def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() return redirect('request') forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', … -
adding and displayin E-Books in django
I am working on a project for selling E-Books but I want to know the best way to display E-Books and handling them considering that users can not download or copy E-Books and can just read them can anyone help me what can I do? -
How can I listen for changes in the Django database?
I have two separate Django projects. Project B shares project A's database by referencing project A's database in it's models Meta class (db_table). Otherwise the projects are completely separate and run in different containers. I want to execute a function in Project A after Project B creates or updates a Model field in the shared database. I have tried using Model signals (post_save) in Project A, but it does not trigger when the Model field is saved in Project B when it is created or updated. How can I pass a signal from Project B to Project A to execute code in Project A, without writing the functionality I want to execute into Project B? Or how can I listen for changes in the database in Project A? -
Django Nginx: Gives WARNING:django.request:Not Found: When running server
I am trying to use Nginx with django to run my server but when i try to run i get these WARNING:django.request:Not Found: errors. normal python manage.py runserver works fine. Also i used this tutorial. Any idea why i am getting these errrors and how to fix them? Full Traceback Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 1 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /robots.txt WARNING:waitress.queue:Task queue depth is 2 WARNING:django.request:Not Found: /robots.txt Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 2 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /.env WARNING:waitress.queue:Task queue depth is 2 WARNING:waitress.queue:Task queue depth is 3 Not Found: /HNAP1/ WARNING:django.request:Not Found: /.env WARNING:django.request:Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 3 Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 2 WARNING:waitress.queue:Task queue depth is 3 Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 4 WARNING:django.request:Not Found: /boaform/admin/formLogin WARNING:django.request:Not Found: /HNAP1/ WARNING:waitress.queue:Task queue depth is 5 Not Found: /.env WARNING:django.request:Not Found: /.env Not Found: /.env WARNING:django.request:Not Found: /.env Not Found: /assets/global/plugins/jquery-file-upload/server/php/index.php WARNING:django.request:Not Found: /assets/global/plugins/jquery-file-upload/server /php/index.php Not Found: /boaform/admin/formLogin WARNING:waitress.queue:Task queue depth is 1 WARNING:waitress.queue:Task queue depth is 2 Not Found: /favicon.ico WARNING:waitress.queue:Task queue depth is 3 WARNING:django.request:Not Found: /boaform/admin/formLogin Not Found: /.env WARNING:django.request:Not Found: /favicon.ico Not Found: /robots.txt WARNING:waitress.queue:Task queue depth is 4 WARNING:django.request:Not … -
how to make a button that redirects to the previous page only if it is on my site
I would like to make a button that redirects the user to the previous page only if it is on my site, otherwise this button would redirect to the home page I read in the doc that we could not read the history urls but only redirect, so I ask the question if anyone knows any tips to do this function Back_on_site() { if (previous_domain == my_domain) history.back() else window.location.href = "my_site/home" }