Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Curl command doesn't work in config file on AWS
I have a Django web application that is deployed to AWS elastic beanstalk (Python 3.7 running on 64bit Amazon Linux 2/3.1.3). I am trying to run the following config file files: "/usr/local/bin/cron_tab.sh": mode: "000755" owner: root group: root content: | #!/bin/bash exec &>> /tmp/cron_tab_log.txt date > /tmp/date source /var/app/venv/staging-LQM1lest/bin/activate cd /var/app/current python manage.py crontab add exit 0 container_commands: cron_tab: command: "curl /usr/local/bin/cron_tab.sh | bash" This file placed in the .ebextentions folder. All other config files are working properly. However, this one is not working. Also, I have tried to run the container_commands code manually on SSH and it gives output such as below. curl: (3) <url> malformed I also checked the /tmp folder but there is no cron_tab_log.txt. I checked /usr/local/bin the cron_tab.sh is located there. I just want this Django-crontab run after the deploy and it doesn't work. How can I handle this issue? -
upgrade django2 to 3 DigitalOcean droplets missing css files
I just install fresh image of django from DigitalOcean droplets marketplace and its work perfectly but its version 2 so I try to upgrade it to 3 and everything went fine except admin page missing 2 file [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.css, line 0) [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav_sidebar.js, line 0) -
Django user model custom fields names
How to rename fields of the user model? I want to rename the fields first_name to firstName, last_name to lastName with AbstractUser class User(AbstractUser): email = models.EmailField('email address',unique=True) firstName = models.CharField("First Name", max_length=150) lastName = models.CharField("Last Name", max_length=150) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'username', 'firstName', 'lastName', ] The above code works, but it does not rename the fields what it does is add the fields firstName and lastName Any ideas or suggestions? -
how to create enable registered users to create their own staff user in django
How to enable registered users on my website to create their own staff users ? Their staff user should be able to login in registered users dashboard . I am very new to coding so please help , how should i move forward ? -
React - Can't get my Axios to POST to my backend URL? Backend URL's work just fine via tests
I'm testing out a new user registration form. I've used this exact same form set-up for my login page, it works just fine, users can login with their credentials and connect to the backend. However, this time when I try to reflect the same method onto my registration form, I'm getting a forbidden 403 error from django. I've tested out the URL path using Postman and Swagger, they both work fine (without headers). Which is why you see the 201 white response in my terminal above. The 403 only occurs when I try to register via my React Frontend app. Here is my Axios post request: const onSubmit = (data, e) => { console.log(data); axiosInstance .post(`user/register/`, { email: data.email, username: data.username, first_name: data.first_name, last_name: data.last_name, password: data.password, subscribed: data.subscribed, }) .then((res) => { history.push('/login'); console.log(res); console.log(res.data); }); }; Here is the code of my React registration form. export default function SignUp() { const { register, control, errors: fieldsErrors, handleSubmit } = useForm() const history = useHistory(); const initialFormData = Object.freeze({ email: '', username: '', first_name: '', last_name: '', password: '', subscribed: false, }); const [formData, updateFormData] = useState(initialFormData); const handleChange = (e) => { updateFormData({ ...formData, ...e, // Trimming any … -
How can you return a value according to the radio field selected?
I'm making a checkout page with radio selection to choose from stripe and paypal. When the user selects Stripe it should direct to the Stripe checkout and when the user selects Paypal, it should go to the paypal one. HTML: <form method="POST" class="post-form"> {% csrf_token %} <div class="col-md-12"> {% for value, name in form.fields.payment_option.choices %} <div class="radio"> <label><input type="radio" name=paymentMethod id="{{ name.id }}"class="mr-2">{{ name }}</label> </div> {% endfor %} </div> </div> <div class="form-group"> <div class="col-md-12"> <div class="checkbox"> <label><input type="checkbox" value="" class="mr-2"> I have read and accept the terms and conditions</label> </div> </div> </div> {% if name in form.fields.payment_option.choices == stripe %} <button type="submit" class="btn btn-primary py-3 px-4" action="{% url '' %}">Place an order</button> {% endif %} </form> urls.py: urlpatterns = [ path('', views.index, name='index'), path('shop/', views.shop, name="shop"), path('about/', views.about, name="about"), path('blog/', views.blog, name="blog"), path('contact/', views.contact, name="contact"), path('checkout/', views.checkout, name="checkout"), path('cart/', views.cart, name="cart"), path('product-single/<slug:slug>/', views.productpage, name="productpage"), path('add-to-cart/<slug:slug>/', views.add_to_cart, name="addtocart"), path('remove-from-cart/<slug:slug>/', views.remove_from_cart, name="removefromcart"), path('payment/<payment_option>/', PaymentView.as_view(), name='payment') ] -
Django, google app engine, bucket No 'Access-Control-Allow-Origin'
Hello i've a problem that i can't solve. Now i've a simple django project and i'm close to finishing. a few days ago i upload my static files and media files to google cloud sql-bucket. Normally everything was fine for media files but when i upload static files something started to happens. Here some of error messages(30+): Access to script at 'https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://storage.googleapis.com/denka_metal_static_bucket/debug_toolbar/js/toolbar.js net::ERR_FAILED Access to font at 'https://storage.googleapis.com/denka_metal_static_bucket/Fonts/jost/Jost-500-Medium.woff2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Also normally django wasn't accept my static files because of they are in somewhere else but i loaded django-cors-headers (i don't know is it full name.) and django accept most of css docs. Here is my settings.py (I cut some parts when i paste here): ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'honeypot', 'ckeditor', 'ckeditor_uploader', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'Product.apps.ProductConfig', 'captcha', 'admin_honeypot', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ( 'http://127.0.0.1:8000', 'http://localhost:8000', 'https://storage.googleapis.com', 'https://googleapis.com', ) CSRF_TRUSTED_ORIGINS = [ … -
Class based views
I'm experimenting with class based views as I've not worked with them yet. I'm also pretty new to Django. I'm having trouble correctly using slug or pk and setting up my URL's in my products app. My Project level urls.py: from django.conf import settings from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls', namespace='home')), path('products/', include('products.urls')), path('checkout/', include('checkout.urls')), ] urls.py(product app): from django.urls import path from .views import ItemDetailView urlpatterns = [ path('', ItemDetailView.as_view(), name='products'), ] views.py(products app): from django.shortcuts import render from django.views.generic import DetailView from home.models import Item def products(request): context = { 'items': Item.objects.all() } return render(request, "products/products.html", context) class ItemDetailView(DetailView): model = Item template_name = "products/product.html" I have tried adding <slug>/ to the products url pattern but that doesn't work. I'm pretty sure I need to adjust my url's but I'm not sure how. -
don't show checkbox type boolean on models.py
i have models item filed itm_stop: class item(models.Model): itm_stop=models.BooleanField(verbose_name='item stop',default=False) in file forms.py: from django import forms,modelsForm class itemsForm(modelsForm.Form): class Meta: model =item fields = "__all__" in file views.py : from .forms import itemsForm def items_create(request): if request.method == 'POST': form = itemsForm(request.POST, request.FILES) else: form = itemsForm() return render(request, 'items/items.html',{"items" :form}) in file Templates item.html: {% load widget_tweaks %} {% for field in items %} <!-- append to an attribute --> <div class="form-group{% if field.errors %} has-error{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} When I do the presentation, I cannot display the checkbox, and it appears as an empty box on the page, and I did not find the reason for that -
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 !