Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not to render all columns in UI Django HTML Template
In my UI I can see all the columns as default. I do not want to view all the columns in my UI, how do do that? In this picture I have four columns by default I do not want to view EMAIL as the default -
Django - not able to upload files/images correctly
I am building a Django application (run in local) and I am having headaches about uploading files/pictures. I have read tons of questions/answers everywhere as well as followed the official doc, but somehow I still have problems. In models.py, I have the following: class Documents(models.Model): hkid = models.ImageField("HKID", upload_to='images/', null=False) Corresponding view in views.py: class ApplicationUploadView(LoginRequiredMixin, CreateView): model = Documents template_name = "home/application.html" fields = '__all__' success_url = reverse_lazy('completion') def form_valid(self, form): print("form is valid") //other stuff.. return super().form_valid(form) In settings.py, I have added (as explained in the docs): MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And finally, I added this at the end of my urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I run the application, everything works fine - I uploade the picture in the form, and the "form is valid" is also printed on the screen. However, no picture is uploaded at all inside media/ or media/images folder. However, if I remove the two MEDIA_ROOT and MEDIA_URL lines in settings.py and I remove the "urlpatterns +=" line in urls.py, the picture instead is correctly uploaded, but in a 'images' folder (not inside media, though). However, if I try to open the picture from the admin panel, which has … -
How can I return the real user after django social-auth-app-django?
In my django project I am using django social-auth-app-django for google login to website.Everything is fine,but When user wants to login with google,if user has registired website before,I want to return this user.So ı don't want to create new user.Hox can I do that.I guess ı have to use SOCIAL_AUTH_PIPELINE but I don't know exactly this is works.Can anyone help me for that?? -
i want to integrate my android studio app with paypal restapi using django server
i want to integrate my app with paypal using Rest-API .I am using django on server-side .i need server-side implementation code to integrate my app? -
Serving file asyncronously with Django and uvicorn
I have a Django view that serves the content of a file. The Django application was running with WSGI until recently. This worked fine. Then I adapted my application to use ASGI running uvicorn. The file serving is now broken as it seems to loose the connection. How can I serve the file asynchronously with Django and uvicorn? Current view: class FileServeView(View): def get(self, request, *args, **kwargs): # ... return HttpResponse( FileWrapper(file_content), content_type="application/octet-stream" ) The server is throwing the following error: ERROR: Exception in ASGI application Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 377, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/asgi2.py", line 17, in __call__ await instance(receive, send) File "/usr/local/lib/python3.8/site-packages/channels/http.py", line 192, in __call__ await self.handle(body_stream) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 382, in __call__ raise RuntimeError( RuntimeError: Single thread executor already being used, would deadlock I'm using: Django 3.2.13 uvicorn 0.17.1 channels 2.3.1 asgiref 3.5.0 -
Limit prefetch_related to 1 by a certain criteria
So I have models like these class Status(models.Mode): name = models.CharField(max_length=255, choices=StatusName.choices, unique=True) class Case(models.Model): # has some fields class CaseStatus(models.Model): case = models.ForeignKey("cases.Case", on_delete=models.CASCADE, related_name="case_statuses") status = models.ForeignKey("cases.Status", on_delete=models.CASCADE, related_name="case_statuses") created = models.DateTimeField(auto_now_add=True) class Status(models.Model): I need to filter the cases on the basis of the status of their case-status but the catch is only the latest case-status should be taken into account. To get Case objects based on all the case-statuses, this query works: Case.objects.filter(case_statuses__status=status_name) I need to get the Case objects such that only their latest case_status object (descending created) is taken into account. Something like this is what I am looking for: Case.objects.filter(case_statuses__order_by_created_first__status=status_name) I have tried Prefetch as well but doesnt seem to work with my use-case sub_query = CaseStatus.objects.filter( id=CaseStatus.objects.select_related('case').order_by('-created').first().id) Case.objects.prefetch_related(Prefetch('case_statuses', queryset=sub_query)).filter( case_statuses__status=status_name) This would be easy to solve in raw postgres by using limit 1. But not sure how can I make this work in Django ORM. -
How to debug a React.js/Django-Rest-Framework application in VS Code?
How can I do debugging in VS Code for React.js/Django-Rest-Framework Application. I'm to do debugging in solo django application but When I use react as frontend, it not stop at breakpoint. -
Django Management Command not workingcif i run for loop
I write this management command but not working from django.core.management.base import BaseCommand from name.models import ProductName class Command(BaseCommand): def handle(self, *args, **options): ids=id[2704, 2709, 2711, 2824, 2825, 2826, 3101, 3102, 3437, 3438, 3439, 3440, 3441, 4256, 4257, 4258, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4424, 5125, 17315, 17320, 17322, 17328, 17345, 17356, 17375, 17386, 17390, 17415, 17425, 17437, 17443, 17445, 17447, 17451, 17454, 17515, 17519, 17525, 17604, 17610, 17624, 17627, 17634, 17636, 17642, 17648, 17656, 17659, 17680, 17690, 17694, 17700, 17704, 17721, 17724, 17734, 17737, 17744, 17746, 17749, 17752, 17767, 17780, 17786, 17792, 17798, 17801, 17813, 17837, 17839, 17851, 17853, 17863, 17881, 17919, 17925, 17945, 17947, 17952, 17955, 17976, 17986, 18016, 18018, 18022, 18030, 18040, 18046, 18055, 18066, 18072, 18108, 18155, 18163, 18173, 18188, 18205, 18211, 18221, 18234, 18247, 18260, 18273, 18294, 18297, 18321, 18519] for i in ids: name = ProductName.objects.filter(i).update(active=False) print(f"The total number of activated ProductName {name}") -
How to use forloop.counter using key and value in django template language
I have a for loop in template. But it has key and value so when I try to use {{forloop.counter0}} it counts by twos. I guess it consider keys and values while counting My code is this: {% for key,value in LANGUAGES %} <p>{{ forloop.counter0 }}</p> <p>{{ key }}</p> <p>{{ value }}</p> <br> {% endfor %} But returns: 0 en English 2 es Spanish But I need this result: 0 en English 1 es Spanish -
Processing multiple files in django filefield
I'm trying to let the user upload several files in a fileuploadfield, which are processed and stored in a database. models.py class MyModel(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='', blank=True, null=True) document = FileField(null=True, blank=True, upload_to="documents") forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = [ 'document' ] labels = { 'document': 'upload documents here' } widgets = { 'document': ClearableFileInput(attrs={'multiple': True}) } views.py if form.is_valid(): counter = 0 for f in request.FILES.getlist('document'): instance = form2.save(commit=False) instance.user = request.user instance.title = counter instance.save() counter += 1 return redirect('overview', num) What happens here is that this loop keeps getting applied to only one instance for every document i upload. If I upload 3 documents, I am supposed to get three separate stored entries in the database called 0, 1, 2. But what happens is that I only get one called 2. What am I doing wrong? -
Python Django Oauth Toolkit with JWT
How can i replace random string token to JWT token in django oauth toolkit? Anyone explain to me with sample? 1 i want to be like this 2 -
How to use forloop.counter if key, value in django template language
I have a fro loop in template. But it has key,value so when I try to use {{forloop.counter}} it counts by twos. {% for job in jobs %} <p>{{ forloop.counter }}</p> <p>{{ job.title }}</p> <br> {% endfor %} Result is: 1 job1 2 job2 What I need is this: {% for job,value in jobs %} <p>{{ forloop.counter }}</p> <p>{{ job.title }}</p> <br> {% endfor %} But result is: 1 job1 4 job2 I need: 1 job1 4 job2 -
docker mysql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I have created a MySQL container and hope to execute shell script in the container and execute SQL statement to get the return result, which is a part of my Django project. Using docker library to create container and execute script in Python program, I get ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)。 But when I execute the same command in the shell to create the container and execute the script, there will be no error. I want to know why. Who can help me, thank you! enter image description here enter image description here -
Django sitemap url page is still showing example.com in the place of my domain, domain.com
I pushed my code to production server and updated sites in Django admin page. But when i check sitemap.xml url, its still showing with example.com domain. Tried many ways of updation, but not working. would be helpful if I get some inputs to clear the error and move forward. -
Django : Media file not found when deleting despite it's correctly written when creating (PROD)
I've been searching in vain for a long time the origin of this issue. Everything works well on development : csv file upload + deletion but in production, file is well uploaded when saving my model but it's not found when I want to delete it. views.py (file_name = sources/newone/egr-2022-light_copie.csv) os.remove(f"media/{str(flow.fl_file_name)}") settings.py. (custom settings file for prod) BASE_DIR = Path(__file__).resolve().parent.parent [...] MEDIA_ROOT = '/home/django/httpdocs/gsm2/media' MEDIA_URL = '/media/' apache conf (+ssl) [...] Alias /static /home/django/httpdocs/gsm2/static <Directory /home/django/httpdocs/gsm2/static> Require all granted </Directory> Alias /media /home/django/httpdocs/gsm2/media <Directory /home/django/httpdocs/gsm2/media> Require all granted </Directory> <Directory /home/django/httpdocs/gsm2/gsm2> [...] I have tried to : modify the path used in remove() by removing media/... without success. modify the path used in remove() by adding gsm2/in front of media/ ... uselessly. to replace my settings.py media path with MEDIA_ROOT = os.path.join(BASE_DIR, 'media')... not better Changed folder rights to 777 and ownership to 'django' ... in vain Any idea about the possible origins of my pains ? -
How to work many to one relationship in django
Hello friends I am trying to figure out how to work properly with a One to Many relationship. I want to create two models, The first model is Post And a second model is Comment Now I say that every post has many comments, and every comment has one post. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) message = models.TextField(max_length=256,null=True) def __str__(self): return str(self.title) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) message = models.TextField(max_length=256, null=True) I'm trying to figure out how I can get all the posts and all the comments so that all the comments match the post to which they belong That is, in the functions in the views file how do I send back this option. because on the HTML page I want to display the post with all its comments but there are a number of posts, so how do I do that? The only thought I can do is this: dict = {} all_posts = Post.objects.all() for post in all_posts: dict[post] = Comment.objects.filter(post=post).values() print(dict) but I have a feeling there is something better -
Tiltled previous and next blog using django class based view
If I open a blog detail, there should be the previous blog and next blog title as a pagination. From Django documentation, I implemented the pagination by page number. But how can I implement the pagination by previous blog and next blog title. Here is my model.py: class Post(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") cover = models.ImageField(upload_to="Uploaded/") content = RichTextUploadingField(blank=True, null=True) sticker = models.CharField(max_length=50, unique=False, null=True, blank=True) published_at = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=STATUS, default=0) tags = models.CharField(max_length=400, null=True, blank=True) class Meta: ordering = ['-published_at'] def __str__(self): return self.title views.py class PostDetail(generic.DetailView): model = Post template_name = 'blogs/post_detail.html' post_detail.html {% extends "blogs/base.html" %} {% load static %} {% block post %} <section class="services"> <dev class="box-container"> <div class="box-lg"> <h3>{{ post.title }}</h3> <img src="/Images/{{ post.cover }}" > <hr> <small>{{ post.published_at }}</small> <p>{{ post.content | safe }}</p> </div> </dev> </section> <!-- Pagination Start --> <div class="center"> </div> <!-- Pagination Ends --> {% endblock post %} Now please help me how to do the prev-next blog titled pagination like the below image! titled pagination image -
set ManyToManyField with particular users from another model's ManyToMany Field
I am building a simple blog app in which I am trying to add particular users from another model's ManyToFieldField to a new model's ManyToFieldField. class ClassGroup(models.Model): admins = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admins') members = models.ManyToManyField(settings.AITH_USER_MODEL) title = models.CharField(max_length=9999, default='') class ClassGroupInvite(models.Model): invite_sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) invite_receiver = models.ManyToManyField(ClassGroup.admins) As you can see that I am filtering (send request only to class group admins) in ClassGroupInvite with setting ManyToManyField with ClassGroup.admins But when I try this then it is showing ManyToManyField(<django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x000001CE78793280>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self' I also read the documentation about it, But I didn't find anything about defining it. then I tried using ClassGroup.admins.all then it showed AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' I have tried many times but it is still not working, Any help would be much Appreciated. Thank You in Advance. -
Django: Removing duplicated data in model
I am getting a data directly from an API and store it in list in dictionary format and then loads the data into the database , but whenever i open that page the data gets duplicated even tho i am clearing the list. -
find out when user leaves a page in django
I have an ajax function that sends requests to a Django view every second: function get_updates() { $.ajax({ url: full_path, type: 'GET', data: {latest_pk: latest_pk}, success: function(json) { ... }, complete: function(data) { setTimeout(get_updates, 1000); } }); } get_updates(); get method of the view is like this: def get(self, request, *args, **kwargs): if request.GET: # If there are GET parameters, use them to return updates. response = self.get_updates(request.GET.get("latest_pk")) return JsonResponse(response) else: # Otherwise if the url is simply requested, # return the rendered chat page. return super().get(request, *args, **kwargs) How can I execute some code in Django, after requests stopped being sent? I need to save the time of the last request. -
DRF and django_filters. Change queryset before applying filters
There is a ModelViewSet and a FilterSet that work great. But the problem is that I need to transform the queryset before filtering, for this I overridden the get_queryset() method. It changes the queryset, but as a result, on the page with a list of objects, I see that no changes have occurred. If I override the list() method using the rewritten get_queryset() method in it: queryset = self.get_queryset() Changes will occur, but filters will not work on this queryset. I tried using: qs = self.filter_queryset(self.get_queryset()) in this case, the filters work, but the data on the page remains as it was before the change in get_queryset(). Please tell me what is my mistake, why can't I filter the queryset with changes and what should be done to make the filtering of the transformed queryset possible? -
i have to make a relation between movie and actor without using manytomany field i have to use only foreign key in django i've write this code so far
models.py class Movielist(models.Model) : Title = models.CharField(max_length=1000) Description = models.TextField(blank=True) ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True) # NoOfActors = models.IntegerField() Upvote = models.IntegerField(default=0) Downvote = models.IntegerField(default=0) def __str__(self): return self.Title class Actorlist(models.Model): Name = models.CharField(max_length=1000) DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True) # NoOfActors = models.IntegerField() def __str__(self): return self.Name class ActorInMovie(models.Model): Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True) Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True) def __str__(self): return self.Movie.Title views.py def Movie_Detail(request): MovieName = Movielist.objects.all() tablelist = ActorInMovie.objects.all() return render(request, 'Collection/index.html', {'MovieName':MovieName, 'tablelist':tablelist}) index.html <table border="solid"> <th>Name</th> <th>Release Date</th> <th>Actors</th> {% for data in MovieName %} <tr> <td>{{ data.Title }}</td> <td>{{ data.ReleaseDate }}</td> <td> <ul> {% for name in tablelist %} <li>{{ name.Actor.Name }}</li> {% endfor %} </ul> </td> </tr> {% endfor %} </table> **i have getting this out put can any any one tell me how to filter this data only my movie id i would like if someone come and help me in solving this problem [this is the output what i am getting but i want filter actors name by movielist.id][1] [1]: https://i.stack.imgur.com/BlAuP.png** -
How to render not to see all the columns as default , user can select the column which they want to see
I am trying to not to make the columns as visiable as default , So by this html redering i can see all the columns but i want just one column not to show as default , but user can view the file if user want to to see the column. the django template configure column. {% extends "admin/base_site.html" %} <!-- LOADING --> {% load i18n grp_tags admin_urls static admin_list %} <!-- STYLESHEETS --> {% block stylesheets %} {{ block.super }} {{ media.css }} {% endblock %} <!-- BREADCRUMBS -- > {% block breadcrumbs %} {% if not is_popup %} <ul class="grp-horizontal-list"> <li><a href="{% url 'admin:index' %}">{% trans "Home" %}</a></li> <li><a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a></li> <li>{{ opts.verbose_name_plural|capfirst }}</li> </ul> {% endif %} {% endblock %} <!-- CONTENT-TITLE --> {% block content_title %} <h1>Columns for {{ opts.verbose_name|capfirst }} list</h1> {% endblock %} <!-- OBJECT-TOOLS --> {% block object-tools %} <ul class="grp-object-tools"> {% block object-tools-items %} {% if has_add_permission %} {% url opts|admin_urlname:'add' as add_url %} <li><a href="{% add_preserved_filters add_url is_popup to_field %}" class="grp-add-link grp-state-focus">{% blocktrans with opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}</a></li> {% endif %} {% endblock %} </ul> {% endblock %} <!-- CONTENT --> … -
Opening Local Desktop Applications from website button
I want to open a Desktop Application from the Website button. The Desktop Application actually uses the username and password to load so it will also be passed. The problem is that the Website works locally but does not work when hosted... I used OsPopen and Os.system to open the applications(which works locally). os.system('putty username@servername -pw password') os.Popen('putty username@servername -pw password') Custom Protocol Handler was tried but I am not able to pass the username and Password. Any Help would be really appreciated and would do wonders!! -
css does not work for <img src="{{i.image.url}}"> in django
I have an image tag in my html tags that wants to add an image to template through admin page of django. html: <body> {% for i in pr%} <div class='card'> <div class="number">{{i.number}}</div> <img src="{{i.image.url}}"> <span class="prname">{{i.name}}</span> <p id="id">{{i.description}}</p> <button><span class="price"> ${{i.price}}</span> <img id='add'src="{% static 'add.png'%}"> Add to cart</button> </div> {%endfor%} </body> i set up my media root and i can see the image in browser but my css about that image tag does not work. css: .card image{ max-height: 100%; max-width: 100%; } urls: urlpatterns = [ path('admin/', admin.site.urls), path('',views.a) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) a part of settings: > # Static files (CSS, JavaScript, Images) > # https://docs.djangoproject.com/en/4.0/howto/static-files/ > > STATIC_URL = '/static/' > STATICFILES_DIRS=[os.path.join(BASE_DIR,'static'), ] > > # Default primary key field type > # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field > > DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' > > MEDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' How can i add some css to <img src="{{i.image.url}}">?