Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Compare List With Another Model Attribute Fields
Need help trying to compare a list with the attribute fields of a model class and then save an instance of the object with the compared list values. class College(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=100) college = models.ForeignKey(College, on_delete=models.CASCADE) def __str__(self): return self.name class Semester(models.Model): name = models.CharField(max_length=100) math = models.IntegerField(null=True, blank=True) compsci = models.IntegerField(null=True, blank=True) english = models.IntegerField(null=True, blank=True) athletics = models.IntegerField(null=True, blank=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) college = models.ForeignKey(College, blank=False, on_delete=models.CASCADE) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=100) college = models.ForeignKey(College, on_delete=models.CASCADE) def __str__(self): return self.name from app.models import * Class.objects.all() <QuerySet [<Class: COMPSCI_1010>, <Class: MATH_2010>, <Class: ENGLISH_2200>, <Class: COMPSCI_1100>]> How do I copmare the queryset list to the attributes of the semester class? I have been able to come up with something like this: But it's not dynamic. def createSemester math = None compsci = None english = None m = 0 c = 0 e = 0 for item in a: if 'math' in item['name'].lower(): math = m+1 elif 'compsci' in item['name'].lower(): compsci = c+1 elif 'english' in item['name'].lower(): english = e+1 s = Semester(name=student + "-First Semester", math=math, compsci=compsci, english=english, student=student, college=student.college) s.save() forgive me please … -
Record specific user data in django
I was developing a django project.i want to build a kind of system like when users hit a specific button their primary key,name,other properties get recorded in my database.And those who do not smash button,their properties wont be recorded on the table.I have completed login-logout system and account registration and authentication for users successfully.How can i procceed next?what changes i have to bring to my models.py or views.py files?kindly help me. -
how do solv thes problem (main_gategory and sub_gategory) django3
Please help me to solve this problemو I want to show sub-products on the ads page but this error appears to me These are pictures of a problem and code These models about main-gategory and sub_gategory. from django.db import models from django.contrib.auth.models import User # Create your models here. AD_CONDITION =( ('New','New'), ('Like New','Like New'), ('Good Condition','Good Condition'), ('Bad Condition','Bad Condition'), ) class Ad(models.Model): code = models.CharField(max_length=12,null=True, blank=True) owner = models.ForeignKey(User,related_name='ad_owner', on_delete=models.CASCADE) name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='ad/') content = models.TextField(blank=True, null=0) category = models.ForeignKey('Category',limit_choices_to={'main_category__isnull':True},related_name='ad_category', on_delete=models.CASCADE) price = models.IntegerField(default=1) condition = models.CharField(max_length=15,null=True, blank=True) brand = models.ForeignKey('Brand',related_name='add_brand',null=True, blank=True, on_delete=models.CASCADE) views_count = models.IntegerField(default=0) def __str__(self): return self.name def save(self, *args, **kwargs): self.code = '##'+((str(self.id)).center(10,'0')) super(Ad,self).save(*args, **kwargs) class AdImages(models.Model): ad =models.ForeignKey(Ad, related_name="ad_images", on_delete=models.CASCADE) image = models.ImageField(upload_to='ad_images/') class Category(models.Model): name = models.CharField(max_length=50) main_category = models.ForeignKey('self',limit_choices_to={'main_category__isnull':None},related_name='maincategory', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name -
How to properly validate date field in Django forms?
I am very new to Django forms and I'm trying to make a very simple form to select a from and to dates to filter out some data. I don't wan't the to date to be later than today's date. I'm having a hard time understanding why when clean_to_date fails i.e., the to date is later than Today, the cleaned_data dict only has a from_data. class DateSelect(forms.Form): from_date = forms.DateTimeField( label='From:', input_formats=['%d/%m/%Y'], required=False) to_date = forms.DateTimeField( label='To:', input_formats=['%d/%m/%Y'], required=False) def clean_to_date(self): data = self.cleaned_data['to_date'] if data != None and data > datetime.today(): raise forms.ValidationError( """ \'to\' date cannot be later than today. """) This is my piece of code in the html template so when I hit OK I just want it to refresh and display the filtered data but also sometimes the pages refresh and the form is not displayed, just the OK button. I can't seem to find the problem. <form action="/admin/report/latest-uploads/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="OK"> </form> BTW, I have read already Django's documentation on Form and field validations but I'm still a bit confused. -
UNIQUE constraint failed: memberships_usermembership.user_id
I'm trying to put together a subscription service, and at the moment it's working, but my DB is having issues storing the information in the form in the DB assosciate with the user. Here's my models.py - from django.db.models.signals import post_save from django.conf import settings from django.db import models import stripe from django_countries.fields import CountryField stripe.api_key = settings.STRIPE_SECRET_KEY MEMBERSHIP_CHOICES = ( ('Regular', 'reg'), ('Premium', 'prem'), ('Free', 'free'), ) # Membership type View for DB admin class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) price = models.IntegerField(default=15) description = models.TextField(default="DESCRIPTION") image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) full_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) phone_number = models.CharField(max_length=20, null=True, blank=True) country = CountryField(blank_label='Country', default="Ireland") postcode = models.CharField(max_length=20, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=True, blank=True) street_address1 = models.CharField(max_length=80, null=True, blank=True) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=80, null=True, blank=True) def __str__(self): return self.user.username def post_save_usermembership_create( sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '': new_customer_id = stripe.Customer.create(email=instance.email) free_membership = Membership.objects.get(membership_type='Free') user_membership.stripe_customer_id = new_customer_id['id'] user_membership.membership = free_membership user_membership.save() … -
Adding a login decorator breaks a view from working
I have a view setup based on the documentation from django-table2, which is as follows: class FamilyView(SingleTableView): model = Family table_class = FMTable template_name = 'family/members.html' And the relevant line from my urls.py path("family/", FamilyView.as_view()) And this all works perfectly. Until I add a login director. When I change my view above to be: @login_required(login_url='/home/login/') class FamilyView(SingleTableView): model = Family table_class = FMTable template_name = 'family/members.html' I get the error that: AttributeError at /family/ 'function' object has no attribute 'as_view' The problem seemed to be with the way the view was referenced in urls.py, which was not a way I was familiar with. I attempted to reform it like so: path('family/', views.FamilyView, name='FamilyView'), But this results in the error: TypeError at /family/ __init__() takes 1 positional argument but 2 were given What is the difference in reference viewName.as_view() versus views.viewName with a 'name' parameter? Why is adding the login decorator as I have breaking my view? -
Django allauth login suddenly stopped working without modifying any code related
I have implemented Allauth since few moths ago and everything was working fine. Without making any change on the login code and just by implementing i18n on the whole application, my login forms stopped working at all. I can see the template, I can fill the input, but either if I use correct or wrong credentials when I click on the button to log in it just seems to refresh the page and do not log in nor show error messages. The input fields are also empty. If I go to django admin and I log in with the default django admin login, it works fine and I can enter with my admin user. I checked the installation guide and the configuration steps two more times but there is nothing changed and everything seems to be on it's place. I tried updating from django allauth 0.42.0 to 0.43.0 but the problem is not solved. The register, passwd recovery and email verification works fine. It's just the login. I have a custom login form, but as I said it was working fine. The only thing I do is modify the layout with crispy-forms: class CustomLoginForm(LoginForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, … -
Django Renaming model and then reusing name for new model
I have a model with existing objects which I want to rename and then use the old name for a new model. Basically - Existing model - class ItemFile(models.Model): file = models.ImageField(upload_to='items/images/%Y/%m/%d') timestamp = models.DateTimeField(default=timezone.now) thumbnail = models.ImageField(upload_to='items/images/%Y/%m/%d/thumbs/', blank=True, null=True) item = models.ForeignKey(Item, related_name='files', blank=True, null=True) This must be renamed to ItemImage And the new model - class ItemFile(models.Model): file = models.FileField(upload_to='items/files/%Y/%m/%d') timestamp = models.DateTimeField(default=timezone.now) item = models.ForeignKey(Item, related_name='other_files', blank=True, null=True) This is what I did - Changed model name from ItemFile to ItemImage. Migration successful Added the new ItemFile model. This is giving me a relation already exists error probably because of existing objects. How do I resolve this? Django - 1.11. Postgres 10 -
create comment for a post in post detail view in django restframework
What is the best practice to add the posting a comment functionality in a post detail view for a post in Django Restframework? thanks. Here the Comment and Post Class: class Post(models.Model): [...] title = models.CharField(max_length=250) body = models.TextField() tags = TaggableManager(blank=True) [...] class Comment(models.Model): post = models.ForeignKey( to=Post, on_delete=models.CASCADE, related_name='comments' ) name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() [...] the PostDetail Serializer: class PostDetailSerializer(serializers.HyperlinkedModelSerializer): author = serializers.ReadOnlyField(source='author.username') tags = TagListSerializerField() category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name') comments = CommentSerializer(many=True, read_only=True) class Meta: model = Post fields = [ 'title', 'author', 'slug', 'cover', 'body', 'category', 'tags', 'created', 'updated', 'comments', ] read_only_fields = ['slug'] And the Post Detail view: class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.published.all() serializer_class = PostDetailSerializer permission_classes = [IsAuthenticatedOrReadOnly] -
Django Generic Relation woth parent model
I have created a model Comments. I want store reply in same table Comment. class Comment(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) text = models.CharField(max_length=300, blank=False, null=False) object_id = models.PositiveIntegerField() timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) content_object = GenericForeignKey('content_type', 'object_id') # Relation reply = GenericRelation(Comment, related_query_name='reply') like = GenericRelation(Like, related_query_name='like') Here i am getting this error !! reply = GenericRelation(Comment, related_query_name='reply') NameError: name 'Comment' is not defined How can i set this relationship ? -
i wanted to upload multiple images to the project directory using python?
i have a project in which i want to create a media directory inside it and i want user to upload multiple images from the html page and those images to be stored in media directory. i tried multiple solutions but it didn't work out for me https://www.geeksforgeeks.org/python-uploading-images-in-django/ [this gives me the error : 'MultiValueDict' object has no attribute '_committed'] https://www.youtube.com/watch?v=C9MDtQHwGYM&t=287s [on uploading the images 2nd time it overwrite the previous uploaded file and how can i give relative path to the destination folder ] if anyone could help me with this. -
How can I avoid this Unexpected token error when using django/javascript?
I am trying to pass some data from my django app into a javascript following the answers this question views.py context['username'] = json.dumps(request.user.username) test_script.js document.write('Script working') username = {{ username|safe }}; But in console I get the error Uncaught SyntaxError: Unexpected token '{' What am I missing? -
Migration admin.0004_auto_20200625_1615 dependencies reference nonexistent parent node ('staff', '0001_initial')
django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20200625_1615 dependencies reference nonexistent parent node ('staff', '0001_initial') -
Getting 500 MultiValueDictKeyError while sending data in the object from react using axios
```let multipleInvitations = []; emailList.forEach((email) => { const invitation = { email: email, inviter: this.user.id, key: this.getRandomIntInclusive(), inviter_msg: this.state.inviter_msg, }; multipleInvitations.push(invitation); }); const multipleInvitationsList = { email: multipleInvitations, }; console.log(multipleInvitationsList); axios .post(`${host}/invite/sendMultipleInvite/`, abc, { headers: { "Content-type": "application/x-www-form-urlencoded", }, }) .then((response) => console.log(response));``` It is giving me the MultiValueDictKeyError at 'email'. I tried every posible way of sending data. like, content-type: 'application/json' and more. it didn't work though. The same format is working in Flutter as my collegue said. -
Python | How to show 2 models information in template with the same class
I need to get 2 models information in template. Because there are Stations that has Devices. (I need to show Station detail with device list) How can I show 2 models information in template? class StationDetailView(DetailView): model = Station model = Device template_name = "station/detail_station.html" Thanks! -
Make migrations Command
I just started teh django with python.while ı tried the run code that is "python manage.py make migrations" , ı see error "module 'django.db.models' has no attribute 'models'". how can ı fix it?(I left the code and error down. ) from django.db import models class Article(models.Model): author = models.ForeignKey("auth.User",on_delete = models.CASCADE) title = models.models.CharField(max_length=50) content = models.models.TextField() created_date = models.models.DateTimeField(auto_now_add = True) Error -
why a model field set to null when updating the object in Django
I have a model and I added a new field in it. I want to set this field in if "self._state.adding" and accessing it in: "if not self._state.adding" when I did this it set successfully in the DB but whenever I accessing it in "if not self._state.adding" I'm getting it as None and also in the DB it is updated to Null. I tried to do the same with the existed fields(old fields in the model) to test but they are not setting to null as the new feild! Does anyone have any idea why this issue accrue why the save function updating the new filed to Null! This is the newly added field: number_format = models.CharField(max_length=100, blank=True, null=True) This is my save function in the model: def save(self, *args, **kwargs): if self._state.adding: self.number_format = “type1” print(self.number_format) super().save(*args, **kwargs) else: print(self.number_format) super().save(*args, **kwargs) -
Error: save() takes 1 positional argument but 2 were given
I'm trying to add a date to the slug on save after I click Publish in the Wagtail admin panel i get en error save() takes 1 positional argument but 2 were given I'm quite new to python and Django/Wagtail so any help at this point would be grate. def save(self, **kwargs): now = dt.datetime.now() if self.slug: self.slug = f"{self.slug}-{now.strftime('%Y-%m-%d-%H-%I-%S')}" super().save(self, **kwargs) Thank you -
Django social auth - After the auth, redirect to the page where the auth is initiated
Scenario: users are using https://example.com When a user is in https://example.com/page-a with account A , and wants to change to account B. The user clicks logout, then after using Django social auth, I want the user still seeing the https://example.com/page-a. Any method to do this with Django social auth? I think maybe can make user of the referrer header during the redirect. When the social auth redirecting the user to the login page (lets say https://accounts.google.com/signin/oauth/...), we can see the referrer header is https://example.com/page-a. I think can make use of this to redirect user back to the page where the login is initiated instead of just a hard coded settings like LOGIN_REDIRECT_URL But not sure how to do this with current Django social auth. -
Logic behing Drag and drop chatbot web application
Is there any open source drag and drop chat bot building frame work? What is the back end architecture of such a platform? -
I want to use # link in django
<div class="site-wrap"> <div class="site-mobile-menu site-navbar-target"> <div class="site-mobile-menu-header"> <div class="site-mobile-menu-close mt-3"> <span class="icon-close2 js-menu-toggle"></span> </div> </div> <div class="site-mobile-menu-body"></div> </div> <!-- .site-mobile-menu --> <div class="site-navbar-wrap"> <div class="site-navbar site-navbar-target js-sticky-header"> <div class="container"> <div class="row align-items-center"> <div class="col-6 col-md-4"> <h1 class="my-0 site-logo"><img src="{% static 'images/avatar.png' %}" width="36" height="50" class="d-inline-block align-middle"><a href="/">Ishan<span class="text-primary"></span> </a></h1> </div> <div class="col-6 col-md-8"> <nav class="site-navigation text-right" role="navigation"> <div class="container"> <div class="d-inline-block d-lg-block ml-md-0 mr-auto py-3"><a href="#" class="site-menu-toggle js-menu-toggle text-black"> <span class="icon-menu h3"></span> <span class="menu-text"></span> </a></div> <ul class="site-menu main-menu js-clone-nav d-none d-lg-none"> <li><a href="#home-section" class="nav-link">Home</a></li> <li><a href="#about-section" class="nav-link">About Us</a></li> <li><a href="#what-we-do-section" class="nav-link">What We Do</a></li> <li><a href="#portfolio-section" class="nav-link">Portfolio</a></li> <li><a href="#contact-section" class="nav-link">Contact</a></li> </ul> </div> </nav> </div> </div> </div> </div> </div> this code should create a navbar. This code is working when i simply use it. But, In this navbar links should appear on clicking the 3 lines but when i use it in django it does not open the navbar links. -
File upload in mssql using django python
I want to upload the pdf file to MSSQL varbinary field from django. I am using angular front-end , however i am getting the error unable to convert on the server when i call the stored procedure. On analysis i got that the type of file when printed from request.files('param_name') it gives inmemoryuploadedfile. -
Dynamically change link in views to html file
I am trying to know if it is possible to change the link to html file in Django views. I have done enough googling but couldn't find any relevant stuff. I have passed the slug in tag in template like <a href="{% url 'detail' slug="abc" %}"> test</a> url.py path('(<slug>[\w-]+)/', views.article, name='detail'), in views.py def article(request,slug): return render(request, 'website/{slug}.html') I want to render abc.html -
how can I retrieve objects of a model that have most related objects in another model?
I have these two models: class Person(models.Model): name = models.CharField() class Image(models.Model): a = models.Foreignkey(A, on_delete=models.CASCADE) img = models.ImageField() every object in model Person has one or more images in model Image. I want to retrieve 5 person objects that have most images. How can I do that? -
Django static files and pull requests from git repo
My question is: When I am developing on localhost and adding bunch of static files(images), what is the best way to get those files to the server which is hosted on DigitalOcean? Right now I have a git repo to which I do push and pull requests, but in my .gitignore I have /static/ ignored from some tutorial. I can not find any information on what is the best practice.