Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weird Django & Angular "No 'Access-Control-Allow-Origin' header is present" when deployed on Cloud server with Nginx
I seem to have a problem with the "No 'Access-Control-Allow-Origin' header is present on the requested resource" on my deployed app. When I am testing these on my localhost:4200 which is angular and localhost:8000 with backend, it works perfectly fine. Below are the Localhost screenshots now this are the deployed angular app What's really weird is that, it only shows the error on this angular component while my other are also similar but works perfectly fine Like this for example I already did the normal cors configurations in django which is INSTALLED_APPS = ['corsheaders'] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware'] CORS_ORIGIN_ALLOW_ALL = True -
How to enable validators in custom account manager for custom user model in Django?
I created a custom User model called Staff, so that I can login through an email. Doing so requires a custom create_user function, which I created following a tutorial. I also created a custom validator for the EmailField, so when I create a User, only certain domains are accepted. However, writing tests for this function, I found out that it allows creating users with domains outside what I want. This is the custom create_user function: class CustomAccountManager(BaseUserManager): def create_user(self, email, first, last, password, **other_fields): if not email: raise ValueError('You must provide an email address') email = self.normalize_email(email) user = self.model(email=email, first=first, last=last, **other_fields) user.set_password(password) user.save() return user And this is how I am making the test: def test_new_user(self): user = Staff.objects.create_user(email='testuser@sertronicsa.com', first='Test', last='User', password='password') self.assertEqual(user.email, 'testuser@sertronicsa.com') self.assertEqual(user.first, 'Test') self.assertEqual(user.last, 'User') self.assertFalse(user.is_superuser) self.assertFalse(user.is_staff) self.assertFalse(user.is_active) with self.assertRaises(ValueError): Staff.objects.create_user(email='', first='Test', last='User', password='password') with self.assertRaises(ValidationError): Staff.objects.create_user(email='test@user.com', first='Test', last='User', password='password') What is really weird is that from the admin page, if I do not use the domain sertronicsa.com, it doesn't allow me to create the user, like I intend to. What I need help with is figuring out how to make my create_user function use the validator, so it raises the error in the test. … -
My InlineRadios django crispy form doesnt work properly
I use InlineRadios for choice field, the default is using select option and i want to use radio button instead of select option this is my model.py class Member(TimeStampedModel): class Religion(models.TextChoices): ISLAM = 'islam', _('Islam') KRISTEN = 'kristen', _('Kristen') KATOLIK = 'katolik', _('Katolik') HINDU = 'hindu', _('Hindu') BUDHA = 'buddha', _('Buddha') KHONGHUCU = 'khonghucu', _('Khonghucu') LAINNYA = 'lainnya', _('Kepercayaan Lainnya') class Gender(models.TextChoices): MAN = 'man', _('Pria') WOMAN = 'woman', _('Wanita') def get_photo_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('uploads/photo/', filename) def get_id_card_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('uploads/card/', filename) location = models.ForeignKey(Location, verbose_name = _('member location'),on_delete=models.CASCADE) name = models.CharField(_('member name'), max_length=60) religion = models.CharField(_('religion'), max_length=10, choices=Religion.choices) gender = models.CharField(_('gender'), max_length=5, choices=Gender.choices, default=Gender.MAN) phone_number = PhoneNumberField(_('phone number')) university = models.ForeignKey(University, verbose_name = _('university'), on_delete=models.CASCADE) email = models.EmailField(_('email requested with domain aptisi.or.id')) photo = models.FileField(upload_to=get_photo_file_path, verbose_name = _('photo')) id_card = models.FileField(upload_to=get_id_card_file_path, verbose_name = _('id card')) this is my forms.py class MemberForm(ModelForm): class Meta: model = Member fields = [ 'location', 'name', 'religion', 'gender', 'phone_number', 'university', 'email', 'photo', 'id_card' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.disable_csrf = True self.helper.layout = Layout( 'location', 'name', 'religion', InlineRadios('gender'), … -
why is my workshop textbox not working django?
i have a webpage as shown in the picture below where the admin will select their role but i not sure why my workshop textbox is not working, everything looks perfectly fine to me and the code looks exactly the same. As can be seen from the image below, i can select all but not the workshop textbox register.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <html lang="en"> <head> <style> .button { background-color: #38d39f; border-color: #38d39f; color: white; padding: 10px 20px; text-align: center; display: inline-block; margin: 4px 2px; cursor: pointer; border-radius: 16px; width: 285px; } </style> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css' %}"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- Style --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>SCS staff registration</title> </head> <body> <div class="content"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 contents"> <div class="row justify-content-center"> <div class="col-md-12"> <div class="form-block"> <div class="mb-4"> <h1>Staff Registration page</h1> </div> <p>Register Page</p> <form method="post"> {% csrf_token %} <div class="form-group first"> <label for="username">Username</label> {{ form.username }} </div> <div class="form-group first"> <label for="firstname">First Name</label> {{ … -
Deploy Django app to Heroku AFTER DATABASE?
I have deployed my django website to Heroku but since the website fields are dependent upon a database that is on my local machine. I've tried using Postgres but the database on Heroku doesn't populate with the data I need it to before the app runs. Has anyone experienced this? Do I need to use an exteranl database on AWS or something (in which case, what is the best way to do this?) -
Django - Django Swagger add custom list of request body params to expect
So for Django Rest Swagger you can add a way to list the params in the request body for example: @api_view(['POST']) @swagger_auto_schema( request_body=Serializer, ) How can I change it so that request_body takes in a list of expected request body attributes? Because I have a post endpoint that should take in a request body of lots of attributes and apply 2 serializers on it, where each serializer will only serialize the proper attributes that it requires. Is there a way to do this? -
Save Image from RSS Feed to Django Image Field
I have a model like this: #models.py class Post(models.Model): cover = models.ImageField(upload_to="news/", blank=True, max_length=255) Then, I pulled the image url from RSS feed using BeautifulSoup4: #views.py def pull_feeds(request, pk): source = Autoblogging.objects.get(pk=pk) url = requests.get(source.url) soup = BeautifulSoup(url.content, "html.parser") cover = soup.find('media:content')['url'] Post.objects.create(cover=cover) The content feed is something like this <media:content url="https://travelcommunication.net/wp-content/uploads/2021/10/Raffles-Hotels-Bring-Legendary-Hospitality-Experience-to-Romantic-Udaipur-TRAVELINDEX-TOP25HOTELS-500x300.jpg" width="500" height="300" medium="image" type="image/jpeg"/> But it only save the url, not the image file. How to save the actual image file instead of url to that image? -
Display items using checkboxes and POST only the checked ones
I am working on a sort of attendance check system which is a webpage. Actually I want a student when registering to be able to select the courses he is enrolled for through the use of checkboxes and then later get this data through POST. How can I achieve this using django modelforms?, how is the rendering done in the template? And how should I POST the data from the checkboxes in my views? Need help please. Thanks. -
Price start DateTimeField and End DateTimeField duration Show the price django models
I will Input start DateTimeField and End DateTimeField from Admin Panel. Offer Price will be shown when the start time will match now() time. I mean when the current time match starts DateTimeField The the price will be shown in the HTML form. similarly, when the End DateTimeField matches the current time the offer price will be shown OFF from the HTML form. model.py ------- class Product(models.Model): price = models.DecimalField(max_digits=6, decimal_places=2) offer_price = models.DecimalField(max_digits=6, decimal_places=2) duration = models.DurationField('duration') offer_price_start_date = models.DateTimeField(blank=True, null=True) offer_price_end_date = models.DateTimeField(blank=True, null=True) def duration(self): return self.offer_price_end_date - self.offer_price_start_date views.py -------- def product_detail(request): product_data = Product.objects.all() context = { 'product': product_data } return render(request, 'show.html', context) show.html --------- {% if product.duration %} <a> Before Price ${{ product.price }} </a> <a> Now ${{ product.offer_price }} </a> {% endif %} -
Change choices list in child model Django
I have a model that is being inherited by another one and has a field that has choices. Is there any way I can change the choices options, or append a new item to choices on the inherited model level? class ModelA(PolymorphicModel): choice1 = "choice1" choice2 = "choice2" CHOICES = ( (choice1, "Choice 1"), (choice2, "Choice 2"), ) method = models.CharField(max_length=30, choices=CHOICES) class ModelB(ModelA): # In this model, I have to exclusively add `choice3` to choices. -
Django algolia search: How to create search for multiple models
In Django I have 4 different models class Baby(model.Model): name = ... #(babys name) description = ... .... other fields not common class BabyStore(model.Model): name = ... #(name of the shop) description = ... .... other fields not common class BabySitter(model.Model): name = ... #(babysitter name) description = .... .... other fields not common class BabyDoctor(model.Model): name = ... #(babydoctors name) description = ... .... other fields not common As per https://github.com/algolia/algoliasearch-django we have to register each model import algoliasearch_django as algoliasearch from .models import YourModel algoliasearch.register(YourModel) This will create seperate index for each model. In my case i want to have a search UI for all of them together and use the model as the facet. eg: So how to use multiple indexes and create a single search I know within each index, we can have facets. But here Along with that i want to use each index as a facet itself -
How transfer data from on list to another in Django?
I'm doing a small to-to list, I'm stuck in views.py, there are to-do tasks, in-progress tasks and done tasks, I want to move a task from the to-do task list to the in-progress task list, I can't figure out how to delete the data in the to-to task and make new data same as to-do task in the in- progress task at the same time. It would be great if anyone can help, I'm totally new to Django. Thanks. ''' models.py class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.text[:60] + "..." class Progress(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.ForeignKey(Todo, on_delete=models.CASCADE) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.text ''' -
What's the difference between the trans tag and the _() function in templates?
I mean you can do: {% load i18n %} {{ trans 'some string' }} Or {{ _('some string') }} Both are discoverable by makemessages, and rendered correctly. At least with Django 2.0.2. -
Django migration not working properly on Heroku
I have deployed a Django App like 3 months ago and i was able to migrate changes easily on the heroku bash. Right now i'm trying this: heroku run python manage.py migrate Also tried this: heroku run python manage.py migrate --no-input And i tried accesing to the heroku bash like this: heroku run bash And then run: ~ $ python manage.py migrate All this commands seems to work: https://i.stack.imgur.com/JWW6S.png But they don't. When i tried to migrate again, i thought it would show me the typical No migrations to apply.. But this is not the case ¿What should i do to migrate changes? -
I am creating css flip cards for projects using Django template tags to iterate over the cards. All of the buttons only flip the first card
As it says in the title. I know Django well, but am still getting the hang of using JS for this type of thing. I am iterating over the cards with {% for project in projects %}, and everything is showing up as it should. And, when I click the button on the first card, it flips the card perfectly. However, when I click the button of any other card, they also flip the first card as well, instead of flipping the next card itself. I think it has something to do with the id of the divs or labels, and have tried a few things but I haven't quite figured it out. Here is the necessary HTML: <div class="wrapper"> {% for project in projects %} <div class="card"> <input type="checkbox" id="card1" class="more" aria-hidden="true"> <div class="content"> <div class="front" style="background-image: url({{ project.image }})"> <div class="inner"> <h2>{{ project.title}}</h2> <label for="card1" class="button" aria-hidden="true"> Details </label> </div> </div> <div class="back"> <div class="inner"> <div class="info"> </div> <div class="description"> <p>{{ project.description }}</p> </div> <div class="location">Warsaw, Poland</div> <div class="price">38€ / day</div> <label for="card1" class="button return" aria-hidden="true"> <i class="fas fa-arrow-left"></i> </label> </div> </div> </div> </div> {% endfor %} The CSS pertaining to the cards: <style> .wrapper { display: flex; … -
Creating a mobile app that uses both a restful api and websockets
I am trying to make an iOS app. Currently, my frontend is coded in swift and my backend is in python. I have been using django's rest framework to make an api to satisfy all the http requests I need. However, I also want to implement a chat feature in this app where two users can send messages to each other. I realise that this will mean the application will need to be updated in realtime, and so I will need to implement some form of web-sockets. Right now, I believe my best bet is incorporating Django channels into my project, but that being said I am not sure that that is the best way forward. My main concerns are whether Django rest framework and Django channels would work well together, and whether there is another/ more efficient way to implement web-sockets. Any advice/help would be greatly appreciated. Thanks in advance! -
Math calculations - backend or frontend
I am creating a web application(Django + Angular) whose main purpose is to draw shapes. I calculate and draw all the shapes myself. Where is it better to do the calculations (calculating line equations, finding common points)- on the backend and ask the server or on the frontend? Thanks -
Efficiently serializing multiple objects that need to make REST call
Say I have a simple model, Account, as follows: class Account(models.Model): name = models.CharField(db_index=True) And an AccountSerializer as follows: class AccountSerializer(serializers.ModelSerializer): name = CharField(source="account.name") def _get_favorite_color(self, obj: Account): # Make a rest call to get this account's favorite color favorite_color = _get_favorite_color(name) I also have a ViewSet with a list action to get all accounts, as well as a Serializer to serialize each items. The JSON returned has the following shape: { 'accounts':[ {'name':'dave', 'favorite_color':'blue'}, {'name':'john', 'favorite_color':'black'}, ] } What is the django-esque way of 'bulk' fetching these favorite colors? This REST call to obtain favorite colors can take as an input a list of all account ids and return them in a single list, avoiding to make n REST calls when just one can do. Where would this logic live to make the most sense? I can't put this logic in the Serializer considering that it only handles one object at a time. Is there another place to put it rather than the ViewSet? My understanding is that ViewSets should be as lean as possible. -
Django Rest API - How to change user password?
I'm trying to change my users password using Django REST Framework (DRF) but I only get back a empty response and I don't understand why, please have a look at my code. url.py re_path(r'^api/v1/user/change_password$', API_Views.change_password, name='api_change_password'), views.py @api_view(['PUT']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def change_password(request,): if request.method == 'PUT': serializer = ChangePasswordSerializer(request.user) return JsonResponse(serializer.data, safe=False) serializers.py class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('old_password', 'password', 'password2') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError({"old_password": "Old password is not correct"}) return value def update(self, instance, validated_data): instance.set_password(validated_data['password']) instance.save() return instance What do I miss here? Please also have a look at the request I build -
django attachments broke when check for authentcation
i have media folder contain attachments, this attachments can be exported to other intgerations like JiRA, it works well without authentcation , but with auth check the files are broken not sure why -
Django Login with Captcha and two factor auth
I'm quite new to Django and have managed to create my own login page integrated with axes and repatcha which basically displays captcha upon 3 failed login attempts with my own error messages - this all works fine as required howver I would now also like to add two factor authentication with what I already have implemented. I had have managed to install django two factor auth package but it seems I am forced to use the login page that comes with two factor auth package. Having spent so much time on my own login and with added features I desperately need to keep this in place. I believe I am able to edit the two factor auth template files but the main issue is being able to use the features from my existing view/decorators with the two factor auth views. The following is my current setup: URLS from django.urls import path, include from . import views urlpatterns = [ path('login/', views.loginpage, name="login"), path('logout/', views.logoutuser, name="logout"), ..., ] View @axes_dispatch @check_recaptcha_login def loginpage(request, credentials: dict = None): attempts_list = get_user_attempts(request, credentials) attempt_count = max( ( attempts.aggregate(Sum("failures_since_start"))[ "failures_since_start__sum" ] or 0 ) for attempts in attempts_list ) #print(attempt_count) attempt_count = attempt_count … -
Django extending template
When I extend the home.html file with {% extends 'menu.html'%}, it also extends it with the menu.css file. I need a home.css file. How can I fix this problem? Thank you for your help -
How to connect the addresses in my sqlite db to position markers with google maps API's Django
I'm starting to program in Django and also starting to use Google API's, in a few words for my little project, i need to set marker points based in my SQLite db linked to the addresses the users register, to the map displayed in my HTML, i know that i need to convert those addresses strings into coordinates in a JSON file, and that JSON file is the one the API can read and display, so far i managed to set the map, geolocation and set pointers from an example file based on a url which google documentation gives you. I'll be forever grateful if someone can guide me tru these questions: a) How do i convert that address variables of my model in Django to a readable Google API JSON. b) How do i call that JSON file to display it on my map. Thank you so much for your time! let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 2, center: new google.maps.LatLng(2.8, -187.3), mapTypeId: "terrain", }); infoWindow = new google.maps.InfoWindow(); const locationButton = document.createElement("button"); locationButton.textContent = " Mi ubicacion "; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click", () => { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) … -
TypeError: __init__() got an unexpected keyword argument 'widgets'
i am getting error when i write forms.py from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UsernameField class SignupForm(UserCreationForm): password1= forms.CharField(label='password',widget=forms.PasswordInput(attrs={'class':'form-control'})) password2= forms.CharField(label='Confirm password(again)',widget=forms.PasswordInput(attrs={'class':'form-control'})) the server says username= UsernameField(label='username',widgets=forms.TextInput(attrs={'autofocus':True,'class':'form-control bg-success'})) File "C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\fields.py", line 216, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'widgets' but when i write widgets in meta class class LoginForm(AuthenticationForm): username= UsernameField(label='username') password= forms.CharField(label=('password'),strip=False) class Meta: widgets={ 'username':forms.TextInput(attrs={'autofocus':True,'class':'form-control'}), 'password':forms.PasswordInput(attrs={'autocomplete':'current-password','class':'form-control'}), } the server totally works but form control class doesn't in the html page. html code is here {% extends 'base.html' %} {% block content %} <div class="col-sm-10"> <h3 class="text-white my-5"> Login Page</h3> <form action="" method="post" novalidate> {% csrf_token %} {% for fm in form %} <div class=""> {{fm.label_tag}}{{fm}}<small class="text-warning">{{fm.errors| striptags}}</small> </div> {% endfor %}<br> <input type="submit" class=" btn btn-primary" value="Login"> {% if form.non_field_errors %} {% for error in form.non_field_errors %}<br> <p class="alert alert-danger my-3">{{ error}}</p> {% endfor %} {% endif %} </form> </div> {% endblock %} help me with this please.and thanks in advance. -
ValueError: Field 'maca' expected a number but got ''
I have a model like this class MacaModel(models.Model): maca = models.PositiveIntegerField( db_column='Maca', blank=True, null=True ) I have form like this class MacaForm(models.ModelForm): maca = forms.CharField(required=False,widget=forms.TextInput(attrs={'placeholder': 'Maca'})) I'm trying to send null value from input, but got this error ValueError: Field 'maca' expected a number but got ''. How can I handle if I don't send a value accept is as a None value or something like that?