Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load value apexchart with template tag filter applied in Django
I want to graph the value output in html using apexchart.js. Here, the value is not just loaded from the DB, but defined in models.py as shown below. It loads the value and outputs the value by applying the filter defined in the template tag. <chart.html> {% for student in student %} <td>{{ student.register_status|enroll_filter }}</td> {% endfor %} <script> series: [{ name: 'Chat', data: {{ date_count | safe }} }], </script> -
How to synchronise on-page requests with testing framework in django & selenium
My code has a functionality that automatically renders initial data and then loads further data immediately on page load. So I created a test that first verifies that initial data had been loaded as well as loading more data, like so: class PageLoadFormTest(WaitingStaticLiveServerTestCase): @parameterized.expand(['html', 'component']) def test_validated_list(self, renderer): self.browser.get(self.live_server_url + reverse('page-load-list', args=[renderer])) tbody = self.browser.find_element_by_tag_name('tbody') rows = tbody.find_elements_by_tag_name('tr') new_num_elements = num_elements = len(rows) # !!!!! the folowing line is the one with the problem !!!!! self.assertEqual(num_elements, 30, 'Initial page load should contain 30 data rows') def load_next(): nonlocal new_num_elements, num_elements num_elements = new_num_elements tim = time.time() while time.time() < tim + 2 and new_num_elements == num_elements: # we wait for 5 seconds for number of elements to update on page time.sleep(.1) new_num_elements = len(tbody.find_elements_by_tag_name('tr')) load_next() self.assertGreater(new_num_elements, num_elements, 'The page was supposed to load next page of elements in a second after initial load') load_next() self.assertEqual(new_num_elements, num_elements, 'The page was supposed to stop loading following pages of elements after the initial addendum') self.browser.execute_script('window.scrollBy(0, 50000);') load_next() self.assertGreater(new_num_elements, num_elements, 'The page was supposed to load next page of elements in a second after scrolling to bottom') However, I have now run into an issue where the events for loading more rows execute faster … -
Image not showing from Django rest api in Reactjs
data i've got from server: [ { "id": 29, "name": "atlas", "image": "/media/images/images-4.jpeg", "price": 67473, }, ] in React: //...code console.log(this.props.img); //>>> /media/images/images-4.jpeg //...code <img src={this.props.img} alt='image' width='100%'/> //... in Django: I think there is no problem in django. I made a template and tried to show image, and it worked. So, how do I show image in React ? -
i want to convert absolute uri to short url & able to display it in a template ,so that for individual product page , there is a short url for those
this is how i am trying to generate link #generating short link def create_short_url(self, request): full_url = request.build_absolute_uri temp_url = md5(full_url.encode()).hexdigest()[:6] try: obj = self.objects.create(full_url=full_url, short_url=temp_url) except: obj = self.objects.create(full_url=full_url) return render(request, 'link.html', {"obj": obj}) i want to render the short url to the template. below is where i want to display <!-- Copy to Clipboard --> <label for="text_copy" class="text-primary"> Short Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy1" value="{{ request.build_absolute_uri }}"/> <div class="container"> <button onclick="copyToClipboard('#text_copy1')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </div> -
Chrome hitting my Django backend but I only made an iOS app
So I have a Django backend deployed on Google App Engine. This backend supports an iOS app. In my server logs I can see all the requests coming in and where they were made. It used to be that I would only get requests from Joon/7.** (which is the iOS app name + version). However, recently I've been getting requests from Chrome 72 which doesn't make sense cause the app shouldn't be able to be used on Chrome. Furthermore these requests are creating a lot of errors in my backend because it is not sending an authentication token. Does anyone know what is going on here? Are my servers being hacked? -
Queryset object has no attribute _default_manager
This is my models.py class PdfParsed(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) pdf_id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, blank=True, null=True) status = models.IntegerField(blank=True, null=True) this is my views.py class pdfListView(LoginRequiredMixin,ListView): model = PdfParsed.objects.filter(user_id=6) login_url = '/login/' context_object_name = 'pdfparsed_list' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) aa=os.listdir('media/pdfs') data['pdf_parsed'] = sum('.pdf' in s for s in aa) return data what i wanted to achieve from above code is to print pdfs that are uploaded with respect to user here for testing purpose i used number 6 but its not working it is showing this error: File "/home/ideas/anaconda3/lib/python3.8/site-packages/django/views/generic/list.py", line 33, in get_queryset queryset = self.model._default_manager.all() AttributeError: 'QuerySet' object has no attribute '_default_manager' -
How to filter a template table on field from a many to many related model in Django using django-filters?
I am trying to create a filter using a reverse many-to-many relationship using django-tables2 and django-filters. I can get a filter for the many-to-many object, but I want to be filter on one of the fields in the related table. How is it that I can do this? example models: class Author(models.Model): articles = models.ManyToManyField(Article,blank=True) age = models.IntegerField() hometown = models.ForeignKey(Town,on_delete=models.CASCADE,null=True,blank=True) @property def articles(self): return ', '.join(art.title for art in self.articles.all()) class Article(models.Model): title = models.CharField(max_length=255, blank=True) publication_date = models.DateField() published = models.BooleanField(default=False) class AuthorTable(tables.Table): articles = tables.columns.Column(accessor='articles') class Meta: model = Author attrs = { 'class': 'table table-responsive table-striped', 'thead' : { 'class': 'thead-dark' } } class AuthorFilter(django_filters.FilterSet): class Meta: model = Author fields = ["articles", "age", "hometown"] This gives me a filter that looks like: Articles: ( Object 1 ) ( Object 2 ) ( Object 3 ) How to I get it to filter on articles which have been published or articles which have a certain publication date? I also do not seem to be able to do the reverse table/filter. If I make an Article table and an Article filter, i cannot seem to fetch or filter the author objects. I have read through both documentations … -
The minimal list of Django study projects after those I can start working in freelance
I need a list of study projects. After complete that, I can work freelancer with confidence. I want to take not arduous tasks, only for experience in conversations with customers and programming for somebody. -
Django ManyToManyField restrict user to single field
I am trying to create a model for a comment section with a like and dislike with ManyToManyField corresponding to the specific user using the below code. class Comment(models.Model): """docstring for comment.""" ... likes = models.ManyToManyField("User", related_name = "CommentLikes", blank = True) dislikes = models.ManyToManyField("User", related_name = "CommentDislikes", blank = True) But I need to create some kind of restriction so that the user is not present in both fields before saving the model. Can someone kindly help me with how to implement it? -
Where is the best place to enable CORS from?
I have a Django application that I can enable CORS using CORS_ORIGIN_ALLOW_ALL = True but I can also enable it through the Nginx Configurations. So where is the best location to do this and why? -
How would I dynamically clone a site and apply custom css to it?
So my school has a "portal"; a site with heaps of resources for the students and teachers. Only downside is that it is really, really badly designed and runs on HTML4. I have some decent web design skills and I want to try and improve it. I have asked if I could directly edit it and I was very quickly shut down. So how would I go about cloning the site while applying custom CSS? While doing an iframe seems like a great idea to start with, it is quickly stopped by CORS. You can't apply custom CSS to an iframe with an origin of a different domain. I could just download the site's source code and write custom CSS for that, but that way it won't update when new content is updated. I am happy to play around with django/flask if needed since I have a lot of experience with python and if it works, I can create a downloadable app using react or something. Anyone got any ideas? -
I want to create timetable for employee's working hours in django
I want to create timetable like this : enter image description here I could not find any similar examples or any helpful libs for timetable for working hours written in python/django. I tried fullcalendar.io django integration but it didnt work for me. I tried write code for this myself but something went wrong. My code : class Timetable(models.Model): name = models.CharField(max_length=200, unique=True) class Meta: ordering = ('id',) def __str__(self): return self.name class Schedule(models.Model): WEEK_DAYS = ( ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Sunday', 'Sunday'), ) timetable = models.ForeignKey(Timetable, on_delete=models.PROTECT) is_working_day = models.BooleanField(default=True) day_title = models.CharField(max_length=12, choices=WEEK_DAYS, default=1) starts_at = models.TimeField(null=True, blank=True) finishes_at = models.TimeField(null=True, blank=True) class Meta: ordering = ('id',) def __str__(self): return f"On {self.day_title} work starts at {self.starts_at} and finishes at {self.finishes_at} " -
How Good is Django compared to Single Page web applications like angular?
I wanted to know that is there really a very significant difference between Single Page Web applications like Angular which use APIs and traditional MVC based ones like Django? What would be the best combination for the backend (API) and Frontend to create robust web applications? -
run ajax call to get form submitting data first, then run the following JavaScript
I have build a Django web app. In the frontend, I want to run the ajax call to get the form submitting data first, then run the following JavaScript to process according to the real time data passed from backend. <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> async function myFunction() { Swal.fire({ title: '', text: "Do you want to confirm entries?", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes', cancelButtonText: 'No' }).then((result) => { if (result.value) { $("#myform").submit(); $.ajax({ url: '127.0.0.1:8000/content_checklist_name_url', type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { alert(data); }, failure: function(data) { alert('Got an error dude'); } }); const result = await if (data.includes('saved')) { Swal.fire( '', 'Entries have been saved.', 'success' ) } else { Swal.fire( '', 'Duplicate Entry. This Course Code already exists.', 'error') } } else { window.stop(); } }) } But the error shows: await is only valid in async function. How could I run ajax to get the data(form submitting result) from backend first then run the if condition: if (data.includes('saved'))? So I could do different pop up from the results passed from backend in real time. -
Django Celery Dynamic Schedule
In my app, i have a reminder system and i want to notify the user at their given time. these are models.py file class Reminder(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="reminder" ) name = models.CharField(max_length=255) remind_at = models.DateTimeField(null=True, blank=True) class Notification(models.Model): reminder = models.ForeignKey(Reminder, on_delete=models.CASCADE) message = models.CharField(max_length=255) and this is the views when user create a reminder: def create_reminder(request): if request.method == 'POST': Reminder.objects.create( user=request.user, remind_at=request.POST['remind_at'], name=request.POST['name'] ) return HttpResponse("Created the reminder") Current i am notifying the user like every hour i running a task with celery beat. this is the tasks.py @shared_task(name ="notify_as_reminder") def notify_as_reminder(): reminder = Reminder.objects.filter( remind_at__gte=timezone.now()-timezone.timedelta(hours=1), remind_at__lte=timezone.now() ) for r in reminder: Notification.objects.create( user=r.user, message="Hey ! You have schedule meeting about to start after one hour" ) and this is celery beat app.conf.beat_schedule = { 'notify_as_reminder': { 'task': 'send_notification', 'schedule': crontab(hour='*/1'), }, } I think the celery beat running the method even there is no notification needs to send to the user. I want exactly same time the user set a time to remind them. I mean dynamically. I heard of apply_async and django_celery_beat Can anyone tell me which one is better to solve problem? or there is any other way to do it? Can … -
Django - The empty path didn’t match any of these
This is the error I get when I run this code: python3 manage.py runserver error message my url.py file looks like this: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('home/', TemplateView.as_view(template_name="home.html")), ] In settings.py under the templates option it looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'template'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And my overall directory looks like this: directory I was following this tutorial: https://www.youtube.com/watch?v=IHTP8-KskcQ I got stuck around 7 minutes in, does anyone know the issue? -
how to add links to navigation bar
I'm making a blog web site using django and I add a sticky navigation bar to web site and also it work pretty well but want add links to menu in the navigation bar.I can't do it because there already link in href.I want to keep this link in href because it make navigation bar sticky.I make this sticky navigation bar with help of w3 school website.here is my code <!DOCTYPE html> <html> <head> <title>Dinindu Theekshana</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar { overflow: hidden; background-color: #333; color: #333; z-index: 9999999; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #294bc5; color: white; } .content { padding: 16px; padding-top: 50px; } .sticky { position: fixed; top: … -
Convert objects into queryset
Probably, it is a bad and db expensive idea, but is there a way to convert list of objects back to a queryset? foo_list = [foo1, foo2, foo3, ...] something like: foo_qs = queryset(foo_list) So that i can return paginated queryset?? -
Confused when delivering PrimaryKeyRelatedField to the Client
If you extract the value of the field used as PrimaryKeyRelatedField, you will see the value in the form of Object, not PK. In the case of the official document, I am using it as below, but it is confusing when using it with the client. I don't know if the tracks will contain id or Object just by looking at the field name. class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['tracks'] def create(self, validated_data): tracks = validated_data.pop('tracks') # [Track, Track ...] Is there a better way? -
Django form submit with hundreds of Celery tasks
I have created a system that enables a user to select users and notify them. When they submit their form, the code will execute a celery task to notify each user. I am getting browser timeouts when sending to 100s of users. Here is a simplified version of my code. Note that my code works as intended, it's just slow when # of users gets into the 100s. Happy to add more if it helps with the answer, but I really want to focus on the generalizable crux of the issue. Note that there reasons why I need so many editable inputs that I'd rather not get into. Let just assume that they are a constraint for the purpose of this question. HTML <form action="" method="POST"> {%csrf_token%} <input type="submit" value="Send"> <table> <tr> <th>User</th> <th>Input 1</th> <th>Input 2</th> <th>Input 3</th> <th>Input 4</th> <th>Select</th> </tr> {% for u in users %} <tr> <td>u</td> <td><input type="text" name="input-1-{{u}}" value=""></td> <td><input type="text" name="input-2-{{u}}" value=""></td> <td><input type="text" name="input-3-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="text" name="input-4-{{u}}" value=""></td> <td><input type="checkbox" name="select-{{u}}" value="True"></td> </tr> {% endif %} </table> </form> Views if request.method == 'POST': # users is a queryset for u in users: # input-#- is a form … -
Custom authorization in Django Rest
I am just a newbie with Django, python. I try to build 1 simple API Collection include CRUD basic, and authentication, authorization. I have 1 simple Views like: @api_view(['GET']) @permission_classes([IsUser]) def get_test(request : Request): return JsonResponse({"message": "success"}, status = status.HTTP_200_OK) and IsUser is: class IsUser(IsAuthenticated): def has_permission(self, request : Request, view): token = request.query_params.get('token') if token: role = jwt.decode(token.split(" ").__getitem__(1), key="secret_key",algorithms="HS256").get('role') if role == 'User': return True else: return False return False My purpose wants to parse the JWT token and authorization based on that. I wonder don't know if my way is really correct? Can anyone give me some comments as well as documentation to better understand this issue? I don't use any other lib because I want to code by myself at first to understand the flow. Thanks for helping me. -
transferring data between JavaScript frontend and Django backend - noob asks
I am exploring web dev very in-depth for the first time and I'm trying to make a chrome extension that sends, let's say, a string to a Django back end, the Django back end processes said string and returns a result back to the chrome extension. I'm doing this because from what I can tell, I can't make a pure Django chrome extension and I am already familiar with Django (although of this I am unsure). Can anyone point me towards some tools I should research to accomplish this? I keep seeing terms like POST, GET, AJAX but have no idea where to begin. Thanks! -
Gunicorn tmp folder fetch my files which got empty
When i was working on server my changed file got deleted but i didn't have restarted gunicorn yet so my system is working properly but i want to get the code of that file. I have tried to look into many directories but didnt found the file Can anyone guide to know where the file will be because i think it might be saved in a temporary directory -
django How to review blog comment before publish?
I am new in django. I want to review my blog comment before it publish or show in my html template. I am using MPTTModel in my model for child parent relationship in my comment section. I used BooleanField in my models but it's not working. Right now my html template showing all blog comment when any user submitting comment. here is my code: #models.py class BlogComment(MPTTModel): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') name = models.CharField(max_length=250) email = models.EmailField(max_length=2000) comment = models.TextField(max_length=50000) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) is_approve = models.BooleanField(default=False) #forms.py class CommentFrom(forms.ModelForm): class Meta: model = BlogComment fields = ['name','email','comment'] views.py class BlogDetail(DetailView): model = Blog template_name = 'blog_details.html' def get(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) def post(self,request,slug): blog = Blog.objects.get(slug=slug) form = CommentFrom(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.blog = blog comment.save() messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return redirect(reverse('blog-detail', kwargs={'slug':slug})) else: form() context = {'form':form, 'blog':blog, } return render(request,'blog_details.html',context) #html {% load mptt_tags %} {% recursetree blog.blogcomment_set.all %} <p>comment: {{node.comment}}</p> {% if not node.is_leaf_node %} <div class="children pl-2 pl-md-5"> {{ children }} </div> {% endif %} {% endrecursetree %} -
Store data of React in Django Database without using Models
I am trying to build a simple project in React and Django. I am a beginner. I am trying to build a punch in machine. I am working on a feature where the user when clicks the image then it displays the time and date she clicked the image. I want to store that time and date in database.But I do not know how to? Do I need to create Model or can be done without the model. My code so far Index.js function CDate(){ const dt = null; const [cdate,setDate] = useState(dt); const handelDate = () =>{ let dt = new Date().toLocaleString(); setDate(dt); } return( <> <h3>{cdate}</h3> <img src={punchin} alt="PunchinMachine" onClick={handelDate} /> </> ) } ReactDOM.render(<CDate />,document.getElementById("root")); Could you please me store the time she clicked in the db so that I can keep track of time.