Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery task is not getting registerd
So I am using celery to run a task in an assigned time. I used ClockedSchedule since I wanted to run the task only one time in a particular time. clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=time PeriodicTask.objects.create( name=slug, task="account.tasks.send_money", clocked=clocked, one_off=True ) # creating periodic task using celery to run the task at scheduled time So when i run the code, PeriodicTask object is created. Task(custom) field is saved. but Task(registered) field is not being saved. So when it tries to run the task, I get the following error: [2022-07-05 11:19:00,035: ERROR/MainProcess] Received unregistered task of type 'account.tasks.send_money'. The message has been ignored and discarded. Please help me to find out the reason behind it. -
How to access a post author's profile picture in Django?
I am trying to display a username's profile picture in a blog/social media app when some user clicks on some other user's username but it is currently not working. In my template: (I think my issue is I don't have access to post?) <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> My users\models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) In my blog/models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I can retrieve some user's username by {{ view.kwargs.username }}, how can I do this with profile pictures? -
Convert Xml and Json file to string in Django
I Have data in XML and JSON and I want to upload it into MongoDB, but in string type. So how do I convert all files into a string and upload them into MongoDB ? -
To build an API for data transfer between MSSQL database and MySQL
I've built 2 websoftwares one with .Net and MSSQL server, the other with Django and MySQL. Now I want to transfer datas which falls in MSSQL to MySQL automatically. Is it possible to build an API for that?? I've no idea how to do it. Thanks in advance. -
Expected pk value, received str (pk is a CharField)
Hi i am new to django and html and I am making a shopping CRUD project with models Producst,categories,Sub_categories,size,colors using SERIALIZERS. I am now trying to make crud of categories,and while inserting I am getting the following error: "{'category_name': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]}" below is my show_cat function def show_cat(request): showcategory = Categories.objects.filter(isactive=True) #print(showall) serializer = CategoriesSerializer(showcategory,many=True) #print(serializer.data) return render(request,'polls/show_cat.html',{"data":serializer.data}) insert_cat function def insert_cat(request): if request.method == "POST": insertcategory = {} insertcategory['category_name']=request.POST.get('category_name') insertcategory['category_description']=request.POST.get('category_description') form = CategoriesSerializer(data=insertcategory) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') return redirect('categories:show_cat') else: print(form.errors) return redirect('categories:show_cat') else: return render(request,'polls/insert_cat.html') below is html for insert <tr> <td>Category Name</td> <td> <input type="text" name="category_name" placeholder="CATEGORIES"> </td> </tr> <tr> <td>Description</td> <td> <textarea name="category_description" id="" cols="30" rows="10"> </textarea> </td> </tr> below is the showcategory html page {% for result in data %} <tbody> <tr> <td><b>{{result.category_name}}</b></td> <td><b>{{result.category_description}}</b></td> <td style="position: relative;left:50px;"> <a href="categories/edit_cat/{{result.id}}"> <button class="btn btn-primary"> <i class="fa-solid fa-pen-to-square">EDIT</i> </button> </a> </td> <td> <a href="{% url 'categories:del_cat' result.id %}" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> <i class="fa-solid fa-trash">DELETE</i> </button> </a> </td> </tr> </tbody> {% endfor %} </table> Where am I going wrong in the code -
django media images forbidden
I got a weird bug: after deploying my django project to server, particular media folder is 403 forbidden for no reason (others work fine), here's a tree diagram of my media folder. . ├── [drwx------] avatar │ ├── [-rw-r--r--] 1.png │ ├── [-rw-r--r--] 10.png │ ├── [-rw-r--r--] 11.png │ ├── [-rw-r--r--] 77.png │ ├── [-rw-r--r--] 78.png │ ├── [-rw-r--r--] 79.png ├── [drwxr-xr-x] cdn │ ├── [drwxr-xr-x] css │ │ ├── [-rw-r--r--] console.css │ │ ├── [-rw-r--r--] demo.css │ │ ├── [-rw-r--r--] demo_list_jYn4xiM.css │ │ └── [-rw-r--r--] shelf.css │ ├── [drwxr-xr-x] js │ │ ├── [-rw-r--r--] demo.js │ │ └── [-rw-r--r--] ui.js │ └── [drwxr-xr-x] webfonts │ ├── [-rw-r--r--] fa-regular-400.woff2 │ └── [-rw-r--r--] fa-solid-900.woff2 ├── [drwxr-xr-x] common │ ├── [-rw-r--r--] 172-1720825_small.jpg │ └── [-rw-r--r--] bg2.jpg ├── [drwxr-xr-x] demo │ └── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm.png ├── [drwxr-xr-x] look │ ├── [-rw-r--r--] 2625191.JPG │ └── [-rw-r--r--] me.jpg ├── [drwxr-xr-x] portray │ ├── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm.png │ ├── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm_VsswTUf.png │ └── [-rw-r--r--] Screen_Shot_2021-08-16_at_3.45.01_pm_XIA2JgY.png ├── [drwxr-xr-x] profile │ ├── [-rw-r--r--] IMG_1684.JPG │ └── [-rw-r--r--] me.jpg ├── [drwxr-xr-x] projects │ └── [-rw-r--r--] default.jpg ├── [drwxr-xr-x] team │ └── [-rw-r--r--] default.jpg ├── [drwxr-xr-x] thumbnail │ ├── [-rw-r--r--] seagull_Z2AYe1w.png │ └── [-rw-r--r--] typescript-in-react.png └── [drwxr-xr-x] video ├── [-rw-r--r--] card.mp4 ├── … -
i have an error when using django for loop in script tag
i have an error when using django for loop in script tag`enter <script> $('#cat_input').hide() $('#addcat').click(function(){ $('#cat_input').show() }); $('#backcat').click(function(){ $('#cat_input').hide() }); {% for book in books %} $(".cat{{book.category.id}}").click(function(){ $(".book_hide").hide() $(".book{{book.category.id}}}").show() }); {% endfor %} </script> code here` enter image description here -
How to replace get_declared_classes() from CakePHP to Python?
I have been moving website made in Cakephp into Django. In one place I found get_declared_classes(). I thinks this function returns list of previously used classes before running current class. First time when I encounter this, I just store list of classes manually in one file and I was using that and this solution worked only for a particular web page but Now I have multiple pages calling this class and everytime list of classnames are very different so I can not store class name list. If question is not clear please let me know, I can provide more information. Is there any other library that can replace this function in Python? Or Is there any other solution I can try ? -
Way to Filter by DB Field in Django using Class Views
I tried to search for answers, but after a few days, I'm here asking: I'm a beginner, making a todo list app - expanding on a tutorial I followed. Currently, it's filtering by user, which is fine, but I also want to filter by a field in the DB (list). Models: class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['created'] class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) list = models.ForeignKey(ToDoList, on_delete=models.CASCADE) def __str__(self): return self.title class Meta: ordering = ['complete'] View I'm trying to change: class TaskList(LoginRequiredMixin, ListView): model = Task context_object_name = "tasks" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tasks'] = context['tasks'].filter(user=self.request.user) context['count'] = context['tasks'].filter(complete=False).count search_input = self.request.GET.get('search-area') or '' if search_input: context['tasks'] = context['tasks'].filter(title__startswith=search_input) context['search_input'] = search_input return context Also, is there a way to access the list variable in the html component, like here? url: path('tasks/<list>/create', TaskCreate.as_view(), name="task-create"), html: <a href="{% url 'tasks' 'task.list' %}">&#8592; Back</a> -
all cloud platforms like Heroku and digital ocean require billing card
Hi I want to deploy my Django app to Heroku and when I want to use add-ons like ClearDB MySQL it requires me to verify my account by giving Heroku my billing card the problem is I'm in a country that is restricted by US law and we don't have global cards so I cant use mine as I searched all over the web for cloud platforms it seems that all of them require such verification do you have any solution for that ? or any platform that won't require such verification? -
TypeError: get() missing 1 required positional argument: 'id'; RequestFactory
I'm testing a view UserProfilePage with a mock request object using RequestFactory. An error is being raised when invoking the GET handler; saying a positional argument is missing. Yet there are not positional arguments within the request. What would be raising this error? Traceback (most recent call last): File "C:\..\site-packages\django\test\testcases.py", line 1201, in setUpClass cls.setUpTestData() File "C:\..\authors\test\test_views.py", line 110, in setUpTestData request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) File "C:\..\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\..\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) TypeError: get() missing 1 required positional argument: 'id' class TestViewUserQuestionsPostedPage(TestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("ItsMe") viewer = get_user_model().objects.create_user("ItsYou") request = RequestFactory().get(reverse("authors:profile", kwargs={'id': 1})) cls.view = UserProfilePage.as_view()(request).view_class cls.view_context = cls.view.get_context_data() def test_viewed_profile_of_user(self): self.assertIsInstance(self.view, Page) self.assertIn('user', self.view_context) self.assertEqual(self.view_context['object'], self.user) class Page(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data() context['search_form'] = SearchForm() return context class UserProfilePage(Page, SingleObjectMixin): model = get_user_model() pk_url_kwarg = "id" def get(self, request, id): return HttpResponse("Hi") authors_patterns = ([ path("<id>", av.UserProfilePage.as_view(), name="profile") ], "authors") urlpatterns = [ path("users/", include(authors_patterns, namespace="authors")) ] -
How can I add query paramater with html form?
Now I'm making a web app with django. I want to put more than 2 query paramaters into my URL, but if I put some keywords into my search box and send them, the query paramater will show only these keywords. For example, current URL is like below. https://example.com/jobs?area=SYDNEY If I search something, it becomes below. https://example.com/jobs?query=something This is not what I want. What I want is https://example.com/jobs?area=SYDNEY&query=something How can I do it? <form action="" method="get"> <input type="text" name="query" value="{{ request.GET.query }}"><input type="submit" value="Search"> </form> -
HTMX sortable works only once, rendering makes it disabled
I am referring to BugBytes channel on YouTube about sortable menu with Django. (Django and HTMX #6 (part 1) - Building a Sortable Drag and Drop Interface ) https://www.youtube.com/watch?v=V-f_yYKUJo8 (Django and HTMX #6 (part 2) - Building a Sortable Drag and Drop Interface ) https://www.youtube.com/watch?v=5Fuwo4tVXmE Some people got stuck by the same issue but found a clue getting through it. I couldn't have any complication. Same question found in StackOverflow here."Sortable JS breaks upon htmx rendering a partial" And I don't think that Answer seems to show any solutions. In my case, following the BugBytes tutorial video and the repository, I made the following Django files. books.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>List Books</title> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://unpkg.com/htmx.org@1.7.0" integrity="sha384-EzBXYPt0/T6gxNp0nuPtLkmRpmDBbjg6WmCUZRLXBBwYYmwAUxzlSGej0ARHX0Bo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script> </head> <body> <section id="book_list"> {% include 'list_books.html' %} </section> <script> document.body.addEventListener('htmx:configRequest', (event) => { event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}'; }) htmx.onLoad(function(content) { var sortables = content.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable = sortables[i]; new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); } }) </script> </body> </html> list_books.html {% csrf_token %} <form class="sortable" … -
Unable to add initial/auto tags tags using tagulous by post-save signal
I am Unable to add initial/auto tags tags using tagulous by post-save signal. I am working on a project which contains smart phones Brands, models, and their specific firmware files. What I want to do is to while posting a table I want to copy brand name model name and the files title into the tags field along with presets of tags. To do so I am using post save signals from django and it outputs the following: I am trying to do add initial tags and also want to copy the title model brand fields to tags but code throughs below error def tag_set(sender, instance,*arg, **kwargs): ans= array_tag(instance) instance.Tags.add(ans) post_save.connect(tag_set, sender=resource) def array_tag(instance): return [instance.title ,instance.desc,instance.size, instance.Brand.title ,instance.Model.title ,instance.Categories.title] Error 'list' object has no attribute 'pk' below are the code settings i used Models.py class Skill(tagulous.models.TagTreeModel): class TagMeta: initial = [ "Python/Django", "Python/Flask", "JavaScript/JQuery", "JavaScript/Angular.js", "Linux/nginx", "Linux/uwsgi",] space_delimiter = False autocomplete_view = "resource_skills_autocomplete" class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(max_length=200, null=True,blank=True) Tags = tagulous.models.TagField( to=Skill, help_text="This field does not split on spaces" ) Settings.py SERIALIZATION_MODULES = { 'xml': 'tagulous.serializers.xml_serializer', 'json': … -
I want to use like button with ajax but I have a problem.The error I get when I click the like button(Not Found: /like)
POST http://127.0.0.1:8000/like 404 (Not Found) I am quite a novice at this. I think the error is due to the url redirection, but the urls I use do not work, what should I use? What I'm trying to achieve is to like the post without refreshing the page when I click the like button. models.py class Post(models.Model): likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') views.py @ login_required def like(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('postid')) post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) urls.py urlpatterns = [ path('like', like, name='like'), ] myscript <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like" %}', data: { postid: $('#like-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] }, error: function (xhr, errmsg, err) { } }); }) </script> post_detail.html {% if request.user.is_authenticated %} <div class="pr-2"> <span class="" id="like_count">{{post.like_count}}</span> <button class="btn btn-link text-dark p-0 border-0 btn-outline-light" id="like-button" value="{{post.id}}"> <svg width="1.5em" height="1.5em" viewBox="0 0 16 16" class="bibiheart"fill="currentColor"xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd"d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 … -
running an old django project on a new database
I have a django project code, there are 10 applications in it, and about 50 models that have relationships (foreign keys) with each other. There are no migration files. I need to run this project. The database is empty. Tell me, pls, what should be my steps for the correct launch of the project? Are the following commands sufficient? python manage.py makemigrations python manage.py migrate python manage.py runserver -
How to include model-choice-iterators into views
I have been looking at form fields in the django documentation Iterating relationship choices but finding it a little hard to understand. I want to develop a form field with an iterator whereby, In the select I get the title of the cruise, and in the options for data-ship_name I get the according ship names, and for text I get the destinations. However, I am not sure how to implement the form into the views/html. Here's what I have tried: models.py from django.db import models class Cruises(models.Model): id = models.CharField(db_column='ID', primary_key=True, max_length=200) # Field name made lowercase. title = models.CharField(max_length=200, blank=True, null=True) ship_name = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'items' def __str__(self): return self.title class Destination(models.Model): location = models.ForeignKey(Cruises, on_delete=models.CASCADE, blank=True, null=True) destination = models.CharField(max_length=200, blank=True, null=True) views.py from django.shortcuts import render from .models import Cruises def basic(request): #form_destination = Cruises long_list = Cruises.objects.values('title', 'ship_name') return render(request, 'cruises/basic.html', context = {'long_list':long_list}) forms.py from django import forms from cruises.models import Cruises, Destination class CruiseSelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex, attrs) if value: option['attrs']['data-ship_name'] = value.instance.ship_name return option class destinationForm(forms.ModelForm): class Meta: model = Destination … -
In a Django template, how do you refer to a static image using a variable?
The following is what I have in my Django template: {% extends 'base.html' %} {% load static %} {% block content %} {% for department in departments %} <img src="{% static 'store/images/product_name.jpg' %}" alt="product photo"> <p>{{ department.name.title }}</p> {% endfor %} {% endblock content %} The same image displays for each iteration, but I want each element in the for loop to display its own image. The path to the each image is stored as a value in the "image_location" key for each item. This is what I've tried (the key, "department.image_location", has the value "store/images/<product_name>.jpg"): {% extends 'base.html' %} {% load static %} {% block content %} {% for department in departments %} <img src="{% static department.image_location %}" alt="product photo"> <p>{{ department.name.title }}</p> {% endfor %} {% endblock content %} I have also tried: "{% static {{department.image_location}} %}" I have also set the key value to "product_name.jpg" and then trying: "{% static /store/images/ %}{{department.image_location}}" None of these work. Is there a way to use a key's value to show a static image? -
__init__() missing 1 required positional argument: 'get_response' error on Django HttpOnly JWT solution
I currently have a Django setup that followed the guide below. Pretty much, it's a workaround that allows for HTTPOnly cookies to be used with Django Rest Framework JWT authentication. It worked fine in Django 3.2, but I'm attempting to upgrade to Django 4, and I'm now running into the error below How to store JWT tokens in HttpOnly cookies with DRF djangorestframework-simplejwt package? Error: __init__() missing 1 required positional argument: 'get_response' I'm still a bit new to Django and DRF, so I have no idea what could be going on. -
Form Issue trying to add a word to an URL
This is my form: <form method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> How can I append a word after the last character of the next link: http://127.0.0.1:8000/saturday/ Sorry and Thank You. -
ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must be in YYYY-MM-DD format. Is there a way to change the date format?
I'm scraping a website for data to include in my project and while fetching the date it comes in a mm-dd-yyyy format like so "July 9, 2022". Is there a way to bypass this and avoid the error? for test_job in final_jobs: newjob = Jobs.objects.create( title = test_job['title'], location = test_job['location'], date_posted = test_job['date_posted'], closing_date = test_job['closing_date'], ) the error: ValidationError: ["'\n- July 9, 2022\n' value has an invalid date format. It must be in YYYY-MM-DD format. -
i set null = true and blank = true but still get "django.db.utils.IntegrityError: (1048, "Column 'massenger_name' cannot be null")"
im trying to run my page but i get this error "django.db.utils.IntegrityError: (1048, "Column 'massenger_name' cannot be null")" and i makemigrations and imgrate again but still i have same problem and my database is mysql this my models.py from django.db import models # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=255,null=True,blank=True) action_time = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.massenger_name) and this my views.py from django.shortcuts import render from .models import Name from django.shortcuts import redirect # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input) name_in_model.save() return render(request , 'index.html') and this my index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static 'CSS/style.css' %}"> </head> <body> <div id="form"> <form class="row" method="POST"> {% csrf_token %} <div class=""> <input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name" required> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button> </div> </form> </div> </body> </html> and this my setting.py """ Django settings for Eid_G project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path … -
Google Login failed {error: 'popup_closed_by_user'} on Google login in Django
I am aware that this question has been asked multiple times. However, they were usually issues related to localhost. I have a django site where I used react for the frontend. Everything runs perfectly when I have my react at port 3000 and django at 8000. Even the google login But when I run npm run build I pasted the build folder in the django root and make all the changes in settings.py Now I directly went to localhost:8000 this error shows up on google login Manifest: Line: 1, column: 1, Syntax error. Google Login failed {error: 'popup_closed_by_user'} sometimes its even a 403 error. I tried it on both localhost and heroku and it won't work. I've been stuck on this for days. Would appreciate some help -
Hide and show elements inside Django HTML template
I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ $(".button_order").click(function(){ $(".myorders").show(); $(".myproducts").hide(); $(".mysupplier").hide(); }); $(".button_supplier").click(function(){ $(".myorders").hide(); $(".myproducts").hide(); $(".mysupplier").show(); }); }); </script> syle.css looks like; .myorders, .myproducts, .mysupplier{ font-size: 25px; display: none; } This works perfectly fine until I use normal data like; <body> {%block content %} <button class="button_order" >ORDERS</button> <button class="button_supplier" >SUPPLIER</button> <p class="myorders" > This is my order </p> <p class="mysupplier"> my supplier is cool </p> </body> But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part. <p class="myorders"> <!-- {% for element in orders %} {% for key,val in element.items %} <ul><li>{{key}}:{{val}}</li></ul> {% endfor %} <hr class="new1"> {% endfor %} --> </p> I should get product data from data base only when PRODUCT button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data. my views.py looks like from django.shortcuts import render client = MongoClient("mongodb://localhost:27017/") db=client.inventory_data def home(request): collection_data_1 = db['orders'] … -
How to show username in django admin form for the connected model?
I have two models one is user model and another one is cars model. class User(models.Model): id = models.BigAutoField(primary_key=True) username = models.CharField(max_length=50, verbose_name="User Name") class Cars(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cars') Now on /admin/app/cars/1/change/ page i want to see the username as a normal text in that form below the dropdown of users. I tried with inline stack but that didn't worked, and throwing error, User has to foreign key to Cars.