Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I delete specific row instead of always the first row (Modal in Django)
I'm building a CRM app and try to delete a specific client when the confirmation button is clicked in the pop-up modal, but it always deletes the first client. I know that it happened due to the ambiguous class name, and the problem may be solved by adding a unique id for each client? I have been searching around for this type of problem but still not sure how to solve it. Since I generated every client by a for loop and I might need to dynamically create a unique id for each client and call the specific id in javascript and modify the corresponding CSS? I feel that this way might be over-complicated. Are there any other methods to achieve my goal? Thanks. My code is following: Templates <!-- client table --> {% for user in clients %} <tr class="mt-3"> <td class="pt-3">{{ user.level }}</td> <td class="pt-3"><a href="{% url 'clients' user.id %}">{{ user.first_name }}</a></td> <td class="pt-3">{{ user.last_name }}</td> <td class="pt-3">{{ user.country }}</td> <td class="pt-3">{{ user.contact }}</td> <td class="pt-3">{{ user.contact_number }}</td> <!-- <td><a href="#" class="btn btn-outline-primary btn-sm">Client Info</a> --> <td><a href="{% url 'update' user.id %}" class="btn btn-outline-warning">Update</a> <a class="btn btn-outline-danger" onclick="clientmodal()" >Delete</a></td> </tr> <!-- client modals --> <div class="modal-bg"> <div class="delete-modal"> … -
Append server name in a API response -- Django rest framework
I have been trying to create a API with Django restframework. There is a Image field in the API which is giving a relative path. I would like to have absolute path or name of the server to append before the Image field. But its throwing an error TypeError: string indices must be integers I believe the json that I created from the ordered dict is a string and is not giving expected output. Problem: I need to access the json keys and append server name in it. I tried the following for it. views.py def get_individualmember_details(request): if request.method == 'GET': serializer = MasterIndividualMembersSerializer(MasterIndividualMembers.objects.all(), many=True) result = json.dumps(serializer.data) print(result) for row in result: if row["member_photos"]["image"]: row["member_photos"]["image"] = request.META['HTTP_HOST'] + "/" + row["member_photos"]["image"] result = json.dumps(result) return JsonResponse(json.loads(result), safe=False) expected output: [ { "model": "userdata.masterexecutivemember", "pk": 1, "fields": { "firstname": "John", "lastname": "Doe", "profile_image": "http://127.0.0.1:8000/user/1.jpeg", //Needs to append servername here "description1": "Test abc", } }, ... ... ] Please suggest how to append the server name or a string before any json key. Thanks in advance! -
Why response is always {"detail":"Unsupported media type \"text/plain\" in request."} in swift?
I have created a sample app in Django which deletes a question from App. And provides a correct output when consumed using POSTMAN. class Questions(APIView): def delete(self,request): received_id = request.POST["id"] print(received_id) place = Question.objects.get(pk=received_id) place.delete() questions = Question.objects.all() seriliazer = QuestionSerializer(questions,many = True) return Response({'Orgs': seriliazer.data}) However, when I am trying to achieve it from iOS app, it's returning {"detail":"Unsupported media type "text/plain" in request."} func deleteQuestion( id: Int){ guard let url = URL(string: "http://127.0.0.1:8000/V1/API/questions/") else { return } var request = URLRequest(url: url) let postString = "id=15" request.httpBody = postString.data(using: String.Encoding.utf8); request.httpMethod = "DELETE" URLSession.shared.dataTask(with: request) { data, response, error in let str = String(decoding: data!, as: UTF8.self) print(str) if error == nil { self.fetcOrganizatinData() } }.resume() } Could not really understand where exactly the problem is ? -
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?