Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The view books.views.save didn't return an HttpResponse object. It returned None instead
i am trying to create a function to save favourite post to users profile, this is working fine in the database it adds and removes the favourite post but when the view is called it shows this error The view books.views.save didn't return an HttpResponse object. It returned None instead. views.py def save(request, book_slug): user = request.user book = Book.objects.get(slug=book_slug) post = get_object_or_404(Book, slug=request.POST.get('post_slug')) profile = Profile.objects.get(user=user) is_saved = False if profile.favourite_book.filter(slug=book_slug).exists(): profile.favourite_book.remove(post) is_saved = False else: profile.favourite_book.add(post) is_saved = True context = { 'book':book, 'post':post, 'is_saved':is_saved, } if request.is_ajax(): html = render_to_string('books/save_section.html', context, request=request) return JsonResponse({'form': html}) -
Why is fileChoice.value() None?
I am working in Django 3.2.13 trying to create a simple upload form for a file model with a chained foreign key. I have tried creating a form with a basic form model and a ModelForm, however, even when checking request.FILES there is no data and request_file = request.FILES['document'] if 'document' in request.FILES else Noneyields None. views.py def home(request): if handleAuth(request) is not None: return handleAuth(request) user = request.user if request.method == "POST": # if the post request has a file under the input name 'document', then save the file. form = FileSubmissionForm(user, request.POST, request.FILES) #print(request.FILES) #request_file = request.FILES['document'] if 'document' in request.FILES else None #if request_file: form.save() #else: # print("NO FILE") userFiles = [] if user.is_company_admin: temp = StorageFile.objects.filter(company_key=user.company_key) else: temp = StorageFile.objects.filter(company_key=user.company_key, profile__in=user.user_profiles.all()) temp.order_by("profile") for file in temp: userFiles.append({"name": file.getFileName(), "path": file.getMediaPath()}) form = FileSubmissionForm(user) return render(request=request, template_name="fileCloudApp/home.html", context={"userHasAdmin": user.is_company_admin, "files": userFiles, "form": form}) forms.py from django import forms from fileCloudApp.models import StorageFile from loginApp.models import UserProfile class FileSubmissionForm(forms.Form): fileChoice = forms.FileField() profileChoice = forms.ModelChoiceField(queryset=UserProfile.objects.none(), label="Choose profile") def __init__(self, user, *args, **kwargs): super(FileSubmissionForm, self).__init__(*args, **kwargs) if user.is_company_admin: temp = UserProfile.objects.filter(company_key=user.company_key) else: temp = user.user_profiles.all() temp.order_by("label") self.fields["profileChoice"].queryset = temp self.user = user def save(self): print(self["fileChoice"].value()) # None pro = … -
Django: The view books.views.save didn't return an HttpResponse object. It returned None instead
i am trying to create a function to save favourite post to users profile, this is working fine in the database it adds and removes the favourite post but when the view is called it shows this error The view books.views.save didn't return an HttpResponse object. It returned None instead. views.py def save(request, book_slug): user = request.user book = Book.objects.get(slug=book_slug) post = get_object_or_404(Book, slug=request.POST.get('post_slug')) profile = Profile.objects.get(user=user) is_saved = False if profile.favourite_book.filter(slug=book_slug).exists(): profile.favourite_book.remove(post) is_saved = False else: profile.favourite_book.add(post) is_saved = True context = { 'book':book, 'post':post, 'is_saved':is_saved, } if request.is_ajax(): html = render_to_string('books/save_section.html', context, request=request) return JsonResponse({'form': html}) -
Django custom User Model : I can't assign a user to a group in admin panel
I have created a custom User Model in my app. But, now, in the administration panel, I can't assign a user to a group or a permission because the right table doesn't appear. I don't find any solution yet, do you have any idea to solve this problem ? thanks SCREENS TO UNDERSTAND : without custom user model : see image now, with the custom user model, the right table is not : see image CODE : admin.py class UserAdmin(admin.ModelAdmin): list_display = ('username', 'email') search_fields = ('username',) fieldsets = ( (None, { 'classes': ['wide'], 'fields': ('username', 'password') }), ('Informations personnelles', { 'classes': ['wide'], 'fields': ('first_name', 'last_name', 'email', 'avatar') }), ('Permissions', { 'classes': ['wide'], 'fields': ('is_superuser', 'is_staff', 'is_active', 'groups', 'permissions') }), ('Dates importantes', { 'classes': ['wide'], 'fields': ('last_login', 'date_joined') }), ) models.py class User(AbstractUser): signup_token = models.UUIDField(primary_key=False, unique=True, verbose_name="jeton d'inscription", null=True, blank=True) avatar = CloudinaryField('image', blank=True, null=True) -
Error when importing django fixture with natural key
In context of a django project, I want to create some sample data in forme of a fixture. I have export my data with natural key to avoid any data overnight at the import but I'm not able to import data at all. The fixture has been created with the following command : python manage.py dumpdata --format yaml --natural-primary --natural-foreign conformity.policy conformity.measure > conformity/fixture/NIST.yaml I have tried to import the fixture with the following command : python manage.py loaddata conformity/fixture/NIST.yaml but I have the following error django.core.serializers.base.DeserializationError: Problem installing fixture 'conformity/fixture/NIST.yaml': ['“NIST Cybersecurity Framwork” value must be an integer.']: (conformity.measure:pk=None) field_value was 'NIST Cybersecurity Framwork' It seems to me that django don't understand data correctly and try to use natural key directly as a primary key. I haven't found any option to change this behavior. Of course YAML file don’t have any pk for the object to be imported (du to natural key), I was expected Django to automatically generate them. -
upload file with django from model
i created a form to upload a file, and also created a model like this: def get_file_path_order(request, filename): original_file_name = filename nowTime = datetime.datetime.now().strftime('%Y%m%d%H =%M%S') filename = "%s%s" % (nowTime, original_file_name) return os.path.join('services', filename) class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fname = models.CharField(max_length=150, null=False) lname = models.CharField(max_length=150, null=False, blank=False) email = models.CharField(max_length=150, null=False, blank=False) phone = models.CharField(max_length=150, null=False, blank=False) address = models.TextField(null=False) services_file = models.ImageField(upload_to=get_file_path_order, null=True, blank=True) and this is the form: {% if product.is_service == True %} <form method="POST" enctype="multipart/form-data" class="mt-3"> {%csrf_token%} <div class="custom-file"> <label class="custom-file-label" for="customFile">upload file contains all your requirenments and describe your needs</label> <input type="file" class="custom-file-input" name="sfile" id="sfile"> </div> </form> {% endif %} </div> it is working well in the admin panel which created automatically, how can I make it by my own with my form? -
How can I do redirect in DRF and pass data to a client (React JS)?
Backend: DRF Frontend: ReactJS I call a function openGoogleLoginPage if a user clicks on a button that opens a google login page and redirects to a server localhost:8000. const openGoogleLoginPage = useCallback(() => { const urlParams = new URLSearchParams(params).toString(); window.location = `${googleAuthUrl}?${urlParams}`; }); <Button onClick={openGoogleLoginPage}> Integrate Google Calendar </Button> On the server I get some JSON data and then redirect back to the client from django.shortcuts import redirect class GoogleLoginApi(APIView): def get(self, request, *args, **kwargs): data=process(request) response = redirect("http://localhost:3000", args=data) return response So I passed the data to redirect, but how can I get what I passed on the client side? Or maybe there is another way to redirect with a data? Anyway, how can I get it in my react app? -
how to send one section's field id to another section for the output
currently I'm making an 'django' app which has functionality of wizard form, in which I want output from first section of wizard form (which has dropdown list) to last section of the wizard form. To clarify more first section has only one dropdown list (sms, whatsapp, twitter, facebook, instagram, etc..), in second section also dropdown list (which has a department lists which means from which department you want to send...), in third section it should be dynamic and that will be depends on the first section of my wizard. For exaple if i select sms then in 3rd section it should show section which is specifically designed for sms and like wise. So, how should i do that?, if you still don't understand contact- captionamerica1112@gmail.com -
error: TypeError: tuple indices must be integers or slices, not str Overlapping check in Django Forms
Hi I am tring to ceate validation when the values will overlap in tuple but it not working , can anyone help or guide me. record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run') for overlap_check in (i, start_run, end_run, application_run): if overlap_check not in record: record.append(overlap_check) else: raise ValidationError( "overlapping not allowed" ) -
Aggregate/Annotate issue with OuterRef not working with non-FK relationship in Django? Is FK required?
I've got an issue with a couple models from different 'shared apps' that I have. I can't FK them together, because these apps exist in multiple projects (some without each other) so it would break other projects. This is an unmanaged model from appA - which uses a different database which we will call databaseA for this example; in a perfect world 'location_id' would be the FK but as I've described above, it cannot be. class Enrollment(models.Model): id = models.IntegerField(db_column="ID", primary_key=True) location_id = models.IntegerField(db_column="locationID") grade = models.CharField(db_column="grade", max_length=10) student_count = models.IntegerField(db_column="studentCount") class Meta(object): managed = False db_table = "mytable_Enrollments" This is a managed model from appB which uses databaseB (which is the primary database used by the rest of the apps in this project); the 'pk' or 'id' of this model is what is listed in the Enrollment model under location_id class Location(models.Model): name = models.CharField(max_length=50) alternate_name = models.IntegerField() If I want to get Enrollment objects for a Location, I have to explicitly put a number in for the id like so: location = Location.objects.get(id=1) enrollments = Enrollment.objects.filter(location_id = location.id) But I'm trying to annotate the 'total_student_count' onto the Location model like so: enrollments = ( Enrollment.objects.filter(location_id=OuterRef("pk")) .order_by() .values("location_id") ) … -
Default value for JSONField
How to set the default value as {}::jsonb on JSONField in Django framework? Is it possible? default_value=dict without results. In the database, all the time null value is the default. -
django request in render to string template
I used to think, request is global variable that can always be accessed in template. until, I defined a property on model instance, and returns render_to_string template. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def card(self): return render_to_string('common/user_card.html', {'user': self.user}) user_card.html {% if request.user == user %} {% elif request.user in user.profile.follower.all %} <span href="{{ user.pk }}" class="user-follow not-followed">unfollow</span> {% else %} <span href="{{ user.pk }}" class="user-follow followed">follow</span> {% endif %} for the result, request is always None and the conditional always jump to else. the request keyword is not picked up by render_to_string, should it be global in any template since we must have a request to return something? I cannot believe it, in many other template I have things defined like: {{ user.profile.card }} I have no idea on what to do now, is there a way to make request always a keyword in any html template? this is such a bad feature that request is not available in render_to_string template which we cannot check who is requesting the page. -
Django throws an error while trying access registration page
Django throws the following at me while I try to access the signup page.. The view accounts.views.signup_view didn't return an HttpResponse object. It returned None instead. I think everything was done right but apparently django doesn't agree. Signup.html <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup_view(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'signup.html', context) -
i want to learn programming but i don't choose asp.net core or django? [closed]
I want to learn programming as job , but I don't know learn django or asp.net core , and future of what are bright 🤔. I worked with c# and python before, and python is my favorite but I scared to loss my job in future, my friend is senior in .net core and say django is not trustable because a framework and maybe defeat in future (like node), but .net core is supported by Microsoft and it have great feature. Is my friend say right ? I 'm confused 😕, Anybody can help me ?! Thanks. -
Django UniqueConstraint on Distant Model
I have models like this. The basic relationship is that auth.Group can have multiple Projects, and multiple Orders can be associated with each Project. Simplified version: from django.db import models class Project(models.Model): group = models.ForeignKey("auth.Group", on_delete=models.SET_NULL, null=True) class Order(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) external_id = models.CharField(max_length=255) The Orders have external_ids that relate them to another system. Those should be unique at the auth.Group level. I know that I can do this: class Order(models.Model): group = models.ForeignKey("auth.Group", on_delete=models.SET_NULL, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) external_id = models.CharField(max_length=255) class Meta: constraints = ( models.UniqueConstraint( fields=["group", "external_id"], name="unique_external_id_per_group" ), ) But I don't want to replicate the group relationship on the order. I tried this: class Meta: constraints = ( models.UniqueConstraint( fields=["project.group", "external_id"], name="unique_external_id_per_group" ), ) and: class Meta: constraints = ( models.UniqueConstraint( fields=["project__group", "external_id"], name="unique_external_id_per_group" ), ) But I just get 'constraints' refers to the nonexistent field 'project.group'. -
Django: Append json data to Response object
New to Python/Django. I am wanting to conditionally append json data to a Response object if a particular filter is present in my request, all within the same json array. There is also standard information I want to return in every response. For example, I have: filter = request.GET['filter'] response = Response({'services': []}) if filter == 'service1': response.data['services'] = {'service1': service_data.get('service1')} response.data['connectivity'].add|append|something({'base_service_data': service_data.get('base')}) return response I can't seem to find a way of appending to this services array, only assigning and therefore overwriting what was there before. Can this be done? The goal is to allow filter to be a list, and have a number of services appended to services. -
Where Django stores Foreign Keys unique name?
In DB we have something like this articles_article_pro_article_id_9b711a07_fk_articles_ as unique FK name, how can i get this name in runtime through model? -
how many dockerized django instances can i put on one small computer?
I would like to run several django instances in different containers on one server. The server is 1 core CPU, 1 GB Memory / 25 GB Disk / AMS3 - Debian 11 x64. I would like to be able to forecast how many django instance i can run on the same server to serve small trafic website blogs. Do you have any idea or should I try and monitor the cpu load/mem load? In that case, from what treshold of % load should i stop adding instances? Thank you best, -
(django) 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
I am now trying to assign two foreignkey onto the same custom user model, the username & profile image field. Custom User model: class Account(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = "Account List" email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, default="") profile_image = models.ImageField(max_length=255, upload_to=profile_image_path, blank=True, unique=True) about = models.TextField(max_length=255, default='Write something about yourself...', blank=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "name"] def __str__(self): return self.username Thread model: class Thread(models.Model): options = (('active', 'Active'), ('deactivated', 'Deactivated')) username = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='username', related_name='user') profile_image = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='profile_image', related_name='profile') alt = models.TextField(max_length=255, blank=True) image = models.ImageField(max_length=255, upload_to=thread_image_path, default='images/family.png') content = models.TextField(blank=True) created = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=11, choices=options, default='active') However, whenever I try to create a Thread, I always encounter the error: UnicodeDecodeError at /api/public/thread/ 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/api/public/thread/ Django Version: 4.0.4 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte Exception Location: c:\Users\85291\Desktop\vscode\my-app\web\env\lib\site-packages\rest_framework\utils\encoders.py, line 50, in default This error occurred right after I assign the foreignkey to … -
Not able to use dynamic routes with react router and django
I am creating an Online job Reviewing system App using react as frontend and django as backend.I have also used django rest framework to create my own api.The app contains details of all the candidates who have applied and when we click on the candidate it should show the details of that particular candidate on a separate page. I am stuck on how to create dynamic routes using react and django. I thought there was issue of "/" in the urls but I have tried every combination but it just doesn't work. When I go to the url having id of that candidate there's no warning or error in console. urls.py of the API app from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('candidates/', views.getCandidates, name="candidates"), path('candidates/<str:pk>/', views.getCandidate, name="candidate"), path('candidates/add/', views.createCandidate, name="create-candidate"), ] urls.py of the main project urlpatterns = [ path('admin/', admin.site.urls), path('', include('api.urls')) ] App.js code excluding the imports <BrowserRouter> <div className="container dark"> <div className="app"> <Header /> <Routes> <Route path="/" element={<CandidatesListPage />} > <Route path="/candidates/:id" element={<CandidatePage />} /> <Route path="/candidates/add/" element={<CreateCandidate />} /> </Route> </Routes> <Footer /> </div> </div> </BrowserRouter> CandidateListPage(Page) which displays the details of all the candidates and where every … -
Saving files in django mdoels - RuntimeError: Input FileName: <class 'django.core.files.base.File'> is not supported
I am trying to save the following file Here is the model: class someModel(models.Model): someFile = models.FileField(storage=someModule(), blank=True) Here is the saving part: some_file_object = File(some_transformed_file, name=os.path.basename(name)) item = someModel.objects.create(someFile=some_file_object ) I get the error RuntimeError: Input FileName of type: <class 'django.core.files.base.File'> is not supported. When I print some_transformed_file (which is what I am trying to save), I get <_io.BufferedWriter name='fileName.csca'> That file was created the following way: flat_array = array.flatten(order="F") with open(filename, "wb") as f: f.write(struct.pack(">i", 192837465)) f.write(flat_array[i].real) return f -
Django prefetch_related - exclude all empty items from template
I have a class where I am using prefetch_related. I'd like to exclude all empty items in my loops. This is what I tried Area.objects.prefetch_related(Prefetch('category_need', queryset=ProductCategory.objects.filter(need_area__isnull=False), to_attr="need_area__category_need__product")).filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct() However, I am not sure how to create a filter that will exclude all items from Need model that are empty. The same should apply to Area model. If there are no items in Area model then it should not appear. views.py class Search(ListView): template_name = 'product_search.html' model = Product queryset = Product.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(ManualSearch, self).get_context_data(**kwargs) data = Area.objects.prefetch_related('need_area__category_need__product').filter(need_area__category_need__product__isnull=False, need_area__category_need__product__status=1).distinct() context['data'] = data return context models.py class Area(models.Model): title = models.CharField(max_length=75, blank=False) body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField('publish', default=timezone.now) class Need(models.Model): title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters') body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField(default=timezone.now) need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area') class ProductCategory(models.Model): title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters') body = models.TextField(default='-') publish = models.DateTimeField('publish', default=timezone.now) category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True) category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False) category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products') status = models.IntegerField(choices=STATUS, default=0) def get_absolute_url(self): return reverse("product", kwargs={'slug': self.slug}) product_search.html {% for area in data %} <div … -
{% block content %} not working in django
I am learning about template inheritence in django base.html:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>leshav</title> </head> <body> <h1>My helpful timestamp site</h1> { % block content % }{ % endblock % } <footer> <hr> <p>thanks</p> </footer> </body> </html> dateTime.html:- {% extends "base.html" %} {% block content %} <p>today is {{ d|date:'d-m-y' }}.</p> {% endblock %} view for the function related to this page's url:- def current_datetime_block(request): now = datetime.datetime.now() return render(request, "dateTime.html",{'d':now}) the problem is that it is not reading the content in the dateTime.html and is returning base.html file as it is output:- My helpful timestamp site { % block content % }{ % endblock % } thanks This is the output when I run the server where the problem is coming? please help me if anything else about the program is needed, you can ask me about it -
Bash command lines in "Django" views.py file during production stage
I'm working on a project, where I'm using bash command lines in views.py to start a program (https://github.com/cleardusk/3DDFA), which creates files. I use this ugly line: os.system('cd ../cleardusk/3DDFA\npython main.py -f ../../django_project/media/'+filen+'\ncd ../../django_project/') For clarity: cd ../cleardusk/3DDFA python main.py -f ../../django_project/media/'+filen cd ../../django_project/ Where variable "filen" is my filename of an uploaded photo. Everything was working fine, when it was in development stage, but since I transfered my project on a server, this no longer works. At first I thought, I was having problems with virtual environments or ownership of the files or even permissions, but that was not the case. The "cleardusk 3ddfa" probably isn't called, because it does not generate new files. I have searched for an answer, but it seems, no one is using bash command lines in views.py. I have to use bash, since it's only way to run "cleardusk 3ddfa" and I have to run it in views.py since in my project client uploads a photo and filename is there, which I use to call this program. Apache Error log says: cant cd to cleardusk Note, I'm new to "Apache" and all production stage stuff. Is there a problem with Apache configuration or what? Any ideas … -
Bank ATM ledger in Django - - deposit, withdrawal, balance
I’m trying to build a rudimentary interactive ATM machine ledger prototype demo in Python with Django. Here is what my web app currently looks like. The intended basic functionality I am trying to create right now is to have the web visitor (banking client) enter the amount of cash in the input field and then click: “Deposit” or ”Withdraw”. Say for example the client deposits $20.00, the amount should appear in the HTML table under the “Credits” column and the “Running Balance” column should reflect that as well, like anyone would expect a typical ATM and accounting ledger to behave. The end goal is to have unique timestamps and transaction IDs to generate with each transaction, but for now I am focused on just getting the ‘running balance’ variable (rightmost column) to update when the web visitor inputs an amount and clicks “Deposit”. Currently, when a web visitor enters $20.00 as the amount in the box and then clicks “Deposit”, since I’ve got a print statement inside my views.py, the Django terminal shows: <QueryDict: {'csrfmiddlewaretoken': ‘<redacted>'], 'amount': ['20.00'], 'transaction': ['Deposit']}>. So an amount is being accepted and processed. But the Running Balance remains $0.00, which is what I am trying …