Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why aren't images being saved in my Django upload form?
I'm having trouble getting my image field to upload correctly with Django. I'm using crispy forms, and all other elements on the form and page work fine. The image field does not produce any errors error or save. I can add the image through admin just fine, it only fails on my crispy form. views.py class CarCreate(generic.CreateView): model = Car slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CreateCarForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) if self.request.POST: data['images'] = CarImageFormSet(self.request.POST) else: data['images'] = CarImageFormSet() return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.create() return super(CarCreate, self).form_valid(form) def get_success_url(self): # return reverse_lazy('showroom:cars', kwargs={'slug': self.object.id}) # Throws an error return reverse_lazy('showroom:cars') forms.py class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller', 'id'] def __init__(self, *args, **kwargs): super(CreateCarForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.form_enctype = 'multipart/' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('manufacturer'), Field('car_model'), Field('model_year'), Field('transmission'), Field('mileage'), Field('description'), Field('price'), Field('drivetrain'), Field('engine_displacement'), Field('forced_induction'), Fieldset('Add Images', Formset('images')), HTML("<br>"), ButtonHolder(Submit('submit', 'Save')), ) ) formset.html {% load crispy_forms_tags %} <table> {{ formset.management_form|crispy … -
Unauthorized response to POST request in Django Rest Framework with JWT Token
I am building a REST API with Django Rest Framework. I currently have an issue where some of my endpoints return HTTP 401 Unauthorized, whereas the vast majority of my endpoints return correct responses. For authentication I am using JWT tokens with djangorestframework-simplejwt. I've configured Django to use token auth with djangorestframework-simplejwt. # rest framework config settings REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ], The vast majority of my endpoints return valid data when I pass a valid access token in the request. If I do not send a valid token, I receive a HTTP 403. On the other hand, I have some custom API views which return a HTTP 401 regardless of whether I pass a valid token or not. I have included the code to one of my problematic views below. class CheckDifferentialView(generics.GenericAPIView): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] serializer_class = QuizDifferentialSerializer def post(self, request, *args, **kwargs): """ A function to check a quiz question and to update a user's record of questions answered """ print(request.META) if 'answer' not in request.data: return JsonResponse({'Error': 'answer not found in request'}, status=status.HTTP_400_BAD_REQUEST) answer = get_object_or_404(Differential, pk=request.data['answer']) serializer = QuizDifferentialSerializer(answer) if answer.is_correct: pass # … -
Django REST - HttpOnly cookie
It is a simple question but I just cannot find the answer. I want to have a fully safe way of storing token in my FE Those are the current steps for login + other "login required" actions SPA site requests a token (username and password) OAuth responses with a token SPA stores that token in a HttpOnly cookie Logged in SPA site requests a data from the BE (cookies are sent with the request) and here comes the problem Django gets all of the cookies EXCEPT those that are with HttpOnly flag How can I fix this? -
How to obtain cleaned_data from a FormSetView (django-extra-views)
I cannot see how to trigger and obtain the cleaned_data from my FormSetView. With a django formset, I would call is_valid() on the formset within a POST'ed response, but not sure how to do that here. Examples in documentation do not show this, afaics. I've implemented exactly as per the example in django-extra-views documentation. I already have a ModelFormSetView working fine although the DB update is automatic in that case. However, in this case of non-model implementation the cleaned data necessarily needs to be massaged into a different format for DB storage. My view (called from the url entry): class TemplateFSView(FormSetView): template_name = 'template_season.html' form_class = TemplateForm success_url = 'tee/home/' def get_initial(self): # initial data is a pre-load test for now... return [{'commence': '07:30', 'finish': '22:00', "spacing": "10"] def formset_valid(self, formset): # do whatever you'd like to do with the valid formset print('How do I get here?') return super(TemplateFSView, self).formset_valid(formset) Form: class TemplateForm(forms.Form): commence = forms.CharField(required=True, label='first tee-time') finish = forms.CharField(required=True, label='last tee-time') spacing = forms.CharField(required=True, label='tee spacing') Template: <form method="post"> {% csrf_token %} <table> {% for form in formset %} {% if forloop.counter == 1 %} <thead> <tr> <th scope="col">{{ form.commence.label_tag }}</th> <th scope="col">{{ form.finish.label_tag }}</th> <th scope="col">{{ form.spacing.label_tag … -
Django Grant permission to Foreign key objects
I have an Image model with a foreign key to Album. A User can have edit or read only permission on Album. How do users with edit Album permission, also edit Images under this Album? Is there a simple way in Django to grant User permissions over foreign key objects? -
I am not able to write a file in NFS which has some chinese character in file name
Basically, when user uploads the file I am writing that file into NFS. But it gives an error 'ascii' codec can't encode characters in position 28-32: ordinal not in range(128) I have tried to install Chinese locale and set it but it is not working I am taking the file name as this but it is not working file_name = file_name.encode('ascii').decode('unicode-escape') -
React-admin turning off reliance on X-Total-Count
I expected React-admin to work out the box with Django Rest Framework, like its website implied but my experience is that it doesn't. It has been a time consuming task trying to set custom headers to fit react-admins requirement for X-Total-Count header for every response. Django Rest Framework prefers to put the count in to the json response it seems. Does anyone know how to read this information from the json instead? It seems logical to me to set an option in react admin instead of rewriting the middleware with Django or other rest frameworks. -
Debugging git packages given in requirement.txt file for application hosted on Cloud Foundry
I am hosting a Django application on Cloud Foundry. In requirement.txt file, I am adding my git code (as a package). I have written some print statements to debug my package. where will I see those print statements. Or How Can I debug a git package I am adding in requirement.txt file. I need to check where my code is failing. I wanted to use a git package in my application. I added it in requirement.txt file and hosted my application on Cloud Foundry. But that package is failing somewhere. So, I wanted to debug where it is failing. I downloaded the package and added print statements in the package code. How can I see those print statements. Or what is the way I can debug, where that package is failing. -
Unable to track the reason for the error djongo.sql2mongo.MigrationError
I was executing an api (using GET method) of mine that has been created using Django rest framework. http://127.0.0.1:8000/api/v1/savedata Previously it was returning JSON records.When I'm executing this api end point its throwing error => djongo.sql2mongo.MigrationError: tweet_location. Note that tweet_location is a field that I have defined later in my model. Also note that I'm using MongoDB and Djongo connector to connect MongoDb from Django rest framework. /*** view code **/ class TwitterdashappViewSet(viewsets.ModelViewSet): #queryset = TwitterMaster.objects.all() permission_classes = [permissions.AllowAny] serializer_class = TwitterdashappSerializer def get_queryset(self): queryset = TwitterMaster.objects.all() tt = self.request.query_params.get('tt') if tt: condition = Q(tweet_text__contains=tt)&Q(tweet_favorite_count=13) queryset = queryset.filter(condition) return queryset def create(self, request, *args, **kwargs): serializer = TwitterdashappSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) /**** Model File ***/ class TwitterMaster(models.Model): tweet_text = models.TextField(blank=True, null=True) tweet_favorite_count = models.CharField(blank=True, null=True) tweet_location = models.TextField(blank=True, null=True) class Meta: db_table = "twitterdashapp_twittermaster" /** Serializer code */ class TwitterdashappSerializer(serializers.Serializer): tweet_text = serializers.JSONField() tweet_favorite_count = serializers.JSONField() tweet_location = serializers.JSONField() def create(self, validated_data): instance = TwitterMaster.objects.create(**validated_data) return instance -
Elasticsearch faceting for array of dictionaries with elasticsearch-dsl Python
I'm using elasticsearch-dsl to add search functionality to my Python/Django app. I'm pretty new to Elasticsearch and still learning as I go, but I have the base search functionality working. I'm now trying to implement some type of faceting. The model I'm indexing has a field called data, which consists of an array of dictionaries, kind of like tags. They are added by the user when creating a new model instance, so cannot be predefined fields. They will vary from instance to instance, and provide some random supplementary details about the model instance. For example: {'color': 'red', 'size'; 'M'} or {'condition': 'new', 'manufacturer': 'Testco'} class MyIndex(Document): category = Text() title = Text() description = Text() data = Object() class Index: name = 'my-index' Is there a way that I can set up faceting for the data field? Ideally I would like to be able to perform a search, then have filters for color, manufacturer, size and any other keys present in the data lists. So far I've tried this, which (expectedly), returns nothing when I execute the search and check response.facets.data: class ModelSearch(FacetedSearch): doc_types = [MyIndex] fields = ['title^3', 'category'] facets = { 'data': TermsFacet(field='data') } def search(self): return super().search() … -
How to recreate this view as a django model
I have the following models in my application class Semester(models.Model): name = models.CharField(max_length=100, unique=True) start_date = models.DateTimeField() end_date = models.DateTimeField() class Classroom(models.Model): semesters = models.ManyToManyField(to=Semester) name = models.CharField(max_length=100, unique=True) class AvailabilityWindow(models.Model): semester = models.ForeignKey(to=Semester, on_delete=models.CASCADE) start_date_time = models.DateTimeField() end_date_time = models.DateTimeField() optional = models.BooleanField(default=False) label = models.CharField(max_length=100) What i want to achieve is a new model called ClassroomAvailabilityWindow and i want to effectively be like the following view select * from avail_classroom c join avail_classroom_semester cs on c.id = cs.classroom_id join avail_availabilitywindow aw on aw.semester_id = cs.semester_id So that's one record, per classroom, per availability window, but only when that classroom and that semester have are joined by their many-to-many I know that i could use the view as model with managed=False but i want the users to be able to update these records. is there some way to achieve this result in django, possibly using the through option with a ManyToManyField? It's throwing me off because of the extra complexity of Classroom and Semester also being a many to many. Currently I have the model defined as below but with lots of signals set to create and destroy records when other records are created or updated and I am … -
Please enter the correct phone and password for a staff account | Django | Custom User model Authentication fails
I made a custom user model and then created a user using python manage.py createsuperuser and the same user can log in to the admin site. I then used the same model to registered another user using a register HTML page and the user object is being created in the db with the user as staff and active = True which works as expected, still while logging into through both admin login and the custom login page, it returns user object = None and shows the below error. Please enter the correct phone and password for a staff account. Note that both fields may be case-sensitive. Note: django forms isn't used. models.py ''' from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, phone, password=None, is_active=True, is_staff=True, is_admin=False): if not phone: raise ValueError("Users must have a valid phone number") if not password: raise ValueError("Users must have a password") user = self.model(phone=phone) user.set_password(password) user.active = is_active user.staff = is_staff user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, phone, password=None): user = self.create_user( phone, password=password, is_staff=True ) return user def create_superuser(self, phone, password=None): user = self.create_user( phone, password=password, is_staff=True, is_admin=True ) return user class MyUser(AbstractBaseUser, PermissionsMixin): phone = … -
Using empty related_name to access foreign object fields directly
I have three models that are very similar to eachother, and all have a foreign key to a parent model. Let's call them Applet1, Applet2 and Applet3 and all of them point to AppletGroup. Applet1 and Applet2 has a fields applet_group that is a ForeignKey, ,but Applet3 is not managed by my project, so it's fields are kept the same as fields that managing project for this model has. So I have created additional model Applet3AppletGroup class Applet3AppletGroup(models.Model): applet_group = models.ForeignKey(AppletGroup, on_delete=models.CASCADE, related_name="applet_3") applet_3 = models.OneToOneField(Applet3, on_delete=models.CASCADE, related_name="applet_group_fk") class Meta: indexes = [models.Index(fields=["applet_group", "applet_3"])] And it was working like this for quite some time. But I find it not consistent as right now to access applet_group from Applet1 and Applet2 you simply access .applet_group, but to access it from Applet3 I have to use applet_group_fk__applet_group. I started wondering if it is safe to use related_name="" in OneToOneField? -
php or python. which sould i learn php or python for web development. thank you
I'm a web designer. NOw I want to learn web development, so which one is better for me either php or python. thank you -
django bash script pass requirements as bash arguments
i have created this bash script to create django projects #!/bin/bash PROJECT_NAME=$1 ENV_NAME=$2 PROJECT_DIR="$HOME/$PROJECT_NAME" echo $PROJECT_NAME; echo $ENV_NAME; mkdir -p "$PROJECT_NAME" cd "$PROJECT_DIR" python3 -m venv "$ENV_NAME" . "$PROJECT_DIR/$ENV_NAME/bin/activate" pip install django django-extensions django-debug-toolbar python-memcached djangorestframework pip freeze > "$PROJECT_DIR/requirements.txt" django-admin startproject "$PROJECT_NAME" mkdir -p public cd "$PROJECT_DIR/$PROJECT_NAME" pwd mkdir -p templates mkdir -p static cd templates touch index.html base.html cd .. pwd cd "$PROJECT_NAME" mv settings.py settings_base.py touch settings.py settings_local.py settings_local_sample.py ls when i run source file.sh project_name env it creates the project, i want to pass the requirements of the project as array argument in the bash , how i can do it -
Django Rest Framework Permission class OR Django Middleware - Which is the best option to perform validations?
In my REST application (built in Django REST framework) containing hundreds of APIs, few of those APIs will need to have access token validated before starting its business logic, few of those APIs will need to have a key validated before its business logic. Likewise, there are different levels of validations to be performed on different group of APIs. I came to know that both permission classes and middleware can be used for validation purposes. I would like to know which of these two will be best choice for my requirement. Any related suggestion will help us to choose the effective option. Thanks in advance. -
Is it possible to (how) to lock a domain server behind a password?
I've been working on a django Web app to manage some data for tenants. Things like their personal contact information, government ID, tenancy agreements etc (in other words, very gdpr sensitive info) as well as personally private information such as expense reports. All of this is displayed on the front end of the app as intended seeing as it's supposed to be a private tool for internal company use. At the moment I run it at home on a local machine server so there is little risk involved however for my convenience I'd like to take the Web app live so I can access it while I'm out and about. The issue I'm having is that there really is no reason for anyone other than myself or business associates to use this app and therefore no reason for anyone else to connect to the domain. I've considered making the landing page of the website a login page and locking all other views behind this with CSRF protection but even that is too close for comfort in my opinion as it would mean allowing external entities tor connect to the app. I'd much rather have a server which refuses any connection … -
How to use username as a string in model in django?
I want to use the username of the account in which my django is running as a string to load the model fields specific to that username. I have created a file 'survey.py' which returns a dictionary and I want the keys as the fields. How can I get the username as string? from django.db import models from django.contrib.auth.models import User from multiselectfield import MultiSelectField from survey_a0_duplicate import details, analysis import ast class HomeForm1(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE,) details.loadData(survey_name = user)#<=====This loads the data for specific user<====== global f1 f1=analysis.getQuestion(in_json=False)#<====We get the dictionary here<======== d=list(f1.keys()) ###################assign the filters####################################################### for k in d: q=list(f1[k].keys()) q.sort() choices=tuple(map(lambda f: (f,f),q)) locals()[k]=MultiSelectField(max_length=1000,choices=choices,blank=True) def save(self, *args, **kwargs): if self.pk is None: self.user= self.user.username super(HomeForm1,self).save(*args,**kwargs) def __str__(self): return self.title -
How to open detail view in editable format as shown in admin page?
I'm trying to show the user the details they entered in an editable format as we can see in ./admin/AppName/model_name/id/change I am using Model Forms. view.py @login_required def view_phone_book(request): all_phone_books = PhoneBook.objects.filter(user=request.user) context = { 'all_phone_books': all_phone_books } return render(request, "CallCenter/view_phone_book.html", context) @login_required def detailed_view_phone_book(request, phone_book_id): try: all_contacts = Contact.objects.filter(phone_book__id=phone_book_id) context = { 'all_contacts': all_contacts } return render(request, "CallCenter/detailed_view_phone_book.html", context) except Contact.DoesNotExist: raise Http404("PhoneBook Does Not Exist!") templates ### detailed_view_phone_book.html {% extends 'CallCenter/base.html' %} {% block title %} Detailed Phone Book View {% endblock %} {% block content %} {% if all_contacts %} {% for contact in all_contacts %} <ul> <li><strong>First Name: </strong> {{ contact.first_name }}</li> <li><strong>Last Name: </strong> {{ contact.last_name }}</li> <li><strong>Phone Number: </strong> {{ contact.phone_number }}</li> </ul> {% endfor %} {% endif %} <a href="{% url 'index' %}">Back To Home</a> {% endblock %} I want to show the user the detail view in an editable way so that the changes he makes in detail view is reflected back. I have no idea on how to proceed. -
Access Reverse Relation in django
Models.py class MaterialRequest(models.Model): owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales') flow = models.ForeignKey(Flow, on_delete=models.CASCADE, related_name='flow') kit = models.ForeignKey(Kit, on_delete=models.CASCADE, related_name='kit') quantity = models.IntegerField(default=0) is_allocated = models.BooleanField(default=False) class AllotmentDocket(models.Model): transaction_date = models.DateField(default=datetime.now) dispatch_date = models.DateField(default=datetime.now) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE, related_name='allotment_sales') parent_company = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_parent') plastic_pallet = models.IntegerField(default=0) side_wall = models.IntegerField(default=0) top_lid = models.IntegerField(default=0) insert = models.IntegerField(default=0) separator_sheet = models.IntegerField(default=0) I wan to access all the material request as well as the ones which have allotment docket to create a table. For e.g I have 5 Material Request and 3 Allotment dockets, i want a table in which there are 5 rows showing all the details of material request's objects and the respective allotment objects Something like this: owner flow kit quantity platic_pallet side_wall top_lid Insert 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 - - - - 5 5 5 5 - - - - -
My djnago applicaion is on nginx. want to install wordpress on /blog
My application is running on ubuntu/nginx. I want to install wordpress on /blog url using nginx. Please let me know the best way. -
'QueryDict' object has no attribute 'first_name'
Have AttributeError 'QueryDict' object has no attribute 'first_name' Get examples from here. I'm don't understand what is the problem models.py class Employee(models.Model): first_name = models.CharField(max_length=30) second_name = models.CharField(max_length=30) patronymic = models.CharField(max_length=30) birth_date = models.DateField() views.py def edit_employee_action(request, employee_id): if request.method == "POST": form = AddEmployeeForm(request.POST) if form.is_valid(): edited = Employee.objects.filter(pk=employee_id) edited.update( first_name = request.POST.first_name, second_name = request.POST.second_name, patronymic = request.POST.patronymic, birth_date = request.POST.birth_date ) else: form = AddEmployeeForm() form = AddEmployeeForm() return render( request, 'edit_employee.html', context={'form': form} ) The parameter employee_id is correct (debugged). -
User Account activation email using Django
I am trying to create User Registration form . User account will be activated by activation email. Following error is coming:- Exception Type: NoReverseMatch at /register/ Exception Value: Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. I followed following links : https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django https://blog.hlab.tech/part-ii-how-to-sign-up-user-and-send-confirmation-email-in-django-2-1-and-python-3-6/ https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef def register(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('website/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user=user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: for msg in form.error_messages: print(form.error_messages[msg]) else: print('in else') form = NewUserForm() return render(request=request, template_name='website/register.html', context={'form': form}) def activate_account(request, uidb64, token): try: uid = force_bytes(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Your account has been activate successfully') else: return HttpResponse('Activation link is invalid!') My html file code {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' … -
Python unittest mysteriously fails because of a second test
I wrote the following unit test, which succeeds when I run it: api\test\test_views.py: class ProductListViewTest(APITestCase): def test_get_products(self): mock_products = MockSet() mock_products.add(MockModel(mock_name='e1', prod_id='1') client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get(reverse('product-list')) serialized = ProductSerializer([{'prod_id': '1'}], many=True) self.assertEqual(response.data, serialized.data) The rest of the code: # api\views.py: from api.models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer # api\urls.py: ... path('product/', views.ProductListView.as_view(), name='product'), ... However, as soon as I add a second test to the same TestCase, which uses the APIClient, the first test fails (the response.data contains an empty array)!!! def test_second_test(self): client = APIClient() response = client.get('/') self.assertEqual(True, True) if I remove the client.get() call, which doens't even make sense, the first test passes again! -
urllib.error.HTTPError: HTTP Error 403: Forbidden while executing url in python 3.x
I am trying to execute url http://domain/logout with python package urllib, getting urllib.error.HTTPError: HTTP Error 404: Not Found. But when i execute this from browser its working and logging out. urllib.request.urlopen("http://domain/logout")