Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST in form is not getting called in django project
After the FamilyForm is Filled and redirect the PersonForm is not get post. they are two forms to fill. adding action to the form also didn't trigger it. there might be something small that has been missed in it. please help as soon as possible for any other information tag and let me know View.py def index(request): familyForm = FamilyForm() if request.method == 'POST': familyForm = FamilyForm(request.POST) if familyForm.is_valid(): familydetails = familyForm.save() return redirect(addPerson,familydetails.familyId) #return render(request, 'html/personForm.html',{"family":familydetails,'personForm':personForm}) return render(request, 'html/index.html', {"familyForm": familyForm}) def addPerson(request,FamilyID): family = FamilyDetails.objects.get(familyId=FamilyID) personForm = PersonForm() print(request.method) if request.method == 'POST': personForm = PersonForm(request.POST) print(personForm.errors) if personForm.is_valid(): personDetails = personForm.save(commit=False) print(personDetails) return HttpResponse("<h1>Form FIlled</h1>") return render(request,'html/personForm.html', {"personForm":personForm, 'family':family }) personForm.html {% extends 'html/familyCard.html' %} <div class="formRepeat"> <form method="post" action="{% url 'add_person' family.familyId %}" id="personForm" class="needs-validation" novalidate data-qualification-url="{% url 'ajax_load_qualification' %}"> {% csrf_token %} urls.py urlpatterns = [ path('', views.index, name="index"), path('addperson/<int:FamilyID>/', views.addPerson, name="add_person"), path('ajax/load-qualification/',views.load_qualification,name='ajax_load_qualification'), ] -
context data not getting displayed in inherited template
Base HTML {% load static %} {% include "navigation/navigation.html" with cat=categories only %} <!-- base template --> {% block content %} some html {% endblock%} Template B {% extends "base/index.html" %} {% block content %} <!-- product right --> Some html <!-- //product right --> <!-- //product right --> {% endblock %} My issue is when I am rendering template b its not showing the context I have passed to the navigation bar, even though when accessing the base template alone context is getting displayed fine, don't know where is the issue, -
ModuleNotFoundError: No module named 'blogpro.wsgi' in Procfile, Deploying Django using Heroku, code H10 : App crashed
I am trying to deploy django project on Heroku, it is not deploying iam getting error as follows: ModuleNotFoundError: No module named 'blogpro.wsgi see full detail error in log. Full deatil log error - click here 2021-07-30T06:58:08.676208+00:00 app[web.1]: ModuleNotFoundError: No module named 'blogpro.wsgi' 2021-07-30T06:58:08.676489+00:00 app[web.1]: [2021-07-30 06:58:08 +0000] [8] [INFO] Worker exiting (pid: 8) my Procfile content is : web: gunicorn blogpro.wsgi and see my Procfile location folder in image below : Procfile location image - click here iam not able to understand what problem is ? is it because of my procfile in wrong location (if your answer is procfile should be in root directory please specify the root directory because i don't know what root directory is)? and whether the problem is in content of Procfile ? please see all images attached to see problem clearly. -
scheduling emails using sendgrid in a django app
I have created a django app which has a model Appointment. This Appointment model has a fields like this start_time = models.DateTimeField() student = models.Charf.... parent = models.Charf... tutor = models.Charf... .... Now, I want to send email notification to student, parent and the tutor. 10 minutes before the start_time. The start_time can be any future date , time. So basically i'm trying to schedule an email as soon as an appointment is created in the database. I'm willing to use sendgrid for this but please let me know if there is any other library that can do this job. -
how to set variable in DjangoTemplates inside in a loop and use outside
I want to set a variable in a loop and use other out a loop but django template not allow me, If i do this in a view then i have to run the loop 2 times, 1 time in a view and other time in a template.. This is not a good idea I try "set" , "firstof" and 'template tag' also example code with template tag @register.simple_tag def setvar(val=None): return val {% for x in "15"|loopRunTime %} {% if x == 12 %} {% setvar x as action %} {% endif %} {% endfor %} {{ action }} 2 example is firstof {% for x in "15"|loopRunTime %} {% if x == 12 %} {% firstof x as i %} {% endif %} {% endfor %} {{ i }} -
How can I trigger a Bootstrap modal programmatically when a Django template condition is met?
Let's say one of the views returns a context with the key 'db_busy' with a String if someone is using the database. Django part: def check_status(request): context = { 'current_tab': '1' } if request.method == 'POST': if get_lock_data(): lock_data = get_lock_data() for x in lock_data: if x['user_name'] != request.user.username: context['db_busy'] = 'Warning! The database is in use by: '+x['user_name'] return render(request, 'index.html', context) So what I want in index.html is, first of all, to check if that key (db_busy) exists in the context, if it exists that means that another user is modifying the database and therefore I want to show an informative modal. What I've tried so far: Javascript part within index.html (truncated index.html): <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); {% if db_busy %} alert("{{db_busy}}"); $('#dbBusyModal').modal('show'); {% endif %} </script> The alert is working properly and showing up as expected when some user is editing the db. But for some reason, the modal is not showing. modal code (truncated index.html): <!-- Modal --> <div class="modal" id="dbBusyModal" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-sm" style="width:350px;" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Warning!</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Warning! The database in use by: test</p> </div> <div class="modal-footer"> … -
How To show The YouTube Video Data in templates from Playlist's many to many field in Django, such as video name and video url
How can I display the video details using the many to many field in Django, what should be the syntax of the templates and views to fetch the all the videos of a playlist. --Models.py-- from django.db import models # Create your models here. class Youtube_Video(models.Model): video_url = models.TextField(default="", blank=True, null=True) video_name = models.CharField(max_length=200 ,default="", blank=True, null=True) def __str__(self): return self.video_name class Playlist(models.Model): image_Url = models.TextField() playlist_Name = models.CharField(max_length=200) playlist_Desc = models.TextField() slug = models.CharField(max_length=200) video = models.ManyToManyField(Youtube_Video, blank=True) def __str__(self): return self.playlist_Name --Views.py-- def videoItem(request, slug): playlist = Playlist.objects.filter(slug=slug).first() context = { 'playlist': playlist, } return render(request, "Home/videoItem.html", context) --Templates {% extends 'base.html' %} {% block title %}Video{% endblock title %} {% block body %} <section id="videoItem"> </section> <section> <h1>{{playlist.video.video_name}}</h1> </section> {% endblock body %} -
model form is not saving in django it is telling user can not be nul
i crated a model name address and connected with user by foreign key so a user can have multiple address but it is not saving i want form to take that user id to save but i don't how to do that here is my models.py class Address(models.Model): phoneNumberRegex = RegexValidator(regex = r"^\d{10,10}$") pincodeRegex = RegexValidator(regex = r"^\d{6,6}$") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username my views.py @login_required def add_address(request, username): if request.method == 'POST': form = Addressform(request.POST) if form.is_valid(): form.save() return redirect('accounts:home') else: form = Addressform() return render(request, 'add_address.html', {'form': form}) my form.py class Addressform(forms.ModelForm): class Meta: model = Address fields = '__all__' exclude = ['user', 'joined_date', 'updated_at'] labels = { 'reciever_name':'Reciever Name', 'phone_no':'Phone No', 'alt_phone_no':'Alternate Phone No', 'state':'State/Union Territory', 'pincode':'Area Pincode', 'eighteen':'Is reciever is 18+', 'city':'City', 'address':'Address', 'locality':'Locality', } widgets = { 'eighteen': forms.RadioSelect() } … -
How to write Django filter query with GROUP BY
I am trying to fetch group by data in Django. How I Can write Django query like this SQL query:- SELECT id FROM table_name WHERE name=%s GROUP BY name" I am trying with Model.objects.filter().values('id').annotate(count=Count('name')).order_by('name') but not get unique name`s id in QuerySet -
Axios-React native PUT request
I want to send a put request to modify the title of a file, but i keep getting 400 bad request error, i m not sure on how to formulate my request so it gets accepted. this is the request : const onPressSaveName=()=>{ handleEditedItem(fileTitle); const modefiedFile=new FormData(); modefiedFile.append('label',label) modefiedFile.append('file', { uri: fileUri }); modefiedFile.append('title',inputText) const headers={ Accept:'application/json', 'Content-Type':'application/json', } const json=JSON.stringify(modefiedFile); axios .put(`http://192.168.1.17:8000/File/${key}/`,json,{headers:headers}) .then((response)=> {response.json()}) .then((error)=>{console.log(error)}) setModal(false) } this is my django backend View : elif request.method =='PUT': serializer=Fileserializers(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors,status=404) -
Access related set from a Custom QuerySet in Django?
I want to annotate additional field to my model via custom queryset and access it with a function, here is a simplified code: class CustomQuerySet(models.QuerySet): def my_func(self): return self.annotate(b_count=self.b_set.count()) # 'CustomQuerySet' object has no attribute 'b_set' class A(models.Model): objects = CustomQuerySet.as_manager() class B(models.Model): a = models.ForeignKey(A) I want to access it like this models.A.objects.my_func().all(), so an extra field would be added to my model when I want to get it. But I can't access b_set from a CustomQuerySet. Previously I was using a @property in model A, but it makes an additional DB request every time. How could I access a set of related model from a Custom QuerySet? -
Return objects with get_object and Retrieve UpdateAPIView
I am trying to use method put and return the changes of an instance of the user model with the token using get_object with RetrieveUpdateAPIView. But I only get the user data: { "id": int, "username": "", "email": "", "is_staff": bool } Is there any way to get it like this?: { "user": { "id": int, "username": "", "email": "", "is_staff": bool }, "token": "" } This in order not to change the logic on frontend; get the token for authorization with: user.token -
In subcategory selection, It show all subcategories from all Categories. Django
my Models: class Category(models.Model): category_name = models.CharField(max_length=60) class Subcategory(models.Model): subcategory_name = models.CharField(max_length=60) category = models.ForeignKey(Category, on_delete = models.CASCADE, default='', related_name="subcategory") class Product(models.Model): product_model = models.CharField(max_length=255) product_category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True, related_name="products", ) product_subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, default='', null=True, related_name="products", ) my CreateView: class CreateProduct(LoginRequiredMixin, CreateView): model = Product fields = ["product_model","product_category","product_subcategory"] template_name = "staff/create_product.html" my template: <div class="card"> <div class="card-header card-header-primary"> <h4 class="card-title">Category&Subcategory</h4> </div> <div class="card-body"> {{ form.product_category|as_crispy_field }} {{ form.product_subcategory|as_crispy_field }} </div> </div> I want when i choose an specific Category, subcategory only show me those Subcategories from that category not all Subcategories -
Unable yo load images on Django Website...shows that the image is not found
please do check the image. it also consists of the error code and the folder where it shows that the file is not found -
Geodjango Vs Geonode vs Geoserver : How Can I tradeoff among these three to use in my Django GIS Application?
I am developing a GIS based web application (Dashboard) in django, suddenly I am being stumbled with GeoNode, Now I am confused which technology stack I should choose from the above three : geodjango, geonode or geoserver. Being new in geospatial domain I even do not know does all three are same or some limitaion exist in any of the three and other fulfill that limitation? Does there was any need to for another CMS like Geonode when we have Geoserver or Geodjango? How one can tradeoff between the above to use in my django web gis application? Moreover, is it right forum to ask this question or not? Need Prophetic remarks and answer. -
Under Django concurrency, why does the generated snowflake ID repeat?
I use modules written by others, as follows: https://github.com/tarzanjw/pysnowflake/blob/master/snowflake/server/generator.py I first ran a single-threaded test by myself. There will be no duplication at all, and there is no duplication at all when multi-threaded locks are added. But when I generate it in the actual project with Django, about 10 Threads submit a total of 1600 pieces of data, and about dozens of duplicates will be generated each time I printed the ID, and this snowflake generator instance has not been initialized. How can I troubleshoot? The approximate code is as follows: from newsnow import Generator logger = logging.getLogger('django-production') get_flake_id = Generator(dc=0, worker=0) def create_product_meta(prepare_product_meta): new_product = models.productMeta( own_store=prepare_product_meta.get("own_store").upper(), product_name=prepare_product_meta.get("product_name"), ) logger.warning(id(get_flake_id)) new_product.flake_id = get_flake_id.get_next_id() return new_product Any suggestions? thanks! -
How to create a conversation list in Django chatting app
I am trying to add messaging functionality to my web app made in Django. So far, I have managed to successfully send and receive messages from user to user. But, now I have been stuck at showing all the conversation lists to the inbox.html page of the logged user. I have tried different approaches that I can think of but can not get the expected result. models.py class Messaging(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message_text = models.TextField(max_length=360, verbose_name='Write Message') message_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.sender}\'s Message to {self.receiver}' viwes.py Function to send and receive messages from user to user @login_required def messageview(request, user_name): sender_user = request.user receiver_user = User.objects.get(username=user_name) message_list = Messaging.objects.filter(sender=sender_user, receiver=receiver_user).order_by('message_date') | \ Messaging.objects.filter(receiver=sender_user, sender=receiver_user).order_by('message_date') if request.method == 'POST': msg_text = request.POST.get('msg_text') messaging = Messaging() messaging.sender = sender_user messaging.receiver = receiver_user messaging.message_text = msg_text messaging.save() return redirect(request.META['HTTP_REFERER']) context = { 'sender_user': sender_user, 'receiver_user': receiver_user, 'message_list': message_list, } return render(request, 'message.html', context) Now I want to create an inboxview in views.py that will render all the conversation of the logged user. Please guide me the way. -
Django Admin hiding objects
I have an auto-created Admin via admin.site.register(MyModel) But some of my MyModel entries are missing. This happens when I set a field called active to False, but active is a field defined by me. Why would setting active to False hide my items from django admin? One clue would be that I'm using a custom manager, but I'm not sure why this would matter given that I don't filter on this in admin. class MyModel(models.Model): ... active = models.BooleanField() objects = models.Manager() active_objects = ActiveManager() class ActiveManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(active=True) -
Serve csv file with different encoding on Django
I'm trying to serve a csv file from my webserver on local network. I'm fetching data from a database to dataframe, making some editions and trying to serve it in-memory, without saving. My code looks like this # function.py def fetch_data_cond(): ... df = pd.DataFrame(fetched_keiyakusha, columns=edited_list, dtype = 'object') df.drop(df.columns[[0, 1, 2]], axis = 1, inplace = True) s_buf = StringIO() df.to_csv(s_buf) s_buf.seek(0) x = s_buf.read() s_buf.close() return x views.py csv_file = fetch_data_cond() response = FileResponse(csv_file, content_type="text/csv") response['Content-Disposition'] = 'attachment; filename="data.csv"' return response This saving the data in UTF-8. But I would like to save it and serve it in SHIFT-JIS I tried: >>> df.to_csv(s_buf, encoding='shift-jis') >>> response = FileResponse(csv_file, content_type="text/csv; charset=shift-jis") Didn't worked at all. File was still UTF-8 encoded -
Static are not loaded during the deploy
Static are not loaded during the deploy. collectstatic was success (I see static dir with all of files on the server). docker-compose.yaml version: '3.7' services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: image: maskalev/foodgram restart: always volumes: - static_value:/code/static/ - media_value:/code/media/ depends_on: - db env_file: - ./.env nginx: image: nginx:1.19.3 ports: - '80:80' volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_value:/var/html/static/ - media_value:/var/html/media/ depends_on: - web volumes: postgres_data: static_value: media_value: nginx/default.conf server { listen 80; server_name 127.0.0.1 x.x.x.x; location /static/ { root /var/html/; } location /media/ { root /var/html/; } location / { proxy_pass http://web:8000; } } I see messages like this: nginx_1 | 2021/07/30 04:55:12 [error] 28#28: *7 open() "/var/html/static/pages/indexAuth.js" failed (2: No such file or directory), client: y.y.y.y, server: 127.0.0.1, request: "GET /static/pages/indexAuth.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/" Please, help me. -
Django can't add user first name and last last name in signup forms and getting IntegrityError
I getting this error when trying to add first name and last name in my signup froms. NOT NULL constraint failed: members_subscriber.first_name console error: return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: members_subscriber.first_name [30/Jul/2021 10:50:44] "POST /subscriber-signup/? HTTP/1.1" 500 193967 getting error after this this two line in my froms.py # error occurring for this two line first_name = self.cleaned_data.get('first_name'), last_name = self.cleaned_data.get('last_name'), forms.py class SubscriberSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = UserManagement @transaction.atomic def save(self): user = super().save(commit=False) user.is_subscriber = True user.save() Subscriber.objects.create( user=user, email=self.cleaned_data.get('email'), # error occurring for this two line first_name = self.cleaned_data.get('first_name'), last_name = self.cleaned_data.get('last_name'), ) my_group = Group.objects.get(name='subscriber') if user.is_subscriber == True: my_group.user_set.add(user) return user views.py def form_valid(self, form): form.instance.user = self.request.user user = form.save() login(self.request, user) messages.add_message(self.request, messages.INFO,'You Sucessfully Login') return redirect('blog:my-account') -
How to integrate Facebook Login in django-graphql-jwt?
We have a django project that uses the Graphene-Django library to implement a GraphQL API in our project. This backend is accessed by our mobile apps. For the authentication of the apps, we use the django-graphql-jwt library, which is a JSON Web Token library in Django with GraphQL approach. Now we want to implement the Facebook Login in our system and with it the authentication happens in Facebook. After authentication, what will be sent to our backend from the mobile app is only the email of the user. How can I register and authenticate the user in django-graphql-jwt without the password? Or is there a better workflow for this? -
NoReverseMatch at error - Issue in my HTML url
When I click my edit button (which is on a page called profile.html) I'm getting NoReverseMatch at /profile/singingstarz Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P[^/]+)/$'] The issue is one line inside my html but I can't figure out what it should be: <a class="btn btn-sm btn-info" href="{% url 'edit_post' post.id %}">View</a> urls.py urlpatterns = [ path("", views.index, name="index"), path("make_post", views.make_post, name="make_post"), path('edit_post/<str:pk>/', views.edit_post, name="edit_post"), path("profile/<str:username>", views.profile, name="profile"), ] my view currently, but I've tried many different views. The issue is in the html part because when I take it out, the profile page loads totally fine. @login_required @csrf_exempt def edit_post(request): if request.method == "POST": post_id = request.POST.get('id') new_post = request.POST.get('text') try: post = Post.objects.get(id=post_id) if post.username == request.user: post.text = new_post.strip() post.save() return JsonResponse({}, status=201) except: return JsonResponse({}, status=404) return JsonResponse({}, status=400) models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.username.username #used to be .user.username -
How to get generic model from content_type model in django
I'm stack with this problem, I have a model which has a generic relation that every model save the same field here. What I wanted to do is to include the generic relation from the model that I'm trying to query. I try to use prefetch_related with related_query_name but seems it doesn't work. and I got an error. Here is my scenario code: class Some1_Model(models.Model): ... fields ... def __str__(self): return f'({self.field}) {self.field}' class Meta: db_table = 'tbl_name' class Some2_Model(models.Model): ... fields ... def __str__(self): return f'({self.field}) {self.field}' class Meta: db_table = 'tbl_name' class ContentTypeModel(models.Model): content_type = models.ForeignKey(ContentType, blank = True, null = True, on_delete = models.CASCADE) object_id = models.PositiveIntegerField(blank = True, null = True) content_object = GenericForeignKey('content_type', 'object_id') ... customize_fields ... def __str__(self): return self.field class Meta: db_table = 'tbl_name' What I'm trying to try: # Where I should put the generic relation model here? Model.objects.prefetch_related('other1_fk').prefetch_related('other2_fk').filter(pk = self.kwargs[self.pk_url_kwarg]) -
I am trying to play my vimeo videos in my website only, for that i restricted the video to domain-level privacy but still its showing Error
I have a django websites where i want to embed my own vimeo videos and i want the video to play in my website only. For that i restricted the video to domain-level privacy. But still its showing error - Because of its privacy settings, this video cannot be played here.(in my website). Please help me to play the video. <iframe class="embed-responsive-item" src="{{ video_link }}" allowfullscreen></iframe> In this way i am embedding video. Even when i am doing curl request by passing the referral(my website domain), its return 200