Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add break to page between parts in django?
I'm creating a page, but for some reason content is not going down but it's going to right. I have tried to use tag br but it's now working. Why is this happening? and... how do I fix it? {% extends "base.html" %} {% load static %} {% block content %} {% include "parts/text_story1.html" %} <br> {% include "parts/text_story2.html" %} <br> <p> <form action="{% url "upload_story" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload Story!"/></p> </form> </p> {% endblock content %} This is how it looks, now it's not important to styling a details but this is a bigger problem. -
Can't see tree when using $tree in django mac terminal
Whenever I try to see my files using $tree, nothing happens. Here is a picture of the code im trying to run. And here is what it is supposed to return. -
Serving Static Files in Heroku
I have a Django and React app hosted on Heroku, the issue is that it does not see my files but everything is completely working in my localhost. It was built successfully on Heroku. Debugging process: Project built successfully Opens App Returns a blank page meaning it is not serving my CSS and js files. Checked Developer tools The Django app requires the CSS and js files to show the template Checked Heroku logs Heroku returns err 404 for those files Check my Deployed files in Heroku I checked to see my files that are deployed in Heroku in my terminal, and they are there. Now, I'm confused, why is it not serving the files, it's not a code problem cos everything is working well in my localhost. Any solutions pls? Thanks. -
How to load part of html page in django?
Before I used to load just part of page in django. Usually it used to be a text that I did not want change often, but I forgot how to do it, now I cannot find it. I have two html docs, in one I want to load other, can you tell me where I made a mistake? Text to load text_story.html <p>Some text!</p> Page where is loaded text about.html {% extends "base.html" %} {% load static %} {% load "parts/text_story.html" %} {% block content %} {% endblock content %} Thanks in advance! -
Django NoReverseMatch error - urls.py path appears to match
In a Django application I am building as a project for an online course, I am expecting a link in one template (entry.html) to direct to a path ("edit") in urls.py with a variable in the url. This should initiate a function called edit in views.py and render the template edit.html. I am getting a NoReverseMatch error ("Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<entry>[^/]+)/edit$']") after clicking the link in entry.html. If I view page source while on entry.html in the development server, I can see the url matches that in urls.py but I still get this error. In the example below, "maggie" is the value for entryTitle I'm trying to pass. entry.html: {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py (last path listed is edit) from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/<str:entry>/edit", views.edit, name="edit") ] edit function in views.py from django.http import HttpResponseRedirect from django.urls import reverse class EditPageForm(forms.Form): content = forms.CharField( widget=forms.Textarea(), label="Edit Content:") def … -
how to pass a function in python mock side effect
I want to achieve the following: mocked.side_effect = somefunction and when mocked() gets called I want somefunction() to get executed however, right now when mocked() gets called only the name of the function is returned and not the callable. Note: I don't want to just do mocked.side_effect = somefunction() because that will call the function first and then result in a value. I would like the function to be called when mocked is called -
How do I render {{ STATIC.URL }} from textfield in database django
I am new to web development and currently building a blog. I want to render HTML that I am pulling in from the database. The HTML is successfully rendered by using |safe but I cant seem to render django template tags {{ STATIC_URL }} within the href. Can someone help me understand why this is not working and what could be the possible solution? html <p class="article-redirect">{{ article.redirect|safe|escape }}</p> models.py class Articles(models.Model): redirect = models.TextField(blank=True, null=True) database "redirect" textfield (the string I want to render) <a href="{{ STATIC_URL }}/articles/8-Photogenic-Spiral-Staircases" class="link-within">8 Photogenic Spiral Staircases</a> -
How do I resolve database migration error due to changed migration filename?
I'm still pretty new to Python as well as Django so I have a situation I'm not sure how to resolve. Main issue is that on deploy of my code to dev, deployment fails, to stage or prod, it passes. I worked on an issue where I had to drop some columns in a table in our app. After making the changes, I deployed to dev and asked for a code review. In code review, it was suggested I change the name of the migration file to something more descriptive rather than just leaving it 0018_auto_. I made that change and deployed to dev and stage. Dev failed (when I expected it to succeed) because the new name was seen and django tried to drop columns that no longer exist. In stage, the name was never changed and the columns were dropped for the first time using that new name of the file. So stage deploys just fine. How do I resolve this error on dev so it recognizes this migration already took place? Thanks! -
My Django REST admin page shows locally but in production I get a 404. What am I missing?
The actual API is working fine. My only issue is that the '/admin' route 404's in production. from django.contrib import admin from django.urls import path from appname import views urlpatterns = [ path('admin/', admin.site.urls), path('people/', views.people_list) ] -
Scheduled Tasks django-rest-framework
I built an api that scrapes data from a web. It needs to scraping every hour. How can I manage to program scraping in the background, and doesn't break the requests of the clients? I apologize for any error gramatical. -
Django - manager on ManyToMany relationship
I have 3 models class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField (Person, through = 'Membership', related_name = 'companies') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) is_admin = models.BooleanField() I can then call person.companies.all() to get the list of companies associated with person. How do I create a manager to have the list of companies associated with person, but whose person is admin (is_admin = True)? -
Django - Show Timeslots by Availability
I'm new to django & python. I've spend ~2-3 weeks on this and have tried many, many solutions. I have a vehicle scheduling service. Customers can login and see their vehicles and schedule service. They can select a service center ("branch"), a date, time, their vehicle, and the service they want. I want to be able to show available slots by date AND branch. Here is what I have so far. Models.py class NewAppt(models.Model): created = models.DateTimeField(auto_now_add=True) start_time = models.DateTimeField(blank=False) end_time = models.DateTimeField(blank=False) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True) unit = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True) vin = models.CharField(max_length=17) sold_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) servicelevel = models.ForeignKey(ServiceLevel, on_delete=models.SET_NULL, null=True) servicetype = models.ForeignKey(ServiceType, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.branch} | StartTime = {self.start_time} | EndTime = {self.end_time} | SoldTo = {self.sold_to} | Service = {self.servicetype} | Level = {self.servicelevel}' class Meta: ordering = ['branch', 'start_time'] unique_together = ('branch', 'start_time') @property def duration(self): return self.end_time - self.start_time class BranchSchedule(models.Model): """Creates one schedule for each branch""" branch = models.OneToOneField(Branch, on_delete=models.CASCADE, primary_key=True) holidays = models.CharField(max_length=1000, validators=[int_list_validator], blank=True, null=True) # list of comma separated days [2021-01-01, 2022-12-31] monday_first_appt = models.TimeField(blank=False, null=True) monday_last_appt = models.TimeField(blank=False, null=True) tuesday_first_appt = models.TimeField(blank=False, null=True) tuesday_last_appt = models.TimeField(blank=False, null=True) wednesday_first_appt = models.TimeField(blank=False, null=True) wednesday_last_appt … -
How to convert back mysql data in original format?
How to get back the data in original format. Screenshot database screenshot -
How to POST an entity specifiying an integer foreign key in django rest framework
I am building a chat application with django rest framework and I m currently working on messages. This are my models: from django.db import models from django.contrib.auth.models import User class Message(models.Model): text = models.CharField(max_length=500) datetime = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE); I am using the Django auth User model. This is my ModelViewSet for the messages: class MessageViewSet(ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer And these are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class MessageSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Message fields = '__all__' And this is my API: The code I've written so far works really well for the GET functionally I want. I want for each message to get the username of the user it belongs to. But now I want the following thing: when I POST a new message, I want to me able to specify with user it belongs to by specifying the user's id. Right now I have only the "text" field in the POST section. I need to add a "user" field which takes in an integer (the user primary key) to specify which user the message belongs to. How should I refactor my code in … -
Override Djange ImageField extension validation
Understand I can add a validator to Django's ImageField validators to restrict file extension types like below. But in terms of the error messages which are displayed via upload on Admin -- I'm still seeing the standard file type list (via PIL allowed types), if I upload a non-image type. If I upload an image type which is not in my custom allowed_extensions below, I see my custom message. How can I override Django's default ImageField handling, and show my custom error message no matter what type of file is uploaded (e.g. when any file other than .png is uploaded per below example)? class MM(models.Model): file_extension_validator = FileExtensionValidator( allowed_extensions=['png'], message='File extension not allowed. Allowed extensions include .png' ) image = models.ImageField( help_text='Upload images only (.png).', validators=[file_extension_validator], max_length=255, blank=False, null=False ) -
Using Python, how can I add attributes to Say in a Gather?
I am saying some text in a Gather. I would like to change the speech rate and I see that I can do this with Prosody, but I don't know how to implement this in Python (Django). Here is something I tried that didn't work: resp = VoiceResponse() with resp.gather(input='DTMF Speech', action=my_url, method='GET', num_digits=1) as g: g.say('Hello', voice='Polly.Amy-Neural') g.say.prosody(rate='50%') return HttpResponse(str(resp), content_type='text/xml') -
Django: How to use handler500 to redirect to a frontend server page and also receive admin error email
My question is very similar to this one, except my problem is that my frontend page is in another server, an Angular application. Basically, what I need is to send a redirect response to my Angular frontend when user faces a 500 error, but also would like to receive admin e-mails with stack traces. This only happens when the response is a 500, not the 302 returned by the handler500 redirection. -
How to access a model's attribute from another model without a Forein Key in Django?
I have two models: class PiggyBank(models.Model): date=models.DateField(default=None) depositor=models.CharField(max_length=100) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) class Withdrawal(models.Model): date=models.DateField(default=None) particulars=models.CharField(max_length=200) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) balance=models.DecimalField(max_digits=10, decimal_places=2, default=0) voucher_number=models.IntegerField() I want to access the amount field of PiggyBank from Withdrawal to write a method to calculate balance. But these models are not connected through a Foreing Key. How can I do that? -
How should I be using Access-Control-Allow-Headers?
I'm building an backend in Django that accepts requests from other domains, so I'm using django-cors-headers to handle CORS. I'm hitting a snag with one of the outside domains hitting my backend, though, because their request code a) sets withCredentials and b) has some extra headers in the request. Both of these should be irrelevant to them being able to hit my backend, but I get the expected errors of Access-Control-Allow-Credentials' header in the response is '' which must be 'true' and Request header field [field_name] is not allowed by Access-Control-Allow-Headers in preflight response. Some other stackoverflow posts pointed me to Access-Control-Allow-Credentials = 'true' for the first, and Access-Control-Allow-Headers = '*' for the second, but I couldn't find much on what best practices are. What I'm trying to figure out is Is it safe to set both of these flags? There are other headers included in the request that handle authentication via tokens, so I'm not sure if there's much security risk here Should I instead tell my users that my backend disallows credentials and other headers (because they're not necessary to the code working)? The docs for Access-Control-Allow-Headers specify ‘The value “*” only counts as a special wildcard value … -
Browsing Server-Side SMB Mount with React and Django
I am developing a web application using a React frontend and a Django backend, and have run into the following engineering requirement: Users would like to, through the web app, browse files stored in a computing cluster (accessible via SSH and SMB) at my university. The frontend needs access to the directory system on the cluster in order for users to select files, and the backend needs access in order to read the contents of those files. I have successfully performed an SMB mount on my own machine (which I am running the server on during development), but am wondering how I might approach this integration with the front end. I ask that you bear with me if I am over-complicating or overlooking things; I am quite new to backend development. Thanks in advance. -
Elastic Beanstalk returns 502 Bad Gateway?
I have a web application which runs on AWS ElasticBeanstalk and once i'm access this view, it returns 502 Bad Gateway. def word_processor(request): sentence_freq_rank, kincaid_score, dict_file_path, doc_file_path = freq_rank_score.main() # sentence_freq_rank, kincaid_score, dict_file_path, doc_file_path = ( # 1, 2, 3, 4) return JsonResponse({'sentence_freq_rank': sentence_freq_rank, 'kincaid_score': kincaid_score, 'doc_file_path': doc_file_path, 'dict_file_path': dict_file_path}) And the freq_rank_score.main() def main(): text = "estamos reformando a nossa casa" dict_file = "word_frequency_portuguese_corpus.txt" doc_dir_name = "Inteligibilidade - Corpus - Âncoras - Nível 01 - Leitor iniciante" doc_file_name = "Âncora Alfabetização - 09 Fofão.docx" dict_dir_name = os.path.dirname(__file__) dict_file_path = os.path.join(dict_dir_name, dict_file) doc_file_path = os.path.join(doc_dir_name, doc_file_name) sent_req, flesch_kincaid_score=get_scores_from_doc(doc_file_path, dict_file_path) return sent_req, flesch_kincaid_score,dict_file_path,doc_file_path if __name__ == "__main__": main() this project work fine in local environment but after deploying it to EB it returns BadGateway, I think problem is freq_rank_score.main() but I don't know why ? And EB's log says this, [error] 661#661: *19614 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: , request: "GET /webapp/wordprocess HTTP/1.1", upstream: "http://127.0.0.1:8000/webapp/wordprocess" Any idea what's wrong here ? -
Is there an easy way to only serialize non-empty fields with Django Rest Framework's ModelSerializer?
I am working on a Django project with a number of rather large models (around 80 fields). I am using Django Rest Framework's ModelSerializer to serialize the models, and ViewSets to provide an API for my frontend. That works very well, but I would like to reduce the amount of data that is being transferred by the server. Most of my model fields are optional and many instances only have values for a few of them. In those cases I would like to serialize only those fields that have values (i.e. that are truthy). I imagine I could do that either on the serializer side or on the model side, but I do not quite understand how these two talk to each other, so to speak. My current serializer is very simple: class OutfitSerializer(serializers.ModelSerializer): class Meta: model = Outfit fields = '__all__' The view is equally simple: # Outfit views class OutfitViewSet(viewsets.ViewSet): def list(self, request): queryset = Outfit.objects.all() serializer = OutfitSerializer(queryset, many=True) return Response(serializer.data) I fiddled with sub-classing the serializer and modifying the __init__ function (inspired by this part of the DRF docs): class NonEmptyFieldsModelSerializer(serializers.ModelSerializer): """ ModelSerializer that allows fields to be set at runtime via the optional 'fields' argument … -
Django template loop through API results to display in table
so I have some data being returned via API which I am passing into my template I am having an issue though in displaying the data as currently it is showing each char per row, I am trying to make it so in the table I have the coin name in a row with the value in the next col and so on. Data being returned- {"error":[],"result":{"ZGBP":"30622.0790","DASH":"0.5104491200","ADA":"2473.80445621","ZUSD":"67787.8285","KSM":"24.7142610000","CHZ":"13773.0349000000","XXLM":"6926.27220000","KNC":"0.0000000000","MATIC":"1838.9295772000","ZRX":"0.0000000000","BAL":"0.0000000000","XXDG":"17006.92601155","LINK":"144.2407000000","USDT":"60000.00000000","TRX":"923.80015900","COMP":"0.0000034600","ENJ":"257.6815000000","DOT":"0.0000000000","XLTC":"11.4923900000","SC":"0.0000000200","XZEC":"0.0000073100","SOL":"1133.3543869800","SUSHI":"172.4585500000","XXRP":"0.00000000","XETH":"14.5877343640","AAVE":"83.6218990800","ATOM":"151.26763831","XXBT":"0.0000012880","ALGO":"32063.69514500","OCEAN":"652.6077000000"}} My template- <table class="table table-hover table-bordered"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Amount</th> </tr> </thead> <tbody> {% for v in api_reply %} <tr> <td>{{ v }}</td> </tr> {% endfor %} </tbody> </table> -
Django REST API serializer.is_valid() always returns false
I'm trying to make a POST request from the frontend to the backend through REST API. I'm passing as data a dictionary which contains all the fields of the table from the database Data from frontend looks like this: var state = { event: { name: "test", id_organizer: 1, start_date: "2019-11-11T11:11:11", end_date: "2019-12-11T11:12:11", location: "test", description: "test", id_type: 1, status: "pending", } } and POST request like this: axios .post("http://127.0.0.1:8000/api/addevent", state.event) .then(response =>{ console.log(response.data); }) .catch(err => console.log(err)); Here is the model of the event: class Event(models.Model): name = models.TextField() id_organizer = models.ForeignKey(User, on_delete=CASCADE, db_column='id_organizer') start_date = models.DateTimeField() end_date = models.DateTimeField() location = models.TextField() description = models.TextField() id_type = models.ForeignKey(EventType, on_delete=CASCADE, db_column='id_type') status = models.CharField(max_length = 50) class Meta: db_table="events" Here is the database table Here is the @api_view: @api_view(['POST']) def addevent(request): if request.method == "POST": data = JSONParser().parse(request) serializer = EventSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({'saved':True},status=status.HTTP_201_CREATED) else: return Response({'saved':False}, status=status.HTTP_400_BAD_REQUEST) Here is the serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' The request happens but the function serializer.is_valid() always returns false and the response is always {'saved':False} I already validated the data that it is sent correct and when I printed it, I got the output: … -
Get all sessions from memcached with Django
I'm using memcached to store my session. Is there a way to get all the session from memcached displayed? I'm looking for a way to manage the sessions and delete the sessions manually through some user interface