Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating PDF based on user selected classes on webpage
I am trying to create a PDF based on information selected by a websites user. The way we currently handle the displayed information does not involve a PDF so we just created a JSON and then used Javascript to tear apart the data and display it. I have read and seen first hand that you cannot use javascript with the xhtml2pdf library. Therefor I was wondering if there is a way to pass multiple Model Objects so that I can access them in the HTML. Without knowing the total amount until the user selects them. I have tried passing multiple objects to the PDF but when I print the data it just displays list that I am seemingly not able to access. By using {{data.}} course_code is the list of objects: this is located in view.py data = CourseLookup().get_equivalent_courses(course_code) return Render.render('pdf_form.html', {'data': data,'response':'', 'request':request}) Located in pdf_form.html. {{data}}# I have tried data.QuerySet and data.Course and it displayed nothing. Displayed on the webpage. []>, ]>] I am trying to access an undetermined amount of class data and display their names in a HTML table that is made into a PDF Document with xhtml2pdf. The amount is determined after the user selects … -
Replace function of pandas does not seem to work
I looked around but I couldn't find something that could help me. I have a dataset which is composed like this: rsid name countexperiments 7 18 1 8 448 1 this dataset is later converted in a dataframe and then I call the replace function import pandas as pd filename = 'a.csv' df = pd.read_csv(filename) df.replace(7, 5, inplace=True) but after that the output is still rsid name countexperiments 7 18 1 8 448 1 -
Django: URLs in django and adding it into templates
How to write URL in the template to take the request to this kind of URL - path('category/<str:cat>/', CategoryView.as_view(), name='category') I am working on Django 2.1 and my urls.py contains multiple str path resolver. To differentiate them I want to write urls by adding some string but I can't find any way to add these urls into my template so that request can be made through templates. path('category/<str:cat>/', SomeView1.as_view(), name='view1'), path('tag/<str:tags>/', SomeView2.as_view(), name='view2'), Please suggest how to add these links to my template or is there any alternate way to solve this issue. -
Django Rest Framework quickstart Page not found 404
I'm trying to do a quickstart tutorial from https://django-rest-framework.org. And this is my urls.py from django.urls import path, include from rest_framework import routers from main.views import MovieViewSet, CommentViewSet router = routers.DefaultRouter() router.register(r'movies', MovieViewSet) router.register(r'comments', CommentViewSet) urlpatterns = [ path('', include(router.urls)), ] and when I go to http://127.0.0.1:8000/movies/ I get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/movies/ Using the URLconf defined in movie_api.urls, Django tried these URL patterns, in this order: ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] The current path, movies/, didn't match any of these. The viewsets and serializers are implemented as in tutorial. Am I tired and not seeing something? -
How to fix this error - 'validationError' object has no attribute get
I have custom login form . When I try to login with username/email that is in database and wrong password. It works fine - it says wrong credentials. But when I try to login with username/email that doesn't exist in database. ValidationError occur. -
Access Django Model Field from Javascript
I'm having some problems with a midi player. I want to reproduce automatically the midi file that is saved in my Django model Field, concretely mi field midi, which saves a real midi file. This is the HTML template that I'm using <body style="margin-top: 250px;"> <h2 style="margin: 115px auto 4px auto; font-size: 20px;">BareBones MIDI</h2> <button id="load">Choose Tune</button> <input id="filein" type="file" accept=".mid, .midi" style="display: none;"> <div id="title" style="margin: 3px; font-size: 10px; font-style: italic; white-space: nowrap;"></div> <div style="margin-left: 845px"> <button id="control">&#9654;</button> <progress style="width:800px; height: 30px"></progress> </div> </body> At the moment, It uses an input tu upload the file, but I want to modify this and change the code so the midi file of my django model field is reproduced automatically, without the input. In my JS code, I've tried to access the field the following way: let cancion_midi = {{cancion.midi}}; But it throws me the following error ReferenceError: tiger_qNDnPUI is not defined I'm losing my head and I don't find any solution. I'd be grateful if somebody could help me. If you have any questions, ask me anything. -
Django Rest Framework, POST request to url/group1/messages
I want to add a message inside a chat room I have made in django rest framework. My problem is that there is no page called: group1/messages. But if I go into url/group I can see all the messages on a different level. And if I go into url/messages, the messages of all the groups appear! How do I set this up so that I can make a post request to url/group1/messages? Django Models: class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) class Room(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(UserProfile, blank=True) messages = models.ManyToManyField(Message, blank=True) class Meta: verbose_name_plural = 'Rooms' def __str__(self): return "{name}".format(name=self.name)enter code here Django Serializers: class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = UserProfile fields = ('id', 'username') class MessageSerializer(serializers.ModelSerializer): sender = UserProfileSerializer() class Meta: model = Message fields = ('id', 'content', 'date', 'sender') class RoomSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True) members = UserProfileSerializer(many=True) class Meta: model … -
Inverse Django lookup filtering
So I have two models: class Member(models.Model): course_member = models.ForeignKey(CourseMember, on_delete=models.CASCADE class CourseMember(models.Model): name = models.CharField(max_length=30) How can I get all the CourseMembers that have 2 or more members? And, how do I stop CourseMember from having more than 1 Member. I was thinking about using Aggregate and Group by, but I wasn't sure how to do it. -
In Python, how do you do substitutions when the template file contains a "$"?
I'm using Python 3.7 and Django. I want to get a string from a template in Python and make the apporpriate substitutions like so ... src = Template(filein.read()) # document data relative_path = article.path.replace(settings.REDDIT_URL_PREFIX, "") d = {'relative_path': relative_path, 'comment': comment} # do the substitution result = src.substitute(d) However, there is one problem. My template contains this ["xpath=//a[@onclick='$(this).parent().submit()']", "xpath:attributes"], The dollar sign is usually used for substitution, and so maybe for this reason, my above code is dying with the error ... ValueError: Invalid placeholder in string: line 248, col 31 Does anyone know how I modify the above template line so that the substitution mechanism ignores the dollar sign on that line? -
PostgreSQL empty list VALUES expression
I am trying to take a list of points, and query a geospatial database, to find all matching rows. I have a computed SQL statement that looks like this: cursor = connection.cursor() cursor.execute( ''' SELECT g.ident FROM (VALUES %s) AS v (lon, lat) LEFT JOIN customers g ON (ST_Within(ST_SetSRID(ST_MakePoint(v.lon, v.lat), %s), g.poly_home)); ''', [AsIs(formatted_points), SRID] ) Here is an example of what the formatted_points variable looks like: (-115.062,38.485), (-96.295,43.771) So, when that is inserted into the SQL expression, then VALUES expression reads: (VALUES (-115.062,38.485), (-96.295,43.771)) AS v (lon, lat) So far so good. However, when the list of points is empty, the VALUES expression looks like this: (VALUES ) AS v (lon, lat) .. which causes me to get this error: django.db.utils.ProgrammingError: syntax error at or near ")" In other words, (VALUES ) is not legal SQL. Here's the question: How do I represent an empty list using VALUES? I could special case this, and just return an empty list when this function is passed an empty list, but that doesn't seem very elegant. -
How to render two separate models on same page?
I am making a post-comment web app. On the home page, various posts are displayed along with an "Answer/Comment" button. When clicked on it, I need to show the contents of the post being answered along with the comment form. The posts and comments are separate models. So far I have scanned the web for methods to display two separate models on same page. But here, I need to render the post content using "GET" and it's pk and a form to submit comment which is a "POST" method. This is my models.py: class Post(models.Model): pid = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home')#, kwargs={'pk':self.pk}) class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) answer = RichTextUploadingField() comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.answer def get_absolute_url(self): return reverse('blog-home') def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) My views.py is something like this: class PostDetailView(DetailView): model = Post class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['answer'] def form_valid(self, form, **kwargs): form.instance.author = self.request.user form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) The two urls- one for post detail view and for comment create view are … -
how to configure angular to work remotely with django APIs?
I am running a web application, front-end with angular and back-end with django. the thing is: These two frameworks are not running on the same server. how can I configure angular to work remotely with APIs? (I have tested the APIs, and they are just fine) -
How to reorder priority data after inserting new data?
Currently building a Help Ticket App with Django Form etc. I am trying to create a 'priority' field for my model whereby the priority number should not repeat itself and if a new priority set has already exist, the other priority should be reordered accordingly. Hence, no priority shall be duplicated I am relatively fresh in Django. I am having trouble to understand how I can modify my models.py so that I can create a method which will execute a certain command to update my other existing 'priority' every time I send a 'post' request after clicking the 'submit' button models.py from django.db.models import F from django.db import models class Request(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True, null=True) priority = models.PositiveIntegerField() # This is what I have tried: def reorder_priority(self): existing_feature = Request.objects.get(priority=self.priority) foo = Request.objects.filter(priority__gte=existing_feature.priority) foo.update(priority=F('priority') + 1) foo.save() def __str__(self): return self.title For example: Title1, Priority = 1 Title2, Priority = 2 Title3, Priority = 3 User adds in a new TitleX, with Priority = 3, Expected output: Title3, Priority = 4 Overall: Title1, Priority = 1 Title2, Priority = 2 TitleX, Priority = 3 Title3, Priority = 4 -
How to serve files to download from HTML using django templating
I'm stuck in my project where i want to serve some files to download on clicking the download button on my webpage. Can anyone kindly direct me how to serve downloadable files on the web pages using template in django. in normal html, we can achieve as <a href="<path_of_file>" download> currently I have beginner level knowledge in django and i want to explore more. Kindly assist me to handle this in django -
How to read spaces and line breaks from a textField django
I have created a textField model that is sended from a .. But my problem is simple... How can i specify a line break in the textField? to avoid that the text will show all fluid without spaces or line breaks. It shows me the text like this: As you can see, without line breaks... Hope you can help me, thank you!. -
set the value of the input field in the action of the form in django
I have created the modelforms with the name field and i want the retrieve the name entered in the input field to be as a url in the django forms.py class githubform(ModelForm): class Meta: model = github fields=['name'] model.py class github(models.Model): name = models.CharField(max_length=200) views.py def github(request): gform = githubform(request.POST or None) if gform.is_valid(): gform.save() return render(request,'formsapp/github.html',{'gform':gform}) github.html <form method="post" action="https://api.github.com/users/{{ gform.data.name }}"> {% csrf_token %} {{ gform.as_p }} <button type="submit">signup</button> </form> <a href="">ccccc</a> now i want the value of the input field entered by the user in place of gform.data.name and i am stuck in getting the value entered by the user into action url. can anyone help me to sort it out -
face problem to install django compressor
I face problem to install django compressor pip install django-compressor==2.2 error: [WinError 3] The system cannot find the path specified: 'C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1\lib' -
django comment and share not showing in template blog post
I am working on blog post and follow django 2 by example book, where i encounter one problem . I create a comment and share section which is not showing in template this is app mysite/blogs/ views.py file def post_share(request, post_id): # Retrieve post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri( post.get_absolute_url()) subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'abc@gmail.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent, 'cd': cd }) def post_detail(request, year, month, day, post): """ """ post = get_object_or_404( Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # list of active comments for this post comments = post.comments.filter(active=True) if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Created Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = … -
Use Q object instead of put a filter after another
I implemented two queries, that I believe they do the same thing. But they don't! My problem is why they don't do the same? def query_5a(n, c): q = Driver.objects.filter( models.Q(car__car_type='A') | models.Q(car__color=c) ).filter( car__ride__gt=n ).distinct() return q def query_5b(n, c): q = Driver.objects.filter( models.Q(car__ride__gt=n) & ( models.Q(car__car_type='A') | models.Q(car__color=c) ) ).distinct() return q I expected that the output of query_5a is equal to query_5b, but it's not. -
Getting "TypeError: argument should be integer or bytes-like object, not 'str'" when searching for string on web page
I'm using Python 3.7 and Django. I want to search for a string in an HTML page. I tried this ... req = urllib2.Request(article.path, headers=settings.HDR) html = urllib2.urlopen(req, timeout=settings.SOCKET_TIMEOUT_IN_SECONDS).read() is_present = html.find(token_str) >= 0 but this is resulting in an error TypeError: argument should be integer or bytes-like object, not 'str' complaining about the last line, where I do the "find." What's the right way to search for a string in HTML? -
Return different templates from views.py based on number of uploaded files by logged in user
Expected Behavior: I have a django app where users upload 'beats' (mp3 files) and I eventually want to have a free tier and a paid tier. The free tier will be limited in the AMOUNT of 'beats' they are able to upload. Say 3 beats max for free users. I am trying to run a query in my views that will send the user to a template page requiring them to become a premium member if they exceed the amount of beats allowed to be uploaded. It should check who the logged in user is, get the count of beats uploaded by that user, and if it is less than allowed show the upload template else show the sign up template. Current Behavior: Using self.request.user is giving my NameError self is not defined. I was able to get the code to work when hard coding the user's ID into the query. Here is my current code. #beatupload/views.py class uploadNew(CreateView): # new model = beat fields = ['title', 'beat'] success_url = reverse_lazy('uploads') #Check number of beats uploaded by user and if exceeds amount require signup #To render sign up template if true and proceed to upload if false def get_queryset(): return … -
Is there a way to password protect the python shell in a Django application?
I want to password protect the shell when running python manage.py shell from inside my Django app for a superuser. After running python manage.py shell I would like to be prompted to enter a superusers username and password. -
i am getting error message running django-admin . i am already installed django
i am a beginner in django . installed Django in pychram but i am not able to make run django-admin startproject . when i run this command i got 'django-admin' is not recognized as an internal or external command, operable program or batch file. python3 -m django --version django-admin.py version ./manage.py --version pip install django Requirement already satisfied: django-admin version 'django-admin' is not recognized as an internal or external command, operable program or batch file. -
Share session variable over different ports in local development
I currently have Django on port 8000 and Angular on port 4200. In production they will be on the same port 80. Due to the ports being different the session cookies are different so the authentication fails. How can I have these two app on different ports share one set of cookies / session? -
How to use ModelMultipleChoiceFilter in django_filters with JSONfield
I'm try filter items use django_filters with JSONfield in my model, but I can't do this. If use CharFields I can get current result, but me need have possibility work on requests. When I use ModelMultipleChoiceFilter I get all variations from filter, but filtering does not happen. Models.py class Product(models.Model): name = models.CharField(max_length=120) properties = JSONField(default=dict, blank=True, null=True, db_index=True) Filters.py from django_filters.rest_framework import FilterSet from django_filters import rest_framework as filters from products.models import Product class ProductFilter(FilterSet): color = filters.ModelMultipleChoiceFilter( queryset=Product.objects.extra( select={'color': "properties->>'color'"}).values_list('properties__color', flat=True).distinct(), field_name='properties', to_field_name='properties', lookup_expr='color__contains', ) class Meta: model = Product fields = { 'color': 'color__contains', } This is Item { "id": 10, "name": "Test_3", "properties": { "color": "Black", "invertor technology": false, "service area, m²": 24 }, }, If I choise in filter color Black. I have error: "Choose the correct option. Black is not among the valid values."