Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Incorporating calendar into django application
I have a planning puzzle, where I have some resources like machines etc, and each machine has a calendar or multiple machines can share a calendar. For each task/process planned on a particular machine I have to attach a schedule on the associated calendar of the machine or book the time slot, the schedule consists of day and duration. Which module can serve my purpose effectively where I can also look for the next available slots and next working day? I am new to django and haven't worked on calendar before. Any suggestion? -
Django: got error when make Post request: CORS policy: Request header field body is not allowed by Access-Control-Allow-Headers
I installed django-cors-headers and have set everything correct in settings.py CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'corsheaders', ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # new ... Here is how I make post request: fetch("http://localhost:8000/isaapi/isaitem/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem("token")}`, body: "" //JSON.stringify(body) } }) .then(res => res.json()) .then(json => { console.log(json); }) .catch(error => console.error(error)); I checked the response's header: Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Wed, 09 Jan 2019 08:22:27 GMT Server: WSGIServer/0.2 CPython/3.6.3 Vary: Origin which shows I already got Access-Control-Allow-Origin: *. Also I have tried clear broswer cache.. but no luck... still getting Error: Access to fetch at 'http://localhost:8000/isaapi/isaitem/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field body is not allowed by Access-Control-Allow-Headers in preflight response. Anyone knows what's wrong here ? -
Display images form the admin panel
I want to make a app in which admin upload a image on admin panel and it display on the template. I'm know there are some question related to this but I tried all of them but still can't display image. Django version: 2.1.4 python version: 3.6.7 In setting.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'image') In model.py from django.db import models class ImageModel(models.Model): caption = models.CharField(max_length=40) image = models.ImageField(upload_to='uploadImage', blank=True) def __str__(self): return self.caption In view.py from django.shortcuts import render from .models import ImageModel def image_page(request): images = ImageModel.objects.all() return render(request, 'input/hello.html', {'image':images}) In urls.py from django.contrib import admin from django.urls import path, include from image import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.image_page), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In imageShow.html <img src="{{ ImageModel.image.url }}" alt="image" /> doing this show me a broken image and some time the full url of the image(where is the image is saved) What I'm doing wrong thanks in advance -
how to import classes from one module and initialise and run it in django
How to import classes from all .py in a module with same structure and run by iterating over it. For Example, module_one: script_a: class A: def __init__(self,**kwargs): code here def run(self,**kwargs): code here def finish(self,**kwargs): code here script_b: class B: def __init__(self,**kwargs): code here def run(self,**kwargs): code here def finish(self,**kwargs): code here and so on ... module_two: script: class Run: def run_all(self,**kwargs): for class in classes_from_module_one: c = class() c.run() c.finish() -
how to send email using smtp mail server in django
i want to allow users to send emails once they submit the form in order to inform that they submit the form and a new record is added to the database. i tried to add the basic arguments in settings.py and add the send_mail function with all the required arguments in order to send the email. settings.py # email setup EMAIL_HOST = 'smtp.hushmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'devleb@hushmail.com' EMAIL_HOST_PASSWORD = '**********' EMAIL_USE_TLS = True views.py send the email after to inform selected sections send_mail('New Te2shira', 'hello there this is a test email.', 'devleb@hushmail.com', ['camiw@mail-2-you.com'], fail_silently=False) i expect from this code to once the user submit the form the system automatically will send the email to the receiver list in order to inform them that a new record is added to the database. -
Define ForeignKey to a model before defining that model
So I am in a situation where I need to create a foreign key to a model before that model is defined. Consider the following models: class Question(models.Model): """Model for question.""" question_text = models.TextField(blank=True, null=True) answer = models.ForeignKey(Option, on_delete=models.PROTECT) # Can't do this class Option(models.Model): """Model for options of a question.""" question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=127) So as you can see, I have a model to save a Question(text and its answer). Also I have another model to save one option which is linked to a question. That way I can create variable number to options for a question, one of which will be correct. But I can't link the correct option to the model Question because the model Question needs to be declared first to link each Option to a Question. Is there some way I can achieve this. -
Updating User and its user profile in django
How to I bind User fields data and user profile data to a model form on my view, I only get user data rendered to a form when i use instance=user but it doesn't render any data of user profile on instance=profile, what i need is to render all user and its profile to a form. models.py class User(AbstractUser): is_supervisor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Supervisor(models.Model): user = models.OneToOneField('User', on_delete=models.CASCADE, primary_key=True, related_name='supervisor') su_mobile_number = models.CharField(max_length=200) view.py def supervisor_update(request, user_id): # user = get_object_or_404(User, pk=user_id) user = get_object_or_404(User, pk=user_id) profile = get_object_or_404(Supervisor, pk=user_id) if request.method == 'POST': form = SupervisorSignUpForm(request.POST, instance=user) else: form = SupervisorSignUpForm(instance=user) return save_user_form(request, form, 'partials/partial_supervisor_update.html') form.py class SupervisorSignUpForm(UserCreationForm): su_mobile_number = forms.CharField(label="Mobile Number") class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name') supervisor_update.html {% load crispy_forms_tags %} <form method="post" action="{% url 'supervisor_update' form.instance.pk %}" class="js-supervisor-update-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Update Supervisor</h4> </div> <div class="modal-body"> {% include 'partials/form_messages.html' %} {{ form.username|as_crispy_field }} {{ form.email|as_crispy_field }} {{ form.first_name|as_crispy_field }} {{ form.last_name|as_crispy_field }} {{ form.su_mobile_number|as_crispy_field }} </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update Supervisor</button> </div> </form> -
Adding dynamic fields to a serializer in django-rest-framework
I have a model class Event(models.Model): random_fields... class Registrations(models.Model): user = models.ForeignKey(User...) event = models.ForeignKey(Event...) ts = models.DateTimeField(...) Now I want to fetch the list of all the events along with whether the user who made the request is registered in that event or not (is_registered field in the ModelSerializer of Event maybe). This should ideally happen in a single request and not too many database queries. What is the efficient way to do this? -
How to set Session on LoginView in-built Django
I want to set session in django after user logged in and destroy session on logout. i am using in-built Auth LoginView to Login path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), -
Print CSV file in django like in jupyter
I want to print csv file in django project with the rows and column like in jupyter notebook I have print the csv with my code but i got like this main.py : def upload(): import pandas as pd dataset = pd.read_csv('./data.csv') return dataset views.py : def upload(request): upl = main.upload() upload = {'upl': upl} return render(request, 'apps/upload.html', upload) file.html : <p>{{upl}}</p> I got the result like this Src Eqid Version ... Depth NST Region 0 ak 10565543 1 ... 11.7 5 Central Alaska 1 nc 71848295 0 ... 4.3 8 Northern California 2 ci 15221369 0 ... 30.3 11 Greater Los Angeles area, California 3 us 2012fzay 4 ... 10.0 18 Tanzania 4 ak 10565529 1 ... 22.6 6 Central Alaska 5 nc 71848265 0 ... 2.2 10 Central California 6 nn 00389471 9 ... 10.3 10 Nevada 7 us c000cw89 4 ... 39.6 0 southern Iran 8 us c000cw7u 7 ... 52.3 28 Costa Rica 9 nc 71848255 0 ... 5.0 9 Northern California 10 nc 71848240 0 ... 9.3 21 Central California 11 nc 71848235 1 ... 0.1 30 Northern California 12 ci 15221361 0 ... 2.6 31 Central California 13 ci 15221353 0 ... 13.5 32 … -
Change errors in password change serializer in rest-auth
I am using Django rest-auth to have endpoints for my registration, password change, etc. I'm working with the password change endpoint which contains the old password, new password, and confirm password. I am trying to override somethings in the original serializer like adding my own error messages if the field is incorrect for example. However, one error message I'm having difficulty overriding is if the fields are blank. The default error message appears like so each time: { "old_password": [ "This field may not be blank." ], "new_password1": [ "This field may not be blank." ], "new_password2": [ "This field may not be blank." ] } I'd like to implement my own error message if the field is blank, however, I am not able to do that. Here's the serializer I created: class PasswordChange(PasswordChangeSerializer): set_password_form_class = SetPasswordForm def validate_old_password(self, value): invalid_password_conditions = ( self.old_password_field_enabled, self.user, not self.user.check_password(value) ) if all(invalid_password_conditions): raise serializers.ValidationError('The password you entered is invalid.') return value and here is the form class: class PasswordForm(ChangePasswordForm): oldpassword = PasswordField(label=_("Current Password")) password1 = SetPasswordField(label=_("New Password")) password2 = PasswordField(label=_("Confirm New Password")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['oldpassword'].widget = forms.PasswordInput(attrs={"placeholder": ""}) self.fields['password1'].widget = forms.PasswordInput(attrs={"placeholder": ""}) self.fields['password2'].widget = forms.PasswordInput(attrs={"placeholder": ""}) def clean_oldpassword(self): … -
Are the global variables for a package in python can considered as evil?
For start, sorry for my bad English. Recently I read book called "elegant objects" by Yegor Bugayenko. One of the topics in this book is dedicated to using of objects instead of public constants. Author writes that public constants is a pure evil. There are a lot of reasons for this. For example, using of public constants breaks incapsulation - if we want to change this contant we need to know how classes of our package using this constant. If two classes in project are using this constant in its own way we need to change code of this two classes if we change constant. Author suggests that instead of using global constants we need to create objects and that's allows us to change code only in one place. I will give an example below. I already read similar topics on stackoverflow, but did not find the answer about best practices or use cases. Is the use of objects better than creating a global variable in some file, for example "settings.py"? Is this class WWStartDate: date_as_string = '01.09.1939' def asTimestamp(self): # returns date as timestamp def asDateTime(self): # returns date as datetime object better than this stored in some file … -
Display associated value of foreign key in createview of django
I have two models: store and claim where store is the foreign key of claim. I am using the CreateView generic views. In the form at frontend, I can see the list of store as like username + Store but I want to display the store's name as option's label and id in value in the dropdown list. The two models are like: class Store(models.Model): user = models.OneToOneField(Ext_User, on_delete=models.CASCADE) store_name = models.CharField(max_length=50, default='', null=True, blank=True) description = models.CharField(max_length=50, default='', null=True, blank=True) .... class Claim(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE) expense = models.DecimalField(max_digits=999, decimal_places=0) customer = models.ForeignKey(Ext_User, on_delete=models.CASCADE) .... class of creating claim: class ClaimCreateView(CreateView): model = Claim template_name = 'claim/claim_form.html' fields = ['store', 'expense'] def form_valid(self, form): form.instance.customer = self.request.user return super().form_valid(form) def test_func(self): claim = self.get_object() if self.request.user == claim.customer: return True return False what I can see at frontend: I want to display the store name instead of these default values. -
Database model for scheduling
I need to create a database for a truck delivery scheduling app using Django. Each truck can have recurring orders (e.g mon, tues, wed). Sometimes the order can be unchecked/edited or added to a different truck for a specific date (e.g Monday 27th of Jan). How would this be represented in a database model? -
"This Field is Required" error even after sending the fields
class DroneList(generics.ListCreateAPIView): queryset = Drone.objects.all() serializer_class = DroneSerializer name = 'drone-list' filter_fields = ( 'name', 'drone_category', 'manufacturing_date', 'has_it_competed', ) search_fields = ( '^name', ) ordering_fields = ( 'name', 'manufacturing_date', ) permission_classes = ( permissions.IsAuthenticatedOrReadOnly, custompermission.IsCurrentUserOwnerOrReadOnly, ) def perform_create(self, serializer): serializer.save(owner = self.request.user) Views.py class DroneSerializer(serializers.HyperlinkedModelSerializer): # Display the category name drone_category = serializers.SlugRelatedField(queryset=DroneCategory.objects.all(), slug_field='name') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Drone fields = ( 'url', 'name', 'drone_category', 'manufacturing_date', 'has_it_competed', 'inserted_timestamp', 'owner' ) class UserDroneSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drone fields = ( 'url', 'name') Serializer.py class DroneCategory(models.Model): name = models.CharField(max_length=250, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Drone(models.Model): name = models.CharField(max_length=250, unique=True) drone_category = models.ForeignKey( DroneCategory, related_name='drones', on_delete=models.CASCADE) manufacturing_date = models.DateTimeField() has_it_competed = models.BooleanField(default=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( 'auth.User', related_name='drones', on_delete=models.CASCADE ) class Meta: ordering = ('name',) def __str__(self): return self.name models.py {"name":"Python Drone", "drone_category":"Quadcopter", "manufacturing_date": "2017-07- 16T02:03:00.716312Z", "has_it_competed": "false"} Post request I had send. the fields are not read by django as shown in the response: "name": [ "This field is required." ], "drone_category": [ "This field is required." ], "manufacturing_date": [ "This field is required." ] -
Textbox for Other option of selectbox on django , openedx platform Best practice advice
I want to take an advice if my way is best practise or not . If not please give me your advice. I have a selectbox one option of the selectbox is "Other" while user select "Other" option then a textarea will shown for answering . I think making this process with those steps . Firstly i want to say i have build the selectbox via forms and model choices 1.Creating a new column for saving user's text on user_profile table (table is for conditional on this example). 2.Adding new hidden textarea field to register form . 3.Doing frontend tasks(hiding/showing textarea) with Jquery . 4.Making some validation for avoiding frontend changes by user on forms.py . Please give me advice this is good practice or not ? Any good recommand is acceptable. My model is for goal column : GOALS_CHOICES = ( ('1', unicode( 'Test1',encoding='utf-8')), ('2', unicode( 'Test2',encoding='utf-8')), ('3', unicode( 'Test3',encoding='utf-8')), ('4', unicode( 'Test4',encoding='utf-8')), ('5', unicode( 'Test5',encoding='utf-8')), ('6', unicode( 'Other',encoding='utf-8')) ) goals = models.CharField( blank=True, null=True, max_length=6, db_index=True, choices=GOALS_CHOICES ) -
Configuring import errors while installing the project
I am installing the Django==1.9.1 project of the former team (I am newcomer) to my server it runs on Centos7. I did as I usually do: installed all the required things and run: pip install -r requrements.txt Then I run the following code: python manage.py makemigrations But I am receiving the following error ImportError: No module name insurance.mixins insurance.mixins is my library. I checked and it is where it should be. What can I do to fix this! -
Django Rest API - ProgrammingError relation 'core_donation' does not exist
Here is a link to my github repo: https://github.com/hertweckhr1/api_foodcycle My user endpoints work great. However when I try to reach my endpoint localhost:8000/api/donation/donations, I get back the error: enter image description here I have tried makemigrations donation and migrate several times. It says my migrations are up to date. Other posts similar to this, I have not been able to find a solution that works for me. Thanks in advance! -
Django- How to get my current location in django
I want to get my current location in django so that I can compare the distance with my location and other city. lat1, lon1 = origin #current location lat2, lon2 = destination #location of other city Further I want to compare between these two for a distance. I have destination lat and long but looking for current lat and long -
Using selenium script to test URL but after browser opens, it does not point to the requested URL
I am following this tutorial to learn more about Test-Driven Development with Django but have hit a snag. In tutorial we are asked to use the following code which, when run, opens up my Firefox browser and dircts to the URL (http://localhost:8000). from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title When run (using PyCharm), the browser opens with no issue but does not direct to the URL and the address bar remains blank. If I manually type in the URL it shows what should appear. After some searching the only real results I found were that there were compatibility issues but after updating everything I am still encountering the error. Does anyone have any suggestions as to resources to help solve the issue or maybe know a solution? Thank you for your time. -
SMTPSenderRefused at /password-reset/ (530, b'5.5.1 Authentication Required)
I set a gmail account to send emails to reset password. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('Email_User') EMAIL_HOST_PASSWORD = os.environ.get('Email_Password') I already turned on lower access from app. I managed to receive the email in my another gmail account by testing locally. But when I tested it in website, I GOT this error. And I also got an alert email said Someone just used your password to try to sign in to your account from a non-Google app, and it was blocked. I wonder is there another way to change settings to bypass this issue? -
Difference between instantiating models by manager and model-name in Django
When I instantiate the model, I usually used the manager, e.g. user = User.objects.create_objects(name='Tom', age='25') but, sometime I can also see the code like, user = User(name='Tom', age='25') Are these two identical codes? -
Trying to pass a string for querying through Django Rest Framework urls
I have a django project and I am using Django Rest Frameowkr. I setup up a model, serializer, view, and url for a users model. I have the urls file. I want to passing in something like a username when the api url is called. I currently have it setup to have a primary key so when I enter a primary key it works. I want to switch it to username. I also want the serializer query to return the user object iwth the usename I pass in. I am using Djangos standard User object from django.contrib.auth.models Here is the code I have Urls.py from django.urls import path from django.contrib.auth.models import User from .views import UserListView, UserDetailsView from .views import ProfileListView, ProfileDetailsView from .views import RoleListView, RoleDetailsView urlpatterns = [ path('user/', UserListView.as_view()), path('user/<pk>', UserDetailsView.as_view()), ] serializer.py file from rest_framework import serializers from django.contrib.auth.models import User from users.models import Profile, Role class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'last_login') Views.py file from rest_framework.generics import ListAPIView, RetrieveAPIView from django.contrib.auth.models import User from users.models import Profile, Role from .serializers import UserSerializer, ProfileSerializer, RoleSerializer class UserListView(ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetailsView(RetrieveAPIView): queryset = User.objects.all() … -
Django app: "Docker Container does not have a com.docker.compose.container-number label"
The exact error I'm getting is: ValueError: Container e3efba4d793f does not have a com.docker.compose.container-number label I'm not sure what is going on here. I'm running from a valid, stable branch. I'm able to run the app fine using "docker-compose -f docker-local.yml up." But when I try to run the test suite using "docker-compose -f docker-local.yml run web python3 manage.py test" I get the error that I mentioned above. My configuration hasn't changed or anything. I have tried reinstalling docker (on mac) and rebuilding the container. Thanks for the help! -
How to add a condition to form valid in django
Intro: I am creating a events app, I want the user to choose a date between 3 days from today to a maximum of 30 days from today class CreateEvent(IsVerifiedMixin, CreateView): model = Event form_class = EventForm template_name = 'event/event_form.html' def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) event = self.object today = datetime.date.today() user = self.request.user if today + datetime.timedelta(days=3) <= event.date <= today + datetime.timedelta(days=30): event.user = self.request.user event.initial_stock = event.stock slug = self.kwargs['slug'] event.save() else: #I know the below line of code is wrong. How do I fix this messages.error(self.request, "The event date has to be equal or more than 3 days away and less than 30 days") return super().form_valid(form) The above gives me a IntegrityError if the date is off if the date is correct the object is created. I just want to get a form error and the form to not go to the next page