Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirecting to Home Page if session not found
I'm creating a form where data is coming from previous form and i'm storing that data in session. If user directly visits second page than I want the user to redirect to first page, but I can't find any way to do it. Is it possible? my code(second page) def get(self, request): a = request.session['a'] since a is not set if user directly visits this page I want him to redirect to first page if session not found. -
Username appearing in django migrations over custom User model with no username
I have written a custom User model, with no username. Still it appears in migrations as primary key and throws unique constraint error while adding new user. Here is my User Model Manager: class UserManager(BaseUserManager): def create_user(self, password,email=None, phone=None, **extra_fields): if not email and not phone: raise ValueError("User must have an email address or phone number") if email: email = self.normalize_email(email) user = self.model(email=email,**extra_fields) elif phone: user = self.model(phone=phone,**extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.model( email=self.normalize_email(email), is_staff=True, is_admin=True, is_superuser=True, ) user.set_password(password) user.save() return user Here is my User Model: class User(AbstractUser): email = models.EmailField(unique=True, verbose_name='email address', max_length=255, null=True ) phone = models.CharField(unique=True, verbose_name='phone number', max_length=10, null=True ) name = models.CharField(max_length=300,null=True) profile_pic = models.ImageField(null=True, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return str(self.email) def has_perm(self, perm, obj=None): "Does the user have a specific permission?" return True def has_module_perm(self, app_label): "Does the user have permissions to view the app `app_label`?" return True Now,The migrrations: migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. … -
How to create an object that has an ImageField within the test code?
I'm creating something like a blog post, the blog post can contain multiple images. To be able to include a variable number of images, I created a new model called Image. This model contains a ForeignKey to the user that owns it, and an ImageField. Code: class Image(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) image = models.ImageField(upload_to=get_image_upload_path) In the post model, I have a ManyToManyField for the Image model. this way, I can have a variable number of images. images = models.ManyToManyField('Image', blank=True) I'm trying to test my code. In one of the tests, I'm trying to create a couple of images, then create a post with the images being passed to in a list. How do I create an instance of the model Image within the tests and provide it an image? image = Image.objects.create(user=self.user, image=...) What should be written instead of ... here? -
Django admin dynamically add to list_display depending on related model
I'd like to dynamically include some extra fields in the list_display of the admin for one of my models. I plan on overriding get_list_display to append a string representing a ModelAdmin method but how can I dynamically create the ModelAdmin methods? class Type(models.Model): ... modules = models.ManyToManyField(Module) class User(AbstractBaseUser): ... type = models.ForeignKey(Type) class UserModuleRecord(User): class Meta: proxy=True @admin.register(UserModuleRecord) class UserModuleRecordAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name'] def get_queryset(self, request): return ( super().get_queryset(request) .annotate_the_additional_list_display_values() ) def get_list_display(self, request): list_display = super().get_list_display(request) modules = Module.objects.all() for module in modules: list_display.append('module_%s' % module.id) return list_display In the above example if get_list_display returns [..., 'module_1', 'module_2'] that means I need methods for module_1 and module_2. Additionally is it possible to create something similar to how get_FOO_display works so there's only one admin method required? -
Hello, my database was changed from 11G to oracle 19C,
my database was changed from 11G to oracle 19C, with that I used the form of authentication using "sid", the error I was giving was 12505, currently the database uses the form "Service Name" , when changing the information in the python django format, stopped giving error 12505, however, now it is giving error ORA-28040. will I need to make any changes to the code? because I only made changes to the database data, putting it in the format that accepts the service_name -
How to import data from csv file to the default Django User model?
I know there is an import-export package which allows us to import data from csv file to our own models by making changes in the admin.py file, but I am not able to do this if I want to import data from csv file to the default User model present in Django. Is there any way to do that? -
django redirect throw 302 and not redirecting
views.py from django.shortcuts import redirect, render ... if request.method == "POST": if request.POST.get("go_to_review"): app = Appointment.objects.get(id=request.POST.get("go_to_review"), status="COMPLETED") has_review = Feedback.objects.filter(appointment=app) print(f"has view : {bool(has_review)}") if bool(has_review): return redirect("patient:patient_profile") my urls.py ... path("", patient_dashboard_view, name="patient_dashboard_view"), path("profile/", PatientProfileSetting.as_view(), name="patient_profile"), ... server log is as : ... HTTP GET /static/img/favicon.png 200 [0.00, 127.0.0.1:58430] has view : True HTTP POST /patient/ 302 [0.04, 127.0.0.1:58458] value of user inside the get_data HTTP GET /patient/profile/ 200 [0.19, 127.0.0.1:58458] ... actually it renders the other view(when i put a print statement on other view it prints that, but redirecting mean it doesn't render that view in screen but it switches to that. As I'm new to django correct me if explained wrong). ~thanks in advance -
IntegrityError at /friendreques/ NOT NULL constraint failed: core_user.pending error in Django
IntegrityError at /friendreques/ NOT NULL constraint failed: core_user.pending. How to overcome this error. user_s = User.objects.get(username = request.user) user_s.pending = edited user_s.save() In pending model is pending = models.TextField() -
Django Form upload to AWS S3 with Boto3 results in empty file
I am having a multipart/form-data form that should upload to a S3 bucket, using Boto3. All is happening as expected, but at the end, the file at the S3 bucket has 0 bytes. forms.py: class DropOffFilesForm(forms.ModelForm): file = forms.FileField(error_messages={'invalid_type': _("Please upload only PDF, JPG, PNG, XLS(x), DOC(x) files")}, validators=[ FileTypeValidator(allowed_types=['application/pdf', 'image/*', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'], allowed_extensions=['.pdf', '.png', '.jpg', '.doc', '.docx', '.xls', '.xlsx'])], required=False) description = forms.CharField(widget=forms.Textarea, label=_("Description"), required=False) def clean_description(self): data = self.cleaned_data['description'] return data class Meta: model = DropOffFiles exclude = ['filename',] fields = ['file', 'description'] views.py: file_form = DropOffFilesForm(request.POST, request.FILES) if file_form.is_valid(): file_form = file_form.save(commit=False) s3 = boto3.client('s3', region_name=settings.AWS_ZONE, aws_access_key_id=settings.AWS_KEY, aws_secret_access_key=settings.AWS_SECRET) file = request.FILES['file'] if file: file_type = file.content_type extension = file.name.split(".")[-1] # construct file name and location filename = calculate_md5(file) + '.'+extension # save the file try: response = s3.upload_fileobj(file, 'bucketname', filename) except ClientError as e: logging.error(e) return False file_form.filename = filename file_form.dropoff = dropoff file_form.save() Happy for any suggestion. -
How do I send all form data from one view to another with sessions in Django
So I already know how to send and receive one value from InputWebView to DisplayWebView but I need to send all values from my form and receive it on the other side to process further. How do I do that? <form method="POST" action=""> {% csrf_token %} {{ form.non_field_errors }} {{ form.web_input }} <input type="submit"> </form/> def InputWebView(requests): form = WebInputForm(request.POST or None) if request.method == 'POST': if form.is_valid(): request.session['web_input'] = request.POST['web_input'] return redirect('add_web') def DisplayWebView(request): var = request.session.get('web_input') -
ValueError at /cart/ Cannot assign "'admin'": "CartItem.user" must be a "User" instance
I get ValueError when i try and save an object, The error is related to User being assigned to a model. When i use without string method (only user=request.user) it says TypeError at /cart/ str returned non-string (type User) when i apply string method (user=str(request.user)) it gives me ValueError at /cart/ Cannot assign "'admin'": "CartItem.user" must be a "User" instance. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem from django.contrib.auth.decorators import login_required from .forms import BookForm # Create your views here. def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) elif request.method == "POST": user = authenticate(request, username=request.POST['username'], password=request.POST['password']) … -
Unable to login as a vendor in django rest framework
I have three types of users in CustomUser model each provided with an integer value. Also, I have made a separate view for login for vendor. I registered a user as vendor from default django admin. But I am unable to login as a vendor when I call the login as vendor api. I get the error message saying this is not a seller account. My models: class CustomUser(AbstractUser): username = None first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") email = models.EmailField(unique=True) Type_Choices = ( (1, 'Customer'), (2, 'Vendor'), (3, 'Admin'), ) user_type = models.IntegerField(choices=Type_Choices, default=1) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email My serializers: class CustomLoginSerializer(LoginSerializer): username = None email = serializers.EmailField(required=True) password = serializers.CharField(style={"input_type": "password"},) user_type = serializers.IntegerField() My views: class VendorLoginUserView(LoginView): permission_classes = [AllowAny] serializer_class = CustomLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = CustomLoginSerializer(data=data) data['user_type'] = request.user.user_type user_type = data['user_type'] if user_type is 2: serializer.is_valid(raise_exception=True) new_data = serializer.data user = serializer.validated_data["user"] serializer = self.get_serializer(user) token, created = Token.objects.get_or_create(user=user) # return response.Response(new_data, status=status.HTTP_200_OK) return response.Response({"token": token.key, "serializer.data": serializer.data}, status=status.HTTP_200_OK) else: message = "This is not a seller account" return Response({'message':message,}, status=status.HTTP_400_BAD_REQUEST) My urls: path("api/vendorlogin/",views.VendorLoginUserView.as_view(), … -
How to translate the name of days of the week and months in Django calendar
I would like to ask how can I change the name of the days of the week and month from the original English to e.g. Polish in the calendar rendered in Django I tried to find a solution in changing the language in the settings but nothing works I also tried to use LocalHTMLCalendar but it didn't work this is my utlis.py file class Calendar(LocaleHTMLCalendar): def __init__(self, year=None, month=None): self.year = year translation.activate('pl') self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) print() return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal and this is my views.py … -
Correct way to read data for a graph
What i want to do is to show some data in a graph. the data is from a pandas data frame that i generated in my main.py file when crunching some numbers. Now i want to show this in a chartsJS graph in another html. Is the correct way to leave my data frame that i generated in my main.py file and generate the graph by looking at the main.py file an reading the data frame. or is the correct way to generate a django model and have the graph read the data from a django model? The data frame will change everyday, hence the graph will be changing daily. If the latter is correct could someone show me how they would make the model if the data frame is just some text with numbers print(df["my_data"]) pass: 20 fail: 50 n/a: 8 -
How to write a bitbucket-pipelines.yml for react and django application to deploy on heroku
On the bitbucket, my all build scripts are running perfectly but when I am deploying the app on heroku then I am getting this build error: -----> Building on the Heroku-20 stack -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz ! ERROR: Application not supported by 'heroku/nodejs' buildpack ! ! The 'heroku/nodejs' buildpack is set on this application, but was ! unable to detect a Node.js codebase. ! ! A Node.js app on Heroku requires a 'package.json' at the root of ! the directory structure. ! ! If you are trying to deploy a Node.js application, ensure that this ! file is present at the top level directory. This directory has the ! following files: ! ! backend/ ! myapp/ ! db.sqlite3 ! manage.py ! media/ ! ! If you are trying to deploy an application written in another ! language, you need to change the list of buildpacks set on your ! Heroku app using the 'heroku buildpacks' command. ! ! For more information, refer to the following documentation: ! https://devcenter.heroku.com/articles/buildpacks ! https://devcenter.heroku.com/articles/nodejs-support#activation More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed My project file format is this : /backend /backend /myapp /media -manage.py -db.sqlite3 -runtime.txt -requirements.txt /frontend /src /node_modules -index.html -package.json -package-lock.json … -
Is it possible to get the coverage for the functions and classes for the unit tests for a Django Project?
I am working on a Django project and I would like to know if it is possible to get the coverage for the functions and the classes ? I tried to do that : But I cannot achieve to get the coverage for functions and classes like I can do it using php unit : Could you help me please ? Thank you very much ! -
Django Rest Framework - How to get the json response in a way, so that it is easier to access in frontend?
Hey guys I have this serializer to get the list of pending users, class UserInfo(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'username',] class PendingRequestSerializer(serializers.ModelSerializer): other_user = UserInfo(read_only=True) class Meta: model = PendingRequest fields = ['other_user', ] views.py class PendingRequestListApiView(APIView): permission_classes = (IsAuthenticated,) def get(self, *args, **kwargs): user = PendingRequest.objects.filter(user=self.request.user) serializer = PendingRequestSerializer(user, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I am getting the json response like this. [ { "other_user": { "id": 8, "username": "testuser5" } }, { "other_user": { "id": 4, "username": "testuser2" } } ] I want the json response to look like this instead. "results": [ { "id": 4, "username": "testuser2", }, { "id": 8, "username": "testuser5", } ] That is instead of having the user information in separate other_user, is it possible to combine it like it is in the second response? Thanks -
Why select_related in Django ORM apply join before where clause?
Consider I have two tables namely Class Department(model.Models): id = models.AutoField(primary_key=True) Class Employee(model.Models): dep = models.ForeignKey(Department) exp = models.IntegerField() Now in views class I am using get_queryset function def get_queryset(self): return Employee.objects.using(schema).filter(exp_gte=date).select_related('dep') Sql statement create is in this form Select `Employee`.`dep`, `Employee`.`exp`, `Department`.`id` from `Employee` Inner Join `Department` on `Department`.`id`= `Employee`.`dep` Where `Employee`.`exp` >= date; Why is join before where clause. And how can I apply join after where clause using Django ORM -
NoneType object is not callable django admin
I have an app in django admin, im trying to make some validations, Transaction model and its a parent for 2 models, FamilyGroup and FamilMember class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) number_of_family_group = models.PositiveSmallIntegerField( null=True) class FamilyGroup(models.Model): name = models.CharField(max_length=10, choices=name_choices) transaction =models.ForeignKey(Transaction,on_delete=models.CASCADE,related_name='family_groups') class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True, related_name='family_members') name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) Im trying to make custome validations in the transaction model like this @property def clean(self): b = FamilyGroup.objects.filter(transaction__id=self.id).count() if self.number_of_family_group != b: raise ValidationError('worng family') when im trying to do this im getting an error NoneType object is not callable -
'WSGIRequest' object has no attribute 'build_absolute_url'
I am building a BlogApp AND I am building Post Share Feature AND I am stuck on an Error. When i click on Share Button then it is showing me this error :- 'WSGIRequest' object has no attribute 'build_absolute_url' views.py def post_share(request, post_id): post = get_object_or_404(Post,id=post_id) sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_url(post.get_absolute_url()) subject = f"{cd['name']} recommends you read "\ f"{post.post_title}" message = f"Read {post.post_title} at {post_url}\n\n" \ f"{cd['name']}\'s comments, {cd['comments']}" send_mail(subject, message, 'admin@myblog.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'post_share.html', {'post':post,'form':form}) models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) description = models.CharField(max_length=10000,default='') post_share.html {% extends 'base.html' %} {% block title %}Share a Post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.post_title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.post_title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send by e-mail"> </form> {% endif %} {% endblock content %} The Problem When i click on Send by Email then it keeping showing me 'WSGIRequest' object has no attribute 'build_absolute_url' … -
the use of the underscore : q.choice_set.all()
I am working on the Django "Writing your first Django app, part 2", in the section "2.4.4 Playing with the API". If someone could explain to me how does the underscore works in this code "q.choice_set.all()" -
Django 'ManagementForm data is missing or has been tampered with' foreign manytomany foreign key
I'm getting this error after submitting my form(it uses inlines and foreign keys). This is a follow up to my question: How to save a model in ModelForm with two ForeignKey fields in Django Now my views.py looks like this: def CreateFlo(request): EstadosInlineFormSet = inlineformset_factory(Listaflor, Flora2Estado, form=Flo2Form) floForm = FloForm(request.POST) if request.method == 'POST': if floForm.is_valid(): new_flo = floForm.save() estadosInlineFormSet = EstadosInlineFormSet(request.POST, request.FILES, instance=new_flo) if estadosInlineFormSet.is_valid(): estadosInlineFormSet.save() else: estadosInlineFormSet = EstadosInlineFormSet() floForm = FloForm() context = {'floForm': floForm} return render(request, 'accounts/enviar_flora.html', context) -
Separate two forms' values in django
I'm working on an ecommerce website. Currently, I'm trying to add variations for products. Variations are dynamic. For adding products to the cart I have two forms, one for general details of the product, and the other for the variations. The problem is when I add a product with specific variations I can't separate these two forms' values from each other. The post request's data is like this --> <QueryDict: {'quantity': ['1'], 'override': ['False'], 'Color': ['1'], 'Size': ['3']]}> As I said color and size are dynamic and it could be more variations, and these are variation items so if I could change post request data to be like this --> {'variations': [1, 3]} it could solve the problem. # forms.py class VariationForm(forms.Form): def __init__(self, variation_fields, *args, **kwargs): super(VariationForm, self).__init__(*args, **kwargs) for field in variation_fields: self.fields[field.name] = forms.ModelChoiceField( queryset=field.item_variations.all()) # views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) # Variation form should come here if form.is_valid(): cd = form.cleaned_data cart.add( product=product, quantity=cd['quantity'], override_quantity=cd['override'], ) return redirect('cart:cart_detail') -
is configured to read a sid, but the database has changed to service_name. What changes should I make?
is configured to read a sid, but the database has changed to service_name. What changes should I make? -
How to use django_crontab with os.environ['SECRET_KEY']?
I'm using a django_crontab library and it worked fine until I decided to export my SECRET_KEY to an environmental variable. Summing up what I have done in bash (while in my venv): export SECRET_KEY='some_secret_key_from_settings' In settings.py: SECRET_KEY = os.environ['SECRET_KEY'] In addition, I use venv, so I've also added this to settings: CRONTAB_PYTHON_EXECUTABLE = '/path_to_my_venv/venv/bin/python3' This is the error that I have: SECRET_KEY = os.environ['SECRET_KEY'] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 681, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' The closest solution I found was this: https://github.com/kraiz/django-crontab/issues/74 However, I'm not too experienced in this stuff and didn't understand what I should do. I will be very grateful for answers with explicit steps I could take to make it work