Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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." -
How to add multiple Emails in one field
I'm trying to create a Company class with an email field who can contains One or Multiple email adresses. I know that there's the EmailField type who can take one email as parameters, but in my case I need to extend it to multiple email. class Client(models.Model): company_name = models.CharField(max_length=100, unique=True) project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL) email_list = models.EmailField(max_length=70) How can I achieved the result to extend this email_list field to take in parameters the multiple email I need ? tx ! -
DRF: GET returns TypeError (500) instead of 405
I have a ModelViewSet that uses @list_route to handle POSTs to a given endpoint. urls.py router.register(r'my-view-set', MyViewSet, 'my-view-set') views.py class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer @list_route(methods=['post'], url_path='validate') def validate(self, request): # validate model return Response({'success': 'Validated'}, status.HTTP_200_OK) When this endpoint is accessed using HTTP GET through curl or wget I get a proper 405 status code as expected: curl: {"detail":"Method \"GET\" not allowed."} wget: 2019-07-09 15:06:48 ERROR 405: Method Not Allowed. However, if I use chrome to browse to the endpoint, I get a 500 error: TypeError at /myapp/api/v1/my-view-set/validate/ __init__() missing 1 required positional argument: 'instance' How do I convince django to return a 405 to a browser instead of a 500 when calling this endpoint with GET instead of POST? Django==1.10.5 djangorestframework==3.5.3 -
Getting GitHub details of a particular user by entering the username dynamically
I am trying to get the GitHub details of a particular user by entering the username dynamically using django. But I am not getting the details,when i click the view button in my index.html code, it is returning that "not found". here is my code forms.py class GithubInfo(forms.ModelForm): class Meta(): model = Github fields = ['name'] views.py from django.shortcuts import render from .forms import UserForm,UserProfileInfoForm,GithubInfo from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse def index(request): form = GithubInfo(request.POST) if form.is_valid(): form.save() return render(request,'signupapp/index.html',{'form':form}) index.html <h2>Github repos</h2> <form action="{% url 'signupapp:index' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <a href="https://api.github.com/users/{{form.name}}/"> <input type="button" value="view"/> </a> </form> can anyone help me to achieve this -
Why FieldFile returns different relative and absolute paths for .doc and .docx files?
I want to convert .doc to .docx if a POSTed (in Django admin page) file has .doc extention. When POSTed file has .docx extention nothing wrong happens: Django uploads document.docx into media/documents/document.docx and I can read it. But if a POSTed file has .doc extention I have strange Django behavior: It doesn't uploads document.doc into media/documents/document.doc! Instead of this Django make relational path for this file like 'document.doc' ('documents/document.docx' for the .docx file) and full path is wrong too: /home/steppenhorde/project/app/media/document.doc (/home/steppenhorde/project/app/media/documents/document.docx for the .docx file). So I get an exeption like "Package not found at '/home/steppenhorde/project/app/media/documents/document.docx'" # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') in the settings.py # file = models.FileField(upload_to='documents/') in the models.py # filepath = Model.file if filepath.path.endswith('.doc'): doc_filepath = filepath print(doc_filepath) # document.doc print(doc_filepath.path) # /home/steppenhorde/project/app/media/document.doc os.system(f'antiword {doc_filepath} > {docx_filepath}') else: docx_filepath = filepath print(docx_filepath) # documents/document.docx print(docx_filepath.path) # /home/steppenhorde/project/app/media/documents/document.docx I tried to make paths by myself like: doc_filepath = filepath splitted_doc_filepath = doc_filepath.path.split('/') doc_file_name = splitted_doc_filepath[-1] docx_filepath = f'{MEDIA_ROOT}/documents/{doc_file_name}x' But I still get an exeption like "Package not found at '/home/steppenhorde/project/app/media/documents/document.docx'" because of Django doesn't uploads document.doc into media/documents/document.doc -
Django admin, many-to-many, saving to and retrieving from DB
I have a rather simple relationship between two models: a Person and cities that the person has visited (City). class Person(models.Model): ... cities = models.ManyToManyField(City) I am writing an admin page for this, and I have a separate form class for Person which doesn't mention cities at all, and I have a class inheriting from admin.ModelAdmin, which does. I need to call a function, passing the completely saved instance of Person, with all of the fields properly updated and saved to the db, including the cities. However, whichever of the save... methods I override, I can get the Person instance to get saved and can read the new values from the db, however, I can't get the updated cities from the db. The ones that I have tried are save_m2m and _save_m2m in the form, save_form, save_related in the ModelAdmin. In each of these locations I call super().<the method> and then check person.cities.all(). Each time I get the old value (the one that was in the db before the update, and not the new value from the form). Is there a location I can tap into to get the actual saved and commited value of the many-to-many field? Is there … -
Which Django model fields won't raise IntegrityError if no input is given?
My initial thought was that if for any field null=False, then if the program does not specify a value for the field, IntegrityError will be raised for violating the NOT NULL constraint. I knew some fields such as CharField are an exception, but I tested this by adding a FileField to a model as test = models.FileField(), and not giving it any input. Saving the model did not raise any error. So my question is, which model fields allow the program to save the model when no value or default is specified and null=False? I can't seem to find any comprehensive list online. -
How to Update Django Object
I want to update an object based on various user input. I am getting the id of the object through the url: www.website/new_opportunity/new_opportunity_review?id=2. I have a nearly identical function which works perfectly fine, so I am wondering why the object is not updated upon submission using this function. views.py def new_opportunity_create(request): id = request.POST.get('id') presales_engineer = request.POST.get('presales_engineer') form_class = AssignOpportunityForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): try: obj = Opportunity.objects.get(id=id) obj.presalesEngineer = presales_engineer obj.save() except Opportunity.DoesNotExist: obj = None # Email template = get_template('new_opportunity_assign.txt') context = { 'id': id, 'presales_engineer': presales_engineer } return render(request, 'website/new_opportunity_create.html', context) new_opportunity_review.html <form action="{% url 'new_opportunity_create' %}" method="post" name="newOpportunityForm" id="newOpportunityForm" data-location-url="{% url 'new_opportunity_location' %}" data-contact-url="{% url 'new_opportunity_contact' %}"> {% csrf_token %} <div class="field"> <label class="label">Presales Engineer:</label> <div class="select"> <select name="presales_engineer" id="presales_engineer"> <option value="{{ presales_engineer_id }}">{{ presales_engineer }}</option> </div> </div> -
Save a choice from verbose_name to actual value
I want to save a CharField using the choices argument from a form sent by axios. The value sent is the verbose_name of the choice. Can I match my verbose_name with the actual value, without retyping an if/else statement which is repeating my choices tuple. Example: class Ball(models.Model): color_choices = ( ('b', 'blue'), ('g', 'green'), ... ) The POST request from axios send the value blue. So in the view, I can do this: if request.method == 'POST': data = json.loads(request.body) if data['color'] == 'blue': color = 'b' elif data['color'] == 'green': color = 'g' ... Is there a more DRYest way?