Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels in django admin
I would like to implement websocket chats inside of Django admin page. I have not found any information, if it is possible to do so? I need some ideas to start from, maybe there are some tutorials on the topic? Or may it be completely impossible to do? -
Google recaptcha no data on admin panel
I have problem with google recaptcha, I saw other, older, similar topics, but they were slightly different, and outdated, so I decided to add new one. I added google recaptcha to my django project (version 2 to one form for now). My adjango app works on localhost (for now), so I generated keys from google, added 127.0.0.1 as domain and used this: https://github.com/praekelt/django-recaptcha steb by step to add recaptcha v2. Everything works (from user's side), I cannot post form if recaptcha is not clicked, I have to choose pictures if I spam too much etc ... Everything looks fine, but on google recaptcha admin side I hace only 3 requests shown, marked as "No CAPTCHa", and information "We detected that your site isn't verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information." above. I'm confused, becouse from one side: I made much more requests, I made dozen-or-so accounts, and around the same number of tests where I clicked recaptcha, but not created account, so there should be much more requests, from the oter side: everything works fine, I can not log in without captcha, I have … -
submit ajax request on get and post in the same view django
i have a view which include GET and POST but before POST method Get occurred , and this is my view def addNewNameInfo(request): qs = NameList.objects.values_list('name',flat=True) add_new_name_info =ListInfoForm() if request.is_ajax(): names = request.GET.get('name') if names: lists = NameList.objects.get(name=names) if request.method == 'POST': add_new_name_info = ListInfoForm(request.POST) if add_new_name_info .is_valid(): obj = add_new_name_info .save(commit=False) obj.admin = request.user obj.name= name_info.name obj.save() messages.success(request,'created') return render(request,'myfolder/my_template.html',{'names':qs,'name_info':name_info,'add_new_name_info':add_new_name_info }) <form method='GET' class="ajax-request" data-url='/my/url/'> <select name="name" class="form-control" id="type"> <option selected="true" disabled="disabled">names</option> {% for value in names %} <option value="{{value}}">{{ value }}</option> {% endfor %} </select> <button type="submit">search</button> </form> <!--then --> <!--return some information about the selected name --> i need ajax request only for the first form <script> $(document).ready(function(){ var $myForm = $('.ajax-request'); $myForm.submit(function(event){ event.preventDefault(); var $formData = $myForm.serialize(); var $thisUrl = $myForm.attr('data-url') || window.location.href; $.ajax({ method:'GET', url:$thisUrl, data:$myForm, success: handleSuccess, error: handleError, }); function handleSuccess(data){ console.log(data); } function handleError(ThrowError){ console.log(ThrowError); } }); }); </script> is there something i've missed or doing something wrong? but it doesnt work and its code are status: 404? i much appreciate your helps -
When does django query the database when acceessing a related model instance through the foreignkey relationship?
This is an example model definition: class Glass(model): type = models.CharField(max_length=255) class Window(model): glass = models.ForeignKey(Glass) class House(model) window = models.ForeignKey(Window) Dotwalking the foreign keys of the mentioned models and getting the related objects. house = House.objects.get(pk=1) window = house.window glass= house.window.glass I understand that to get house a query is run. Then when I get house.window I presume a second query is run to get an instance of the window. And when accessing glass does Django already have the window loaded in the instance of House? Or does it query window again? I can't seem to find the exact answer to this question online or in the Django docs. Answer would be great to further my understanding of Django ORM querying. Cheers! -
Best way to use API versioning with Django on big application (compatible with Swagger)
Past days I'm investigating the use of versioning on my API. To avoid breaking response changes, leading to frontend bugs. Django offers this documentation: https://www.django-rest-framework.org/api-guide/versioning/ However, there is none (or less) information about how to integrate this with Swagger. As Swagger is a popular way to test and use endpoints. I tried a few ways, but none seems very compatible with swagger. (In displaying the urls based on version for example). So, general question, what is the best way to version big Django API's? -
Django Rest Framework List of Strings Serializer
I have two models created in my Django app and am looking for a serialization approach so that the IPs are shown in JSON as a list of strings instead of a list of IPAddress objects. Desired JSON [ { "hostname": "www.example.com", "ip_addresses": [ "1.1.1.1", "2.2.2.2" ] } ] Current JSON [ { "hostname": "www.example.com", "ip_addresses": [ { "id": 1, "ip_address": "1.1.1.1" }, { "id": 2, "ip_address": "2.2.2.2" } ] ] urls.py class HostSerializer(serializers.ModelSerializer): hostname = serializers.CharField(source='name', read_only=True) class Meta: model = Host fields = ['hostname', 'ip_addresses'] depth = 1 models.py class IPAddress(models.Model): ip_address = models.GenericIPAddressField() def __str__(self): return str(self.ip_address) class Host(models.Model): name = models.CharField(max_length=100) ip_addresses = models.ManyToManyField(IPAddress) def __str__(self): return self.name -
Django remove Image from Object at forms.py
Assuming the following save method at Django forms.py: def save(self, commit=True): instance = super(PostForm, self).save(commit=False) if self.cleaned_data.get('remove_cover'): try: os.unlink(instance.postcover.path) except OSError: pass instance.postcover.delete() if commit: instance.save() return instance To me this looks wrong. How to properly deleted a postcover from a Post element if self.cleaned_data.get('remove_cover') is present? -
Django - 'myapp' vs 'myapp.apps.myappConfig' in settings.py Installed Apps
I know this might sound stupid but I was just wondering what's the difference if I just type 'myapp' instead of 'myapp.apps.myappConfig' in my Installed Apps list. Is it something related to models or what? Regards -
How i make Like counter in django
I want to make like counter in my website below my code any one tell me what changes i do for making like counter.any one tellme /..................................................................................................................................................................................................................... My Model where exist like LikeModel:. Models00.py class Like(models.Model): user = models.ManyToManyField(User, related_name="linkingUser") post = models.OneToOneField(Post, on_delete=models.CASCADE) # for liking post @classmethod def like(cls, post, liking_user): obj, create = cls.objects.get_or_create(post = post) obj.user.add(liking_user) # for disliking post @classmethod def dislike(cls, post, disliking_user): obj, create = cls.objects.get_or_create(post = post) obj.user.remove(disliking_user) def __str__(self): return str(self.post) class Post(models.Model): user =models.ForeignKey(User,on_delete=models.CASCADE,related_name='user') image =models.FileField(upload_to='post',blank=True) caption = models.CharField(max_length=200,default="") views = models.IntegerField(default=0) date =models.DateTimeField(auto_now_add=True,blank=True, null=True) liked =models.ManyToManyField(User,default=None,blank=True) def __str__(self): return str(self.user)+' '+ str(self.date.date()) @property def num_likes(self): return self.liked.all().count() views.py def likePost(request): post_id = request.GET.get("likeId", "") post = Post.objects.get(pk=post_id) user = request.user like = Like.objects.filter(post = post, user=user) # like,created=Like.objects.get_or_create(user=user,post_id=post_id) liked = False if like: Like.dislike(post, user) else: liked = True Like.like(post, user) resp = { 'liked':liked } response = json.dumps(resp) return HttpResponse(response, content_type = "application/json") template.html <button class="btn btn-light mr-3 like" id="{{ i.id }}"> {% if i in liked_post and i.liked.all %} <a href="{% url 'user_homeview:like_dislike_post' %}" style="color:red;" id="likebtn{{ i.id }}"> Liked </a> {% else %} <a href="{% url 'user_homeview:like_dislike_post' %}" style="color:red;" id="likebtn{{ i.id }}"> Like </a> {% endif %} … -
Different domain for each language in Django project
I am using Django translation for my project "domain_name".eu, but recently we bought one more domain "domain_name".dk. And now I want defaulting to Danish on the .dk domain, and defaulting to English on the .eu! I have site framework enabled for the .eu domain SITE_ID = 1, but i don't want to create separate settings.py and different urls.py for the new .dk domain! I saw that I can use middleware to activate proper language depending on domain, but i want and language switcher, which will redirect to the current url, but with domain depending on language! The question is can I just add another Site object directly from Admin and use one settings file for these two domains? -
Javascript adding a class to the odd indexes from a django iteration
First and foremost the code that I have: BTW >>> concursuri is a query list with an x number of elements, doesn't really matter now what elements are in there I want to know how to align the div like in the photo down bellow with JS {% for concurs in concursuri %} {% if concurs.done %} <div class="row featurette"> <div class="col-md-7" id="div-selector"> <h2 class="featurette-heading">First featurette heading. <span class="text-muted">It'll blow your mind.</span></h2> <p class="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div class="col-md-5" id="photo-selector"> <img class="featurette-image img-fluid mx-auto" data-src="holder.js/500x500/auto" alt="Generic placeholder image"> </div> </div> <hr class="featurette-divider"> {% endif %} {% endfor %} <script> var element_text = document.getElementById("div-selector"); var element_photo = document.getElementById("photo-slector"); element_text.classList.add("order-md-2"); element_photo.classList.add("order-md-1"); </script> This is what I exactly want to achieve, have a post first be on the right than on the left, for now, I have created the model and I am iterating through it using the Django syntax for HTML, the {% %} one, the problem comes when I want to write a JS function to add a class that moves the item to the right … -
Autocomplete working but not displaying the values and not able to select the value
Let us consider some items list and when auto complete the item name the items name or items list are not displayed.And also not able to choose the items from the list. $('#item_id').autocomplete({ source: function(request, response) { $.ajax({ url: "/scam/get_items/", data: { query: request.term, unique: true }, dataType: 'json', success: function(json_data) { var chain_names = []; for(i=0; i<json_data.length; i++) { chain = json_data[i]; chain.value = json_data[i].item_name; chain.label = json_data[i].item_name; chain_names.push(chain); } response(chain_names); console.log("autocomplete") } }) }, minLength: 1, select: function(event, ui) { var item = ui.item id= item['pk'] console.log("id",id) $('#item_id').val(item['pk']); } }); -
Image/block of content breaking at page end with kendos exportpdf
I'm using kendos exportpdf function to convert html template into pdf file in django framework.pdf file comes/looks good. when we use only text within template. When I have added block of content using css(bootstrap cards) the text along with block is breaking(as per below screenshot) when it comes to end of the page. Can anyone help me to resolve this issue and please let me know if any additional information to be added for clear understanding. enter image description here -
Out of range float values are not JSON compliant with django render
I'm working with django-restframework and I'm using JSONRenderer to render my return response. But I always got error like: response = response.render() File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\renderers.py", line 104, in render allow_nan=not self.strict, separators=separators File "C:\Users\Domob\Desktop\dev\venv_bv_crm\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "D:\python3\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "D:\python3\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "D:\python3\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) ValueError: Out of range float values are not JSON compliant My main logic codes are like below, there're some nan values in my data dict: class BasicView(viewsets.ModelViewSet): queryset = ... serializer_class = ... filter_backends = ... renderer_classes = [JSONRenderer, BrowsableAPIRenderer] @action(methods=['get'], url_path='dash', detail=False) def dashboard(self, request): try: data = a = [{"k": 1, "v": float('nan')}, {"k": 2, "v": float('inf')}] return Response({"data":data}) except json.decoder.JSONDecodeError: print(f"empty result with {request.user.id}") return Response(status=status.HTTP_404_NOT_FOUND) except: import traceback as tb print(tb.format_exc()) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) How can I get right response? -
Django View without a rendered Response
I want to use a Button to pass an Integer through the URL to my views.py. I want this function in the views.py not to load any new templates or show HttpResponses. Is there a way to call this function by the push of a button, but not reload a new page? Here is the Button in the HTML Template: <a button type="button" class="btn btn-secondary" href="../../frage1f1/1/">1</a> Here is the urls.py Part: path('frage1f1/<int:f1>/', views.frage1f1), Here is the Python Method in the views.py: def frage1f1(request, f1): collection = database["Survey_1"] collection.update_one({"_id": ObjectId(document_id)}, {"$set":{Frage1: f1}}, upsert= True) return HttpResponse("Frage 1 beantwortet") I just want to pass the integer to the fuction and not reload a new page. Is this possible? I am very new to this and would be very thankful for any advice. Thanks in advance. Greetings -
How to make the Right Queryset - django queryset
hello hope you are doing well ! I don't know how to do the right queryset here, to get total mail have status='affecté' in the same date I used a queryset like this : Evenement.objects.annotate(Day=TruncDay('date_Evt')).values('Day')\ .annotate(affecte=Count('mail_item_fid',filter=Q(status='affecté')))\ .all().order_by('Day') but I want to get something like : Total mail have status 'affecté' : (for example 100) date when the mail have status 'affecté': (for example 09/07/2020) Day+0 : (here total mail have status 'livré' in day difference = 0) Day + 1: (here total mail have status 'livré' in day difference = 1) and so on [ I mean by day difference is the day difference between (day when mail have status 'livré' ) and (day when mail have status'affecté ' ) ] the objectif here is to see whether th mail_item is delivered in Day 1 or Day 2 etc ... I would like to have them by Office to see the activity of every office-see my class below here is my class : class Evenement(models.Model): EVENEMENT_CHOICES = ( ("déposé","déposé"), ("reçu","reçu"), ("expédié","expédié"), ("affecté","affecté"), ("livré","livré"), ("echec de livraison","echec de livraison"), ) mail_item_fid = models.ForeignKey(mail_item,on_delete=models.CASCADE, related_name='mail_item_fid_evenement') from_office = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Evt_evenement') date_Evt = models.DateTimeField() status = models.CharField(max_length=50,choices=EVENEMENT_CHOICES) agent_delivery_cd = models.ForeignKey(Delivery_Agent,on_delete=models.CASCADE,blank=True, null=True ,related_name='agent_evenement') def __str__(self): … -
Upgrading python from 2.7.15 to 2.7.18 breaks Django app with SyntaxError (noqa)
I'm in the process of migrating an old python 2.7.15 app towards 2.7.18. I created a new virtualenv and installed the same requirements.txt (there was no difference in dependencies), but the server fails to start with the following error: invalid syntax (base.py, line 107) My main issue is that I can't locate the origin of the problem. From the Stacktrace, it seems its an exception thrown from Django's internals, but I'm not sure. Also, I don't explain why it'd break considering the dependencies are the same as before. Would you have any idea of what's causing this error? -
Comparison Between Variable And Loop Iterator In Template Always Failing
I am trying to print something whenever an int variable from one of my models == my iteration of the loop. My iteration counter increments correctly, and the test passes if I change it to if data.number == '1'. I've read a lot of posts about this and I'm sure this should work, but it doesn't. {% for iteration in range %} {% for data in lesson_data.all %} # this never passes {% if data.number == iteration|add:"1" %} Thank you. -
why SASS and SCSS are not working in django?
I integrated some SCSS and SASS codes in the static folder inside my django project but they are not working although i already used {% load static %} is there any specifi process or guide I should follow ? -
How to not stop the music while I surf to different pages in my website?
I am making a music player app using django. So how can I implement it...Like if I play a song and surf through the website, the sound should not stop...Any Idea how to implement it?? -
JWT user authentication method for django APIs
I have a django project where I am using GraphQL for GET requests and for POST,PUT and DELETE Im using REST APIs. For authentication, Im using rest_framework_simplejwt for REST APIs and graphql_jwt for GraphQL APIs. Its difficult to maintain 2 authentication methods in the frontend. Im just wondering is it possible ti use just the rest_framework_simplejwt authentication for GraphQL. -
django-filter showing model objects when querying foreign key items
I have created a filter using django-filter that is supposed to query the YearLevel field and display row/s that matches the selected checkbox/es (Year 8, Year 9, Year ...). Although, the filter slightly works, as it displays a functioning CharFilter/Field, which I can manually type in a year level and it returns the corresponding row/s; below it contains a bunch of checkboxes with primary keys as labels and returns nothing when selected. My models: class StudentProfile(models.Model): RelatedPersonName = models.CharField(max_length=10) RelatedPersonFirstName = models.CharField(max_length=30) RelatedPersonFamName = models.CharField(max_length=30) StudentLegalName = models.CharField(max_length=30) StudentFamName = models.CharField(max_length=30) Email = models.CharField(max_length=130) Street1 = models.TextField(max_length=30) Suburb = models.CharField(max_length=30) State = models.CharField(max_length=5) PostCode = models.CharField(max_length=6) StudentLegalName = models.CharField(max_length=30) StudentFamName = models.CharField(max_length=30) StudentNo = models.CharField(primary_key=True,max_length=10) Class = models.CharField(max_length=6) YearLevel = models.CharField(max_length=10) objects = StudentProfileManager() class AttendanceQuerySet(models.QuerySet): def get_yearlevel(self, yearlevel): return self.select_related('BCEID').filter(BCEID_id__YearLevel = yearlevel) def get_all_studentprofile(self): return self.select_related('BCEID') class AttendanceManager(models.Manager): def get_queryset(self): return AttendanceQuerySet(self.model, using=self._db) def get_yearlevel(self, yearlevel): return self.get_queryset().get_yearlevel(yearlevel) def get_all_studentprofile(self): return self.get_queryset().get_all_studentprofile() class Attendance(models.Model): BCEID = models.OneToOneField(StudentProfile,primary_key=True,on_delete=models.CASCADE) AttendanceRate = models.CharField(max_length=10) objects = AttendanceManager() Filters.py class YearLevelFilter(django_filters.FilterSet): yearlevel = django_filters.ModelMultipleChoiceFilter( queryset=Attendance.objects.all().distinct(), field_name="StudentNo", to_field_name="BCEID", widget=forms.CheckboxSelectMultiple(), label="Year Level", label_suffix="", ) class Meta: model = Attendance fields = ['BCEID__YearLevel'] Please help. NB. Please ignore the camelcased vars. -
Render Emoji HTML Entity stored in database in Django?
I've stored the following HTML Entity (&#x1f336;🌶) in varchar and is calling it from the database. And then using a for block in the HTML. However, when the page is rendered, it is displayed as &amp;#x1f336; instead of the red pepper, I was hoping for. Am wondering how the amp; got inserted. Want &#x1f336; but got &amp;#x1f336; -
object has no attribute in Django Rest Framework
I develop a mobile application with Django Rest Framework at behind, and React Native at front side. I have to models and nested serializers. I need to insert record at same time to them. But I have 'Entity' object has no attribute 'automobile' error. When I check similar examples, I do not understand where I am wrong. There will be an entity inserted first, and after that an automobile will inserted with the connection of this entitiy. Could you please help me? class Entity(models.Model): customer = models.CharField(max_length=100, null=True, blank=True) seller = models.CharField(max_length=100, null=True, blank=True) entity_name = models.CharField(max_length=50, blank=True, default='') class Meta: verbose_name_plural = u"Entities" verbose_name = u"Entity" def __str__(self): return "%s %s" % (self.id, self.entity_name) class Automobile(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=True) entity_address = models.CharField(max_length = 250, blank = True, default = '') used_km = models.IntegerField(default = 0) manufactured_year = models.IntegerField(validators=[MinValueValidator(1900), MaxValueValidator(timezone.now().year)], blank = True, null = True) def __str__(self): return "%s" % (self.entity_id) class Meta: verbose_name_plural = u"OptionedAutomobiles" verbose_name = u"OptionedAutomobile" class AutomobileSerializer(serializers.ModelSerializer): class Meta: model = Automobile fields = [ 'entity_address', 'used_km', 'manufactured_year'] class EntitySerializer(serializers.ModelSerializer): automobile = AutomobileSerializer(many=False) class Meta: model = Entity fields = ['id', 'customer', 'seller', 'entity_name', 'automobile'] def create(self, validated_data): automobile_data = validated_data.pop('automobile') entity = … -
user interaction with django
I'm working on a question and answer system with django. my problem : I want the app to get a question from an ontology and according the user's answer get the next question. how can I have all the questions and user's answers displayed. i'm new to django, I don't know if I can use session with unauthenticated user and if I need to use websocket with the django channels library.