Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FieldError: Unsupported lookup for CharField or join on the field not permitted on Django
Why do I get this error: FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted? Info Language: Python Platform: Django Database: PostgreSQL Code View: def search(request): query = request.GET.get("query") searched = Book.objects.filter(title__unaccent__icontains=query) # Error here return render(request, "main/search.html", { "query": query, "searched": searched, }) Expected output Unaccent the query and search for the unaccented version in the database. Description I get the error FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted when I try to query the database using __unaccent while using the advanced search features mentioned in the django docs. -
PermissionDenied return to home
For my blog on all the relevant views such as delete and update I have this if request.user.id != post.author_id: raise PermissionDenied() This is working as expected however it just sends the user to a page that says 403 forbidden. I would rather just redirect the user to the homepage. Would it be insecure or poor practice to do something like return HttpResponseRedirect('/') or is it fine as is and I am overthinking it -
item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'
Good afternoon, I'm writing a store on django, but the following problem occurred when going to the shopping cart page: item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'. The error itself lies in cart.py , and it seems simple, but I do not know how to solve it. Forms.py: PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py from django.shortcuts import redirect, get_object_or_404, render from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart … -
How to pass django context values to the javascript variable?
I want to pass all the values of the {{ i.nsn }} turn by turn to the ajax script. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} If I tried the ajax script in the way {% for i in dibbs %} <script> var nsn = {{ i.nsn }} console.log("Hello") $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://localhost:8000/toggle/"+nsn, contentType: 'application/json', success: function (data) { appendData(data); function appendData(data) { var mainContainer = document.getElementById("switch_{{forloop.counter}}"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ; mainContainer.appendChild(div); } } } }); }); </script> {% endfor %} The ajax script also repeats as per the loop. My url is different for every nsn. I want to send a single ajax request when I clicked in the button. I want to execute a single ajax function for a single click removing the for loop. -
How to get the ID of the record created in the model after saving it from a Form
Let's say I submit a form to the back-end and I save a record of the model in the following way: views.py: def viewName(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() #I want to get the id of this after it is saved else: print (form.errors) form = ProjectForm() return render(request, 'index.html', context) forms.py: class ProjectForm(ModelForm): class Meta: model = Project fields = '__all__' Right after saving the form, I would like to get the id of the record for the model. I tried with form.id and form.pk as I saw in other similar questions without success. How can I get the id or the pk of the new entry added to the Project model? -
How to write a search in django backend side search?
class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) email_verified = models.BooleanField(default=False, blank=True) phone = models.CharField(max_length=200) phone_verified = models.BooleanField(default=False, blank=True) company_id = models.ImageField(upload_to=get_file_path_id_card, null=True, max_length=255) company_id_verified = models.BooleanField(default=False, blank=True) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name This is my moodel i want to serch using name and phone number. -
How to host Django website on oracle cloud virtual machine?
I am trying to host a Django Project on Oracle cloud virtual machine running Ubuntu. As I am not too experienced with virtual machines, I was following along with this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 What I have succeeded in doing so far is to create postgresql database and starting django project and connecting the database to the django project, and applying migrations. However, as per the tutorial, I run python manage.py runserver 0.0.0.0:8000 and it appears that the website has been deployed, but upon entering public ip into browser, it says could not connect to the ip. Any help? I have added ingress rules 8000/udp and 8000/tcp into the subnet but still no luck -
Django Custom Password Reset Form widget not working
Stumped as to why my template isn't showing my custom password reset form. Here is code: forms.py class CustomPasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): super(CustomPasswordResetForm, self).__init__(*args, **kwargs) email = forms.EmailField( label='', widget=forms.EmailInput(attrs={ 'placeholder': 'placetest@test.com', 'class': 'form-field', })) Views.py class PasswordResetView(auth_views.PasswordResetView): form_class = CustomPasswordResetForm template_name = 'password_reset.html' urls.py urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('password_reset', PasswordResetView.as_view(), name='password_reset'), path('login_success/', login_success, name='login_success'),] Template {% load static %} {% block title %}Home{% endblock %} {% block content %} <div class="form-container" id="pwrest"> <div class="form-title"> <h2>Enter your email address</h2> </div> <form method="POST"> {% csrf_token %} <p>email</p> <div>{{ form.email }}</div> <input class="submit-button" type="submit" value="Send me instructions!"> </form> </div> </div> {% endblock %} CSS .form-field{ width: 300px; height:30px; margin-bottom:5px; margin-top:5px; border:none; border-radius: 5px; background-color:whitesmoke; } When I view the template in my browser, I am seeing the form field as the default, its almost like its just not recognizing the CSS class. I'm not sure what I've missed. Thank you. -
Change date time format after AJAX call in Django
I have the following Datatable: $('#table').DataTable( { responsive: true, autowidth: false, destroy: true, deferRender: true, ajax: { url: '/ajax_view/', type: 'GET', data: {}, dataSrc: "" }, columns: [ {"data": "fields.filename"}, {"data": "fields.uploaded"}, {"data": "fields.updated"}, {"data": "fields.user"}, {"data": "pk"}, ], columnDefs: [ { className: 'text-center', targets: [1] }, { targets: [0], class: 'text-center', orderable: true, render: function (data, type, row) { var filename = data.replace(/^[^/]*\//,''); var buttons = '<a class="file-links" href="/media/'+data+'" target="_blank">'+filename+'</a>'; return buttons; } }, { targets: [-1], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<button type="button" value="'+data+'" class="btn btn-danger fileId"><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="white" class="bi bi-trash-fill" viewBox="0 0 16 16"><path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/></svg></button>'; return buttons; } }, ], order: [ [0, 'asc'] ], "pagingType": "numbers", dom: 'rtp' … -
Flask & MySQL connector in Python
I am using MySQL in a Python written backend without an ORM. I have a bunch of classes that provide database access services using mysqlconnector and these services may be used by the same or different API routes. They are provided as member functions using a single MySQLConnection and MySQLCursor object that is initialized in a constructor and then passed around. Is it possible to make this thread-safe without altering the design too much i.e. without requiring opening a new connection for every member function that accesses the database? -
Python Azure SDK - Incorrect datetime format inferred when reading tabular data from blobstore with from_delimited_files()
I am using the Azure Python SDK to read a tabular dataset from a Blob Store as follows: df = Dataset.Tabular.from_delimited_files(path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True) The data has four datetime columns, one of the columns reads in with no problem because there are instances where the month-day order is not ambiguous, but the other three are being inferred incorrectly as "month-day" instead of "day-month". When reading in the data I get the following warning: UserWarning: Ambiguous datetime formats inferred for columns ['Period Start', 'Period End', 'Extracted At'] are resolved as "month-day". Desired format can be specified by set_column_types. I have attempted to set the column types as below, and have tried a few different formats but all I end up with is NULL in place of all the values. df = Dataset.Tabular.from_delimited_files( path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True, set_column_types={'Period Start': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Period End': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Extracted At': DataType.to_datetime("%d-%m-%Y %H:%M:%S")}) The documentation for from_delimited_files() is here Can anyone tell me how to force from_delimited_files() to resolve the ambiguous datetimes as day-month or tell me how to use set_column_types correctly? I've worked around it temporarily by inserting a dummy row with a non-ambiguous datetime. -
Files in media directory being routed through the dynamic link gets blocked
I have a dynamic link which i declared in django urls.py as this url(r'^(?P<user_name>[a-zA-Z0-9]+)', views.dynamic_link, name="user_details"), But all the media files is not been shown in the web pages of this dynamic link although the url of those files where correct whereas all files in the static folder is been shown. I called the media file through <img src="{% get_media_prefix %}{{list.picture}}" alt="this is alt {{img}}"> This is a sample of the link of the media and static file url in the web page code /static/css/bootstrap.css /media/images/byron_cream.jpg When I tried to view images, css etc from my static folder directly from inside the browser the browser displayed the images, css etc but doing the same thing with the media files the browser was not showing up but sending page to show the url does not exist(which i created for non existing url ). On further test I saw that the url of the media file was passing through the def dynamic_link function unlike that of the static files In other to ensure that a url which exist in my database is what is being called I have written my views function to check that any url which is passed thrugh the … -
Helpdesk ticketing system for IT - opening ticket by receiving email from the customer?
I have started to learn django, and I have build a helpdesk ticketing system, right now the tickets can only be opened by admin and I want the customer to open the ticket automatically by sending email to a specific email address, I know what am asking is broad but any advise on what tools are needed to achieve this would be highly appreciated. -
values_list query is returning the foreign keys pk rather than it's value
I am trying to get all the categories currently used in Recipes without any duplicates, by querying CategoryToRecipe. class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name class CategoryToRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) query_set = CategoryToRecipe.objects.values_list('name', flat=True).distinct() query_set is returning numbers, which I assume are the ID for Category, not the name (e.g. Lunch, Dinner, etc.). How do I get the actual name string of Category? -
Unused space in sqlite
I ran sqlite3_analyzer in order to try to understand why a database consumes much more disk space than expected, even after using VACUUM. The output shows that there are many tables with extra pages used for seemingly no reason. Here is an example: *** Table ACCOUNT_EMAILCONFIRMATION and all its indices *********************** Percentage of total database...................... 2.6% Number of entries................................. 0 Bytes of storage consumed......................... 12288 Bytes of payload.................................. 0 0.0% Bytes of metadata................................. 24 0.20% Average payload per entry......................... 0.0 Average unused bytes per entry.................... 0.0 Average metadata per entry........................ 0.0 Maximum payload per entry......................... 0 Entries that use overflow......................... 0 Primary pages used................................ 3 Overflow pages used............................... 0 Total pages used.................................. 3 Unused bytes on primary pages..................... 12264 99.80% Unused bytes on overflow pages.................... 0 Unused bytes on all pages......................... 12264 99.80% Here, three pages, each 4,096 bytes are used to store zero entries. The result is that a tiny database takes hundreds of KB. This makes me suspect that the database size might quickly explode when I put my Django website into production. So, why does this happen? -
Django registration form exceeds username length. [error]
I have a custom user model that has a username field with a max_length=50. Under the custom registration form, it throws me an error when the value of the username` field is just less than 10 characters: Ensure this value has at most 50 characters (it has 170). Below are the codes that I used that is in correlation with the username field: #models.py class UserAccount(AbstractBaseUser, PermissionsMixin): username = models.CharField(null=False, blank=False, max_length=50, unique=True) #forms.py class RegisterForm(UserCreationForm): username = forms.CharField(widget=TextInput( attrs={ "class": "form-control", "id": "username", #"placeholder": "Username", })) class Meta: model = UserAccount fields = ('username',) def clean_username(self): username = self.cleaned_data.get("username") username_filter = UserAccount.objects.filter(username__iexact=username) if username_filter.exists(): self.add_error('username', "Username is already taken") return self.cleaned_data HTML <div class="row form-group"> <div class="col-sm-4 label-column"> <label class="col-form-label" for="username-input-field">Username </label> </div> <div class="col-sm-6 input-column">{{register_form.username}}</div> </div> The error only occurs when I use the registration form on the html when creating a user, but when I create the user via python manage.py shell and admin panel, it gets created without any error. -
Django why I can't access objects of another model via foreignkey?
I have two model Doctor and UserProfile. I want to access UserProfile model objects via foreignkey. here his my code: models.py class Doctor(models.Model): docter_id_num = models.CharField(blank=True,null=True,max_length=100) doctor_name = models.CharField(max_length=100) slug = models.SlugField(max_length=255,unique=True,blank=True,null=True) class UserProfile(models.Model): acess_doctor_model = models.ForeignKey('hospital.Doctor', on_delete=models.CASCADE,blank=True,null=True,related_name="acess_doctor_model") ....my others model fields Now I need to access UserProfile model from my views fuction. here is my views.py def EditDoctor(request,slug=None): obj = get_object_or_404(Doctor,slug=slug) user_profile = UserProfile.objects.filter(acess_doctor_model=obj) print(user_profile) here is my perint result for user_profile : <QuerySet [<UserProfile: None>]> here is my print result for obj: Doctor_id: DCKMC3G0-----Doctor Name: HARTHO Why I can't get access userprofile model via this queryset: UserProfile.objects.filter(acess_doctor_model=obj) -
Different permissions for different methods in action decorator view?
I have an action decorator in a ViewSet that accepts two methods: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer = DefaultItemSerializer @action(detail=True, method=["get", "post"], permission_classes=[AllowAny]) def custom_action(self, request, pk): qs = self.get_object() if request.method == "GET": return Response(CustomItemSerializer(qs).data, status=200) else: serializer = CustomItemSerializer(qs, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.data, status=400) Currently both get and post have the same permission of AllowAny. What if I want them to be different? E.g. get to be AllowAny while post should only be IsAdminUser -
Why is Django forms fields value not rendering in html template for function based update view?
The issue is when i try to update my profile, i do not see the exising value i do not actually know what is wrong with the views.. views.py def profile_update(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() profile = get_object_or_404(Profile, user=request.user) Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=profile) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile', profile.user.username) else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Why Djano forms fields value not rendering in html template for function based update view?
This is my update views: def EditDoctor(request,slug=None): if request.method == "POST": obj = get_object_or_404(Doctor,slug=slug) form = DoctorUpdateFrom(request.POST,instance=obj) if form.is_valid(): form.save() return redirect('hospital:all-doctor') else: form = DoctorUpdateFrom() context = {'doctor_form':form} return render (request,'hospital/edit-doctor.html', context) The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms. -
Create new object Program and related objects Segments using data from another database and user provided fields
I am reading entries from an outside database using get_context_data and displaying them in a list. When user choses an entry - you get a form which displays the chosen entry's data via context. I want to create a model object based on what the user entered, and also create the related object(s) using the context data displayed on the form (not editable information). For example: You have a list of shows from the last month: Show-Dec-31 Show-Dec-30 Show-Dec-29 . . Show-Dec-1 When you choose a show (say Show-Dec-25): You get a form with Name: Show-Dec-25 - User can change this if they want Producer: _______ (required) Editor: ________ (required) Air Time: __:__:__ (required) Run Time: __:__:__ (required) Segments: (via context) (Display only) 1 Intro 00:01:00 2 Monologue 00:01:00 3 Dance Skit 00:09:00 4 Comedy Skit 00:09:00 Create Button Here When the user hits create - it creates a new Program in form_valid by saying: def form_valid(self, form): new_program = Program() new_program.title = form.name new_program.producer = form.producer new_program.editor = form.editor new_program.air_time= form.air_time new_program.run_time= form.run_time new_program.save() The segments need to be created - based off of the just created new_program id. So if new_program id after creation was 44 - then … -
Django Attach variables from one step to another
How would I grab the 2nd form and add it to the first form and save it in another model that looks the same as the custom user. etc username,password,email,first_name,last_name,verified Would I need to add another model? With a similar signup form? I would like another table that's not capable of logging in until the admins adds it to the abstractuser table. So adding users will also need to check if there are values in the new table. views.py from django.core.files.storage import FileSystemStorage import os from django.conf import settings class DoctorWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor')) template_name = "registration/signup.html" form_list = [SignUpForm,verify] def done(self, form_list, **kwargs): data=process_data(form_list) return redirect('home') class UserWizard(SessionWizardView): template_name = "registration/signup.html" form_list = [ SignUpForm] def done(self, form_list, **kwargs): data=process_data(form_list) form_list[0].save() userCreate = form_list[0] username = userCreate.cleaned_data.get('username') raw_password = userCreate.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(self.request, user) return redirect('home') forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class verify(forms.Form): verified = forms.ImageField(required=True) class Meta: model = Profile fields = ('verified',) models.py class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True) phone_number = PhoneNumberField(max_length=25, region="US") … -
VACUUM is not reducing the database size
I am using an sqlite database with Django. The db.sqlite3 file is currently 600KB, while the database is really small, so I think it should fit in just a few KB. After deleting some more rows, I executed: sqlite3 db.sqlite3 "VACUUM;" However, the file did not become a single byte smaller. The environment is the console of pythonanywhere. What am I missing? -
Selective loading of values to populate the ModelViewSet form / Phyton Django RestFramework
I admit I'm new to the Python world. I would like to add some loading moments while I compile the form of the Rest Framework ModelViewSet, in order to make the insertion of data in the forms more agile. below also 2 screens of the form generated by the Framework and a screen of the models, I think I'm working well, I made them in ForeingKeys Is it possible to make such customizations in the Rest Framework views? Rest Framework View Screenshot Django Models -
How extract array values and save to variable? Python
I dont understand how this line of code works in the function below. Mainly what I am asking is how is this line capturing any data? What is this method of capturing data called? Problem line below? self.cart[product_id]['quantity'] = quantity Full function below? def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save()