Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i create a dynamic dropdown form using jquery
i am working on a Django project and i am trying to implement a dropdown form on button click. I have a dropdown form when a button is clicked and each form has its own button, the problem is that when i clicked on a particular form button, all other forms dropdown as well. I want only the particular form to dropdown while the others do not. I think this has to do with passing the id of the form to each button clicked. This is what i tried. Template: {% for comment in all_comments %} <ul> <li class="float-right"> <!--Dropdown--> <div class="dropdown dropdown-commentdeleteedit"> <a data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-ellipsis-h grey-text"></i> </a> <!-- Menu --> <div class="dropdown-menu font-small z-depth-1"> <a class="dropdown-item material-tooltip-email editform-dropdown" data-toggle="tooltip" data-placement="top" title="Edit"> <img src="{{ '/static/' }}images/edit24px.png" width="18" height="18"></a> </div> </div> <!--Dropdown--> </li> {% endif %} <h6 class="comment editcomment-text ml-5"> {{ comment.comment_post }} </h6> <!-- DROPDOWN EDIT COMMENT FORM --> <form method="POST" enctype="multipart/form-data" class="ajaxcomment-editform editcommentform editcomment-form mb-4" id="" action="{% url 'site:comment_update' post.id comment.id %}"> {% csrf_token %} <textarea name="comment_post" cols="20" rows="5" required="" id="id_comment_post{{ comment.id }}">{{ comment.comment_post }}</textarea> <button type="submit" class="btn btn-sm waves-effect z-depth-1">Save</button> </form> </ul> {% endif %} Jquery: <script type="text/javascript"> //HIDE AND SHOW COMMENT EDIT FORM … -
Getting Internal Server Error when calling view view for dependent dropdown
I am getting data In first dropdown(countries) and second dropdown is dependent on countries dropdown. So I am select country then make an ajax call for language then it give me error "Internal Server Error: /language/" while If call this in countries then it works it means data is available in models and work fine. I am learner urlpatterns = [ path('admin/', admin.site.urls), path("", views.home, name="home"), path("login/", views.login_user, name="login"), path("post/", views.post, name="post"), path("language/", views.language, name="language"), path("logout/", views.logout_request, name="logout"), ] @login_required(login_url='/login/') def post(request): if not request.user.is_authenticated: return redirect('/login/') countries = Countries.objects.all() print(countries) context = {'countries': countries} return render(request, 'post.html', context) def language(request): print("call language") countryId = request.POST.get('country_id') print('country id: ' + countryId) languages = Languages.objects.filter(country_id=countryId) print("obj "+languages) context = {'languages': languages} return render(request, 'post.html', context) <script type="text/javascript"> function getSelectedCountry() { d = document.getElementById("countries").value; <!--alert(d);--> var token = '{{csrf_token}}'; $.ajax({ headers: { "X-CSRFToken": token }, type: 'POST', url: "{% url 'language' %}", data: {"country_id": d}, success : function(json) { $("#id_city").html(data); console.log("requested access complete"); } }) } </script> -
Unable to connect to server: FATAL: password authentication failed for user "xxxx" FATAL: password authentication failed for user "xxxx"
I'm building a Django app and I'm trying to create a connection from AWS. The password is right and the hostname/address link is the but it says "Unable to connect to server: FATAL: password authentication failed for user 'xxxx'" Here's a screenshot of the error: https://prnt.sc/sqziuq Other screenshots for another details of the connection: https://prnt.sc/sqzm9z https://prnt.sc/sqzlx7 -
Correctly export column headers from Django to csv
New to Django and python as well. Issue that I am having while maintaining a Django app is when exporting records from django, one of the field names is showing up as get_mobile instead of mobile. code for the get_mobile function is def get_mobile(self): if self.mobile: return str(' '.join([self.mobile[:4], self.mobile[4:7], self.mobile[7:]])) else: return self.mobile get_mobile.short_description = 'Mobile' code for writing the header data is # Write header. header_data = {} for name in headers: if hasattr(self, name) \ and hasattr(getattr(self, name), 'short_description'): header_data[name] = getattr( getattr(self, name), 'short_description') else: field = None try: field = self.model._meta.get_field(name) except FieldDoesNotExist: pass if field and field.verbose_name: header_data[name] = field.verbose_name else: header_data[name] = name header_data[name] = header_data[name].title() writer.writerow(header_data) I kind of have a general idea of where the issue lies - the header is using the function name instead of the short_description. Being new, I am kind of stuck at getting my head around the header code itself. Would greatly appreciate if someone could help me understand the header code please and explain why it is currently not working as expected - my understanding is it should be using the short_description for mobile instead of function name get_mobile when exporting the records. TIA -
How to diplay number of blog posted per category in Django
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage. models.py: class Category(models.Model): CATEGORY = ( ("Un-categorized", "Un-categorized"), ("Machine Learning", "Machine Learning"), ("Data Science", "Data Science"), ("Programming", "Programming"), ("Latest Trends", "Latest Trends") ) category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True) def __str__(self): return self.category class Post(models.Model): title = models.CharField(max_length=20) # title of the post content = models.TextField() # content of the post date_posted = models.DateTimeField(auto_now_add=True) # when the post is created date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved. author = models.ForeignKey(User, on_delete=models.CASCADE) # Referring the django's inbuilt User model. category = models.ForeignKey(Category, on_delete=models.CASCADE) # one post can have only one category whereas under one category there can be multiple post. img = models.ImageField(default='default.jpg', upload_to='post') # tag = to store important tags related to the post def __str__(self): return self.title views.py : def home(request): # Home page of the website. post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order. categories = Category.objects.all() '''categories_count = [] i = 1 for item in categories.count(): categories_count[item] = Categories.objects.filter(id=i).count() i += 1 ''' context = { 'posts':post, # 'count' : categories_count, 'categories': … -
Different pieces of web development
I would like to start learning web development for an e-commerce website that includes a chat option. I have been daunted by the new terms that I no longer know what I need to learn. So I know there is backend and frontend, but where do things like django, rest API, ajax, apache, msquery, vue and other stuff fall into the puzzle. What exactly do I need to know for full-stack development. Could someone walk me through different pieces needed? Thanks!! -
How to add placeholders in or near the input fields in django models
I am trying to build a blog app in Django. The problem is that i am not able to mention any thing near the input field. For example There is an image field and i want mention "Only upload images of size 300px x 250px" near it. Thanks in advance -
Preventing Users From Submitting A Form More Than Once
I have a multi-part form that users can leave mid-way through and come back to at any time. However, users can only submit it once so I want to prevent them from even being able to view any part of it once they have completed the final section. I figured I could either: 1 Have a boolean within the user model (False == havent submitted the form, True == have submitted). 2 Create two user groups, a default group for users who havent completed the form, and another for those who have - which users would be allocated to using a signal triggered when they submit the final form. I could then add checks for these in the template and not display the button if they fail, and add checks to the views to prevent users from accessing the form by typing it directly into the url bar. Which (if either) of these methods is best? Or is there another way more suitable / less hacky / more aligned with Django conventions. Thank you. -
How can I connect a model to a user model in Django?
I've created two different users and I want those users to have access to the same model called user_data. class user_1(Account): first_name=models.CharField() last_name=models.CharField() class user_2(Account): first_name=models.CharField last_name=models.CharField class user_data(models.Model): Data_1=models.IntegerField() Data_2=models.IntegerField() -
i want to create clock on my website can anyone please
here is my website url enter link description here i want to add clock using python using django framework. refer above url, also it shoud be fully functional in deployment of the webapp. kindly refer below snap. kindly help us to create this type of webapp. -
page not found 404 django
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about/ Using the URLconf defined in Hello.urls, Django tried these URL patterns, in this order: admin/ admin/ [name='home'] service [name='service'] contact [name='contact'] about [name='about'] The current path, about/, didn't match any of these.[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/jZMW9.png -
I'm getting an error while running a code which includes Django's built in DetailView
It is showing that the reverse for the detail has no arguments. I'm not sure what it means. I'm uploading the snippets of my files.This is the picture of my browser with the error displayed Please help me if you find my error. Snippet of the urls.py file in the app(class_app) -
Django DRF: save data in different models in a single request
Lets say I have two models such as class A(models.Model): field_1 = models.CharField(max_length=200, blank=False) field_2 = models.CharField(max_length=200, blank=False) class B(models.Model): field_1 = models.ForeignKey(A, on_delete=models.DO_NOTHING) field_2 = models.CharField(max_length=200, blank=False) I need to write a view and serializer with three fields . Save 2 fields on model A, then the primary key of the saved data on model B along with third field data. Can someone tell me how can I get this done.Iam using django 2.7. -
writing djnago test for __str__ in a model
I want to test my blog app. After running coverage, I have about 91% with 4 missing. The coverage pointed out the lines of code below to be missing. def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title Thus, I decided to write a test for str(self). Here is what the test looks like class PostTest(TestCase): def create_post(self, title="only a test", text="Testing if the created title matches the expected title"): return Post.objects.create(title=title, text=text, created_date=timezone.now()) def test_post_creation(self): w = self.create_post() self.assertTrue(isinstance(w, Post)) self.assertEqual(str(w), w.title) The test fails with the following error. django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (1, only a test, Testing if the created title matches the expected title, 2020-05-31 05:31:21.106429+00, null, null, 0, null, 2020-05-31 05:31:21.108428+00, ). This is what the model looks like: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, blank= True, null=True) updated_on = models.DateTimeField(auto_now= True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=STATUS, default=0) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) class Meta: ordering = ['-published_date'] def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title How do you suggest I write the test to fix this error and improve the coverage? -
Как получить логин пользователя в models или views
Я новичок в Django, не могу сообразить, как через request получить логин пользователя. Делаю сайт типа словаря, и нужно, чтобы каждая добавленная запись помечалась тем, кто ее добавил. Вот мой models.py from django.db import models class EngDict(models.Model): orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово') translate = models.CharField(max_length=500,null=False,blank=False, verbose_name="Перевод") remarks = models.TextField(null=True, blank=True, verbose_name="Примечания") published_by = models.CharField(max_length=50, verbose_name="Добавлено", initial=request.user) published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Дата добавления") category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория') class Meta: verbose_name = ("Перевод") verbose_name_plural = "Англо-русский словарь" ordering = ['-published_date'] А это views.py from django.shortcuts import render from django.template import loader from .models import EngDict, Category from django.views.generic.edit import CreateView from .forms import EngDictForm from django.urls import reverse_lazy from django.views.generic import TemplateView, ListView, FormView from django.db.models import Q from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login class EngDictCreateView(CreateView): template_name = 'dict/create.html' form_class = EngDictForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context Я так понимаю, мне надо написать функцию типа def user_name(request) , но я не могу сообразить где должна быть эта функция и как она должна выглядеть. Мне по идее надо, чтобы в published_by автоматом подставлялся логин пользователя при создании новой записи. -
middleware updates request.user, but request.user becomes AnonymousUser in view
I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt returns a User object. # app.middlewares.py class JwtMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) return self.get_response(request) def process_request(self, request): request.user = self.get_user_from_jwt(request.headers) ... In settings: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'app.middlewares.JwtMiddleware', ] When I log, request.user is set to the proper User instance at the middleware level, but once at the view, request.user becomes AnonymousUser. I tried switching the orders of the middlewares too. Any ideas how I can update what request.user means inside my views using a middleware? -
Unit Test: How To Mock MEDIA_ROOT But Still Access A File That Is Stored In My Normal MEDIA Folder
Im testing one of my webpages POST functions. if request.method == 'POST' it generates a pdf and attaches it to the user. Every time I ran tests I was generating pdf files which were building up in my MEDIA folder and I had to manually delete them. I decided to look for ways to prevent this from happening and what seems to me to be the best way is to override my MEDIA_ROOT with a tempfile. I am getting the following error message FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Acer\\AppData\\Local\\Temp\\profile_pics\\default.jpg' I am sure this is due to the fact that I must create and log-in a user prior to running the test (I dont want to do this in setup as I must generate different types of users for different tests). Every time a user is created their profile picture is set to profile_pics\\default.jpg'. My understanding is that the mocked MEDIA_ROOT is empty and doesnt contain the default profile pic, so the error is thrown. My question is how can I circumvent this? I found other solutions besides mocking the MEDIA_ROOT folder, but they seem quite hacky and id prefer to do it properly and hopefully learn from … -
Django CRM Need to invite agents by admins using email address
I have an uncompleted django CRM. I have 2 types of users: Agents: can post and view data. Admins: can view and edit data. The thing is i need each admin to invite the users to CRM. i need it to work as following: Admins will have access to a form where they can write down the agents name and email, once theysubmit the form and an email will be sent to the agent. The agent will receive an email with another form to set their username and password so they can login do you have any idea what i should look for or how can i do that? -
Javascript Errors when loading Bootstrap Modal a second and third time that contains a form with drop downs
I'm a complete beginner...please excuse the mess. Only been learning for about a month. The structure is like this. I have a nav.html template I've created for a top level menu across the site. It contains a drop down for creating New entries...and in this case a 'New Job' Job has two special parts. I've used Django-autocomplete-light for finding/creating new customers in the one form. This leverages select2 and some other javascript wizards A google places autocomplete for finding site addresses Everything worked fine as just opening in a fresh page. Then I decided I wanted to put the New Job form in to a modal instead. I'm an idiot. I'm using non-modified bootstrap css and the js for it as well...but pulled them down to be local copies in my static folder. Same goes for jquery and popper. Got it to actually work/pop up fine but then these happened in the background. Grabs from the google chrome console. These are the errors I see when just opening and closing without entering any data. I started learning about the javascript event loop and it hurt my brain...but does this all have something to do with that? This kind of feels … -
How can I define a function in django so that stays active in background?
How can I define a function that stays active in background? For example, I want django to update all of the movies in database using IMDB information. If there are too many movies in database, It can take too long for django to update them. So I want the process of updating to stay active in background and don't stop if I close web browser. 1) How is this possible? 2) Can I add a progress bar to see how many movies are updated so far ? -
how to handle a variable number of arguments in django query
My current project has me building a page where the output can be filtered by category. Meaning by default you get a full list of items but you can narrow the output by clicking on ( multiple or a single) check boxes. The idea would be if you only want to see the results from two categories you can choose those two and just see items from those two categories. (think like an Amazon page where you can can search for an item but filter the results) This works through a form using the get method. So the url will look something like: ip/?family=category_one&family=category_two My code is as below: Please note the Firmware model is related to ProductModel through a ManyToManyField and ProductModel is related to Family through a ForeignKey relation *models class Family(models.Model): family_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) slug = models.SlugField(null=False, unique=True) family_name = models.CharField(max_length=50, editable=True, unique=True) class ProductModel(models.Model): model_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) model_number = models.CharField(max_length=25, editable=True, unique=True) family_id = models.ForeignKey(Family, on_delete=models.DO_NOTHING, editable=True, null=False, blank=False) class Firmware(models.Model): firmware_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) version = models.CharField(max_length=50, help_text='The \'version number\' of the firmware', editable=True) model_id = models.ManyToManyField(ProductModel, editable=True) *View: class FirmwareListView(ListView): model = Firmware context_object_name = 'firmwares' qs = QuerySet() … -
Group Django queryset into separate sections depending on choice
I've got the following Django model: class Product(models.Model): HARDWARE = 'H' SOFTWARE = 'S' CATEGORY_CHOICES = ( (HARDWARE, 'Hardware'), (SOFTWARE, 'Software'), ) name = models.CharField(max_length=100) category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, default=HARDWARE) I'd like to display all products in a template, separated into Hardware and Software. {% for category in grouped_by_category %} <h1>{{category.name}}</h1> <ul> {% for product in category.products %} <li>{{product.name}}</li> {% endfor %} </ul> {% endfor %} This is what I have, but it just seems inefficient. def grouped_by_category(): grouped_products = [] all_products = Product.objects.all() for key, name in Product.CATEGORY_CHOICES: category_products = [] for product in all_products: if product.category == key: category_products.append(product) grouped_products.append({'name': name, 'products':category_products}) return grouped_products -
Replies to Comments submitted as new comments in Django
I am trying to add a reply to comments to posts in a blog, every time a reply is submitted it is added as a new comment not a reply although I have filtered comments to reply = None in the views.py Here are models.py: class Post(models.Model): ---------------------------------------- title = models.CharField(max_length=100) likes = models.ManyToManyField( User, related_name='liked', blank=True) slug = models.SlugField(blank=True, null=True, max_length=120) class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey( User, on_delete=models.CASCADE) reply = models.ForeignKey( 'Comment', on_delete=models.CASCADE, null=True, related_name="replies") content = models.TextField(max_length=160) Here are the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return … -
How to add profile picture on django
I have been trying to add a profile picture to users but the file seems to be "unknown" so I think the error is on the profile.html but I dont know how to fix it. views.py def profile(request, username=None): if username: post_owner = get_object_or_404(User, username=username) user_posts = Profile.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts = Profile.objects.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, } return render(request, 'profile.html', args1) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank="True", default="default.png") def __str__(self): return f'{self.user.username} Profile' profile.hmtl <h2 class="account-heading">{{ post_owner.username }}</h2> <img class="account-img" src="{{ user.profile.profile_pics.url }}" style="max-width: 300px; max-height: 300px;margin-left: 15px;margin-right:15px;"> <h2 class="account-heading">{{ post_owner.first_name }}</h2> btw I have pillow installed, but I will add the settings.py and urls.y so that you van see it:) views.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django template query for loop render taking too much time
I have a related query of limit 10 of an object. It's taking over 9s to load the whole page in development mode. When I'm not running the related query for loop on template, it only takes 1s to load. I'm quite confused what's going on in here! Please help me identify the problem/what I'm doing wrong here! Thanks in advance! Here' my view file code - related = News.objects.filter( is_active=True, status='public', language=request.LANGUAGE_CODE, category=news.category ).order_by('-published_at')[:10] And here's the loop on template file - {% for r in related %} <li class="row mb-4"> <a href="{% url 'single_news' r.id %}" class="col-5"> <img src="{{ r.featured_image.url }}" alt="Image" class="rounded img-fluid"> </a> <div class="col-7"> <a href="{% url 'single_news' r.id %}" class="no-underline"> <h6 class="mb-3 h5 text-charcoal">{{ r.heading }}</h6> </a> <div class="d-flex text-small"> <span class="text-muted ml-1">{{ r.published_at }}</span> </div> </div> </li> {% endfor %} Here's the django-debug-ttolbar image of the query time -