Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How can I fix errors in django data base?
when I went to the 2nd part of the django tutorial, I saw a bug in the shell. when I reach the end of the first part of the shell and write Question.objects.all (), and then the shell responds to all commands <QuerySet [<Question: Question object (1)>]> because of this my site does not work -
ProgrammingError at / relation "home_sitesetting" does not exist LINE 1: ...ation", "home_sitesetting"."news_pagination" FROM "home_site
my project currectly run on local host But when I try to run it on the server, I get an error. On the server command line, I also get this error when executing the Migrate command: django.db.utils.ProgrammingError: relation "home_sitesetting" does not exist LINE 1: ...ation", "home_sitesetting"."news_pagination" FROM "home_site... my model: from distutils.command.upload import upload from tabnanny import verbose from django.db import models from django.core.validators import MaxValueValidator from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class SingletonBaseModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super().save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj class SiteSetting(SingletonBaseModel): site_title = models.CharField(max_length=250, verbose_name="عنوان سایت") about_us = RichTextUploadingField(verbose_name="متن درباره ما", blank =True, null= True) about_us_img = models.ImageField(upload_to='site/setting', verbose_name='تصویر صفحه درباره ما') contact_us = RichTextUploadingField(verbose_name="متن صفحه ارتباط با ما", blank =True, null= True) contact_us_img = models.ImageField(upload_to='site/setting',null= True, verbose_name='تصویر صفحه ارتباط با ما') phone = models.CharField(null=True, blank=False, max_length=12) address = models.TextField(verbose_name="آدرس", null=True) email = models.EmailField(verbose_name='ایمیل', max_length=100) instagram = models.URLField(max_length=200, verbose_name='آدرس اینستاگرام', null=True) telegram = models.URLField(max_length=200, verbose_name='آدرس کانال تلگرام', null=True) fb = models.URLField(max_length=200, verbose_name='آدرس فیس بوک', null=True) twitter = models.URLField(max_length=200, verbose_name='آدرس توییتر', null=True) youtube = models.URLField(max_length=200, verbose_name='آدرس یوتیوب', null=True) linkedin = models.URLField(max_length=200, verbose_name='آدرس لینکدین', null=True) whtasapp … -
django blog like button not showing up
am making a django blog and writen some like code but cant seem to get it to work. Any ideas how to get my like button to work? Any help would be appreciated! First error code i get is: newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('posts:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() … -
Django orm is creating a copy of instance instead of accessing it
I have I think kind of a tricky question in Django and it's orm. This does not work : cartitemproduct_in_cart_session.get().quantity+=1 cartitemproduct_in_cart_session.get().save() If I check just after that the value of cartitemproduct_in_cart_session.get().quantity, it wasn't updated This works : cartitem_session=cartitemproduct_in_cart_session.get() cartitem_session.quantity+=1 cartitem_session.save() The value was updated But why ? (cartitemproduct_in_cart_session is a queryset, result of a filter, but I think it doesn't matter : cartitemproduct_in_cart_session=cart_session.cartitem_set.filter(product__slug=cartitem.product.slug) ) I am guessing that somehow, when I do cartitemproduct_in_cart_session.get().quantity, the field quantity becomes a new attributes of cartitemproduct_in_cart_session.get() and isn't linked anymore to the field in the database, but I don't understand why ... Why do you need to first assign an instance of a model to a name, in order to update the fields of that instance ? -
How to make the test take an existing coin_id?
My code It is necessary that the test itself could substitute the existing coin_id, so that in the future the test does not fall, for example, due to the removal of a coin under id=2 class ModelTransactionTest(TestCase): @freeze_time(timezone.now()) def test_auto_setting_date_if_field_empty(self): field = Transaction.objects.create(rubles_cost=1, purchase_price=1, amount=1, dollars_cost=1, coin_id=2) self.assertEqual(timezone.now(), field.date) -
Omit __str__ of model in TabularInLine
I am using a TabularInLine to display a list of models, however each entry also displays the __str__ method of this model, and I was wondering how I can remove this. According to this answer I need to change the CSS file used in the admin interface, but this answer is over 10 years old so I'm not sure if that is still the best way of doing this. -
Django form - use different pre defined date ranges for different choices
I have a Django form where the user can select a variable in a choice field, start date and end date in a select date widget. For different variables, the possible start and end dates varies. The form works, but only with one pre-defined date range for all variables. How can I change the possible start and end dates according to the variable? from django import forms from datetime import datetime Parameter_CHOICES = [ ('', 'Wähle ein Umweltvariable'), ('niederschlag', 'Niederschlag [L/m²]'), ('bodentemperatur_5cm', 'Bodentemperatur in 5cm Tiefe [°C]') ] class DataForm(forms.Form): parameter = forms.ChoiceField( widget=forms.Select, choices=Parameter_CHOICES) start_date = forms.DateField(label='Beginn:', widget=forms.SelectDateWidget(years=list(range(2007,2023)))) end_date = forms.DateField(label='Ende:', initial=datetime.now, widget=forms.SelectDateWidget(years=list(range(2007,2023)))) Is it possible to do this in the forms.py or do I have to make this in javascript/html? -
store an object in django
i use react to get all the data of a table and that data is stored into a single variable called res. i want to store that data into another table and in a single row of django. const [data,setData]=useState(""); const put=async()=>{ const res=await Axios.get("http://127.0.0.1:8000/api/getdata"); console.log(res.data); setData(res.data); } function set(){ console.log(data); const a={ abc:data } Axios.post("http://127.0.0.1:8000/api/test",a).then((res)=>alert(res.data)); }