Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Change form styling of django-filters from SelectMultiple to CheckboxInput¶
I feel that the documentation is quite unclear on this. I have the following filter logic on an attribute called categories of model ProductPage (works as intended): class ProductFilter(django_filters.FilterSet): class Meta: model = ProductPage fields = ['categories'] def product_list(request): f = ProductFilter(request.GET, queryset=ProductPage.objects.all()) return render(request, 'product/filter.html', {'filter': f}) Template looks like this: <form method="get"> {{ filter.form }} <div class="fieldWrapper"> {{ filter.form.name.errors }} {{ filter.form.name }} </div> <input type="submit" /> </form> I get the typically Multiple Select form which technically works well: Picture of form However, I would rather have a few checkboxes / radio buttons / something similar. Yet, I have no idea where to get access to the styling or type of widget. -
'widget_tweaks' to style the formset.empty_form
Does anyone know how I can use 'widget_tweaks' to style the formset.empty_form. Check the documentation however when applying it I get this error: the object 'PartForm' does not have attribute 'as_widget' I think i'm not doing well in html. I already used widget_forms on the same page and it looks good; but when implementing it in empty_forms it doesn't work presupuestos-forms.html <div class="form-row" id="empty-row"> {{formset.empty_form|add_class:"form-row" }} </div> -
How to Logout the App when Refresh the page ? In Django
This Is My code of login in Django Application from django.shortcuts import redirect, render from django.contrib.auth import authenticate,logout,login from django.contrib.auth.decorators import login_required from SedHelper.settings import LOGIN_URL from .models import HelperApps # Create your views here. def Login(request): if request.method == 'GET': if request.user.is_authenticated: logout(request) return render(request,'login.html') elif request.method == 'POST': username=request.POST['username'] password=request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect(home) else: error={ 'LoginSts':False, 'MSG':'You are not Logged In' } return render(request,'login.html',context=error) # No backend authenticated the credentials def logout_view(request): print(request.user.is_authenticated) if request.user.is_authenticated: logout(request) return redirect(Login) def home(request): #load all data from db(10) if request.user.is_authenticated: posts=HelperApps.objects.all()[:11] return render(request,'dashboard.html',{'posts':posts}) else:return redirect(Login) I just wanted to Logout when ever someone refresh the Page .In entire Application where ever someone refresh the the page it should logout immidiately.Anyone please. i am also new to stackoverflow Please try to ignore the mistakes. -
TypeError: __init__ missing 1 required positional argument: 'to', I get this error when I make migrations "python3 manage.py makemigrations"
Python 3.8.10, django version 3.2.9. When I am running the following code: "python3 manage.py makemigrations auth_app" ... I get this error: TypeError: init() missing 1 required positional argument: 'to'. I've checked out everything that says the error and still get the same.This is the whole error message. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/allfsr/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/allfsr/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/allfsr/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/allfsr/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/allfsr/.local/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/__init__.py", line 1, in <module> from .account import Account File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/account.py", line 4, in <module> class Account(models.Model): File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/account.py", line 6, in Account user = models.ForeignKey(related_name='account', on_delete= models.CASCADE) TypeError: __init__() missing 1 required positional argument: 'to' -
django jQuery date picker wont change date format
I have a django form which as two date fields. I am trying to have a Calendar Pop-up with the default date being sent on click as ("yyyy-mm-dd"). I have tried this several ways, changed the setting in the javascript, changed the django settings file, but no matter what the form says invalid date and the date format that gets sent to the field always is mm/dd/yyyy. Here is an example of the code In the form I have: from django import forms from functools import partial DateInput = partial(forms.DateInput, {'class': 'datepicker'}) class SearchForm(forms.Form): start_date = forms.DateField(widget=DateInput(format = '%Y-%m-%d'), required=False, input_formats=['%Y-%m-%d']) end_date = forms.DateField(widget=DateInput(format = '%Y-%m-%d'), required=False, input_formats=['%Y-%m-%d']) My tempplate has the following: <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script> $(document).ready(function() { $('.datepicker').datepicker() }); </script> <TR> <TD COLSPAN="3" ALIGN="Center"> Start Date:&nbsp;{{ form.start_date }}&nbsp;&nbsp; End Date:&nbsp;{{ form.end_date }} Date Format <B>MUST</B> be YYYY-MM-DD<br> Dates are inclusive.<br> If a date is left blank it is assumed to go until the start or end.</TD> </TR> I have tried putting dateFormat('yyyy-mm-dd') inside the datepicker code , as well as format('yyyy-mm-dd'), format('yy-mm-dd'). None of them changes the way to date is sent to the field, it's always "mm/dd/yyyy'. The form says this is not … -
I need to create an authentication for a distributor using jwt
I need to create an authentication for a distributor using jwt. However I'm only able to create the authentication token for the superuser. Could someone help me create a way to authenticate the distributor? Here are the models: class Distributors(TimeStampedModel): name = models.CharField("Nome completo", max_length=250) cpf = BRCPFField("CPF") email = models.EmailField("Email") password = models.CharField("Senha", max_length=15) def __str__(self): return self.name authentication needs to ask for name and password