Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
nvim coc-pyright can't get django 'objects'
I don't know why my coc-pyright cannot access member 'objects' in django. The code works just fine, but autosuggestion box doesn't work because pyright can't read 'objects'. It only suggests that are used in the same working file. Pyright reportGeneralTypeIssues Cannot access member "objects" Member "objects" is unknown [init.vim] coc plug install]2 I've downloaded COC through vim-plug [init.vim] coc plug config coc-settings.json I just copy paste these lines from somewhere.. I think I am doing something wrong with my coc-settings.json file, but don't know how to set it right. my coc-pyright version not found coc-pyright version I checked through CocList extensions I am using: Apple M1 BigSur NVIM (0.5.0) COC Django (3.2.5) Using miniforge python is located in /opt/homebrew/caskroom/miniforge/base/bin/python3 it seems my homebrew manages every files that were downloaded through 'brew install' directories are in '/opt/homebrew/Cellar' not in 'usr/local/Cellar' -
Migrate command in django giving error when deployed to heroku
So i was trying to deploy a django app to heroku which works fine locally. Though the deployment process completes successfully but the migrate command gives an error. django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node ('auth', '0013_alter_user_email') Here is my migration file; import accounts.models from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion from django.contrib.postgres.operations import CreateExtension class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('auth', '0013_alter_user_email'), ] operations = [...] -
python django django.db.utils.OperationalError: table pybo_question has no column named content error?
I was studying django with my book but I have met a unknow error This is the error django.db.utils.OperationalError: table pybo_question has no column named content I have two tables in my models.py Question and Answer. from django.db import models class Question(models.Model): subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField() After I finished writing q.save() the error came out. In my python interpreter: from pybo.models import Question, Answer q = Question(subject=hi', content='hello.' , create_date=timezone.now()) q.save() -
Query filter isn't returning object
I'm trying to get this audience object, that currently has its date set to 30/07/2021 (tomorrow), using the following querysets: print("qset 1:",Audience.objects.filter(start_date__year=self.year, start_date__month=self.month)) print("qset 2:",Audience.objects.filter(start_date__year=self.year, start_date__month=self.month, lawyer=lawyer)) But it returns nothing. So I decided to try and check manually with those... aud=Audience.objects.get(id=3) print("lawyer:",lawyer,"date",self.month,self.year,aud.start_date.month,aud.start_date.year) if aud.start_date.month == self.month: print("month") if aud.start_date.year == self.year: print("year") ... and got the return I was expecting on the console lawyer: marcosv1 date 7 2021 7 2021 month year qset 1: <QuerySet []> qset 2: <QuerySet []> qset 3: <QuerySet []> Can anyone identify the issue on this? I've spent several hours, with nothing coming to mind. -
Django pass checkbox state to view.py when clicked
Hello I'm trying to pass a change in a checkbox when this box is clicked. I'm trying to accomplish this by using Ajax, but for some reason I'm unable to accomplish this. When the checkbox is clicked I'm able to see that it's clicked in my logs. HTML/JAVASCRIPT/AJAX: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-sm-10"> {{ map|safe }} </div> <div class="col-sm-2"> <form method="POST" id="form_legend"> <h3><span style="color: #e8c4b4;">Places</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="check_legend" name="cities"> <label class="form-check-label" for="check_legend">Cities</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="check_legend" name="poi"> <label class="form-check-label" for="check_legend">Points of Interest</label> </div> </form> </div> </div> <script type="text/javascript"> $("input[type=checkbox]").on("change",function(){ var names = []; $('input[type=checkbox]:checked').each(function () { names.push($(this).val()); }); $.ajax({ url: '/api/post_form/', type: "POST", dataType: "json", data: {names: names}, cache: false }).done(function(data) { if (data.result === true){ alert(data.message); } }); }); </script> url.py: path('api/post_form/', post_form_api, name="post_form_api"), Part in view.py that captures the ajax response: @csrf_exempt def post_form_api(request): data = {} if request.method == "POST" and request.POST.get('names', None) is not None: form_field1 = request.POST.get('names') # save the form data and indicate success data['result'] = True data['message'] = "Form saved successfully" if request.is_ajax(): return JsonResponse(data) else: return HttpResponseBadRequest() Another part in view.py where I try to read and print the checkbox states: def test_view(request): if request.method …