Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement Apache2 + Django + Vuejs into one platform
I am stuck with the Integration of Django and vuejs with apache2 into one single application. Basically python manage.py runserver can run the django. Instead of running python manage.py runserver apache2 can do the job. So what I need to do is; need to integrate the apache2 to run both Django (BackEnd)+ vuejs(FrontEnd). I couldn't find a solution for this. Please help me to solve the problem. Currently Django is working along with apache2. But vuejs has no solution. To load vuejs application (FrontEnd), basically we need to run it separately in the terminal npm run serve. What I want to do is; when I run this code service apache2 reload. Backend (Django) and Frontend (vuejs) should load simultaneously. -
Login redirect url in django
I am building a website that have customer and merchant. Each of them have different login. what i want is each user to login to his own view. models.py class User(AbstractUser): is_customer=models.BooleanField(default=False) is_merchant=models.BooleanField(default=False) class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Merchant(models.Model): #user = models.ForeignKey(User, on_delete=models.CASCADE) user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) views.py #merchant view def users_homepage(request): product = Product.objects.filter(merchant=request.user.merchant).order_by('date_added') itemsordered=OrderItem.objects.filter(merchant=request.user.merchant) #customer view def index(request): listing=Category.objects.all() product=Product.objects.all()[:8] setings.py LOGIN_REDIRECT_URL='/users' please show me how i can do it. thanks beforehand. -
Implement one-to-many relation with one-to-one relation without circular dependency
I have two model, User & Company where a company may have multiple users and a single owner(which is also a user). A user can be associated with only one company. Now my question is, how am I supposed to maintain the Owner of any company? Because if I use any one-to-one relation field in Company model then it will give me circular-dependency error as I have foreign-key relation field in my User model. Models are given below: User model class User(BaseMixin, AbstractUser, BlameableMixin): """Extends django user with extra optional fields.""" role = models.ManyToManyField(Role) company = models.ForeignKey( Company, related_name='user_company_map', on_delete=models.SET_NULL, null=True, ) designation = models.CharField(max_length=max_length_medium, blank=True, unique=False) mobile_no = models.CharField(max_length=max_length_medium, blank=False, unique=False) organization = models.CharField(max_length=max_length_medium, blank=False, unique=False) Company model class Company(BaseMixin, BlameableMixin): """Company detail.""" name = models.CharField(max_length=max_length_large, blank=True, unique=False) code_name = models.CharField(max_length=max_length_large, blank=True, unique=True) domain = models.CharField(max_length=max_length_large, blank=True) As shown on the code above I have a foreign key field on User model that connects my User model to Company model. Now I would like to have a field that will help me to keep track of a user who is the owner of any specific company. It will be also very helpful if you provide the django-orm queries for … -
Dynamically redirecting in django
I am trying to dynamically redirect from one dynamic page to another. Think about being on an IMDB movie page (dynamic) and then following the link to the writer/director/actor page(dynamic). These are the urls: urlpatterns = [ path('', views.index, name="index"), path('writer/<int:id>', views.writer, name="writer"), path('title/<int:id>', views.title, name="title"), path('creator/', views.creator, name="creator"), ] This is the index.html: {% for pilots in pilot %} <div> <p>Title: <a href="title/{{ pilots.id }}">{{ pilots.title }}</a></p> {% for writers in pilots.creators.all %} <p>Writer: <a href="writer/{{ writers.id }}">{{ writers.writer }}</a></p> {% endfor %} </div> {% endfor %} This is the title.html (which the dynamic ahref isn't working): {% for title in titles %} <p>{{title.title}}</p> <p>{{title.count}}</p> <p>{{title.year}}</p> <p>{{title.description}}</p> {% for creators in title.creators.all %} <a href="creator/">{{creators.writer}}</a> {% endfor %} {% endfor %} And this is the views.py: def title(request, id): titles = Pilot.objects.filter(id=id) context = { 'titles': titles, } return render(request, 'title.html', context) def creator(request): return redirect(f'writer/{id}') -
Filter many-to-many field DRF
I need to filter my API response of document using a many-to-many category field. This is my model: class Document(models.Model): name = models.CharField(max_length = 100, blank = True) file = models.FileField(null = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])]) date_created = models.DateTimeField(auto_now_add = True, null = True) category = models.ManyToManyField(Category) company = models.ForeignKey(Company, null = True, on_delete = models.SET_NULL) author = models.ForeignKey(Employee, null = True, on_delete = models.SET_NULL) The serializer for this models is: class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Document fields = "__all__" And I'm trying to filter it with this: class DocumentFilter(filters.FilterSet): # having_category = filters.Filter(name = 'category', lookup_type = 'in') class Meta: model = Document fields = { 'company': ['exact'], 'author': ['exact'], # 'category': ['in'] } I tried using this solution as you can see in the code but wasn't successful. filtering with company and author are working, and I'm facing an issue only with category. How should I create the filter? -
Django validate_unique restricts update/patch
I have this model which is serialized via DRF class Orders(models.Model): accession = models.CharField(max_length=20) testcode = models.ForeignKey(TestCodes, on_delete=models.CASCADE, related_name='tcodes') # testName = models.ForeignKey(TestCodes, on_delete=models.CASCADE, to_field='testname', related_name='tnames') method = models.CharField(max_length=50, blank=True, null=True, default='NGS') custName = models.CharField(max_length=50) testSite = models.CharField(max_length=50) procedure = models.ForeignKey(Workflows, on_delete=models.CASCADE, blank=True, null=True) where I'm trying to make the accession and testcode fields combination unique to prevent user from creating the same accession with the same testcode def validate_unique(self, exclude=None): qs = Orders.objects.filter(accession=self.accession) if qs.filter(testcode=self.testcode).exists(): raise ValidationError('Accession must be unique per testcode') it works well but if I try to patch or update other fields it raises the validation error 'Accession must be unique per testcode' is there a workaround for this issue -
How to get all the appended sinlge input files?
Here user selects only one image at once and the selected image gets appended inside the ul tag. There is max limit to 5 images inside the ul tag but I am being unable to get all the files selected in my django view. I want to send those all the images inside the ul tag to the backend . Right now only the last image selected is passing. What I have to do for this ? js var prew = true; function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { var thumbnail = e.target.result; img = ` <li> <div class="image"> <img src="${e.target.result}" width="100" height="100"/> <div class="close"><div class="ic-close" id="img-remove"></div> </div></li> ` if (prew) { $("#thumbnail").attr('src', thumbnail); prew = false; } $('#blah').append(img); if ($('ul#blah li').length > 5) { $("#blah li:last-child").remove(); alert("You can't upload more than 5 images."); } } reader.readAsDataURL(input.files[0]); $('ul#blah').on('click', '.ic-close', function(e) { console.log('k'); $(this).closest('li').remove(); }); } } $("#imgInp").change(function() { readURL(this); //var files = $('#imgInp').prop('files'); //console.log(files) }); html <ul class="list list-inline list--image" id="blah"> <li class="thumbnail"> <div class="image"> <img id="thumbnail" src="" width="100" height="100" /> <p>Thumbnail</p> </div> </li> <div class="files--upload"><input class="d-none imgUpload" name="image" type="file" id="imgInp" placeholder="" /><label class="upload-label" for="imgInp"> <div class="ic-add"></div> <div class="mt-2">Add Photo</div> … -
Django: How to redirect UpdateView in the get request
I have a use-case in which if a drop-down changes, the view should be redirected to another view. In the update view, I am using built-in class-based view, UpdateView. How do I redirect if the redirect is needed before submitting the form. I take it that get_success_url() works for when the form is submitted -
How to solve local variable referenced before assignment and return form data in template correctly?
I want to return the item code and item number entered in the form in the template. This is a very simple application. views.py def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_itemcode= csv_form.cleaned_data['item_code'] csv_itemnumber= csv_form.cleaned_data['item_number'] else: csv_form = CsvForm() context = {'csv_itemcode': csv_itemcode, 'csv_itemnumber': csv_itemnumber,'csv_form':csv_form} return render(request,'colorlib-regform-6/submit.html',context) submit.html <html> <body> <h4>{{ csv_itemcode }}</h4> <h4>{{ csv_itemnumber }}</h4> </body> </html> I got local variable csv_itemcode referenced before assignment. Any suggestions towards this. -
When I create a single form, 2 forms appear. Why is that happening ? Thanks
Hello everyone i got a problem and i tried hard to fix it but i cant solve. When i add my form to my template (only using {{ form.dept }}) it happens 2 form on my site. My Models.py > class Kaydol(models.Model): name=models.CharField(max_length=40) surname=models.CharField(max_length=40) email=models.EmailField(max_length=100) DEPARTMENTS=[ ('BK', 'Hiç Birisi'), ('KK', 'Kredi Kartı ile Ödeme'), ('Çek', 'Çek ile Ödeme') ] dept=models.CharField(max_length=3, choices=DEPARTMENTS, default='BK') my forms.py > class KaydolForm(forms.ModelForm): class Meta: model = Kaydol fields = ['name', 'surname', 'email','dept'] widgets = { 'name': forms.TextInput(attrs={'placeholder':"Adınız"}), 'surname': forms.TextInput(attrs={'placeholder': "Soyadınız"}), 'email': forms.TextInput(attrs={'placeholder': "Email"}) views.py def kaydol(request): if request.method == 'POST': form = KaydolForm(request.POST) if form.is_valid(): form.save() form = KaydolForm() else: form = KaydolForm() form=KaydolForm() context = { 'form':form } return render(request,'index.html',context) and my html > <div class="col-sm-12"> <b>Alternatif Ödeme Kanalı</b> {{ form.dept }} -
default=True is not reflected in django admin BooleanField
I have added a field this_field in django models but in admin its False. My model. this_field = models.BooleanField(default=True) My migration: migrations.AlterField( model_name='a', name='this_field', field=models.BooleanField(default=True), ), Default value should be true of the field but its not working default is shown as false. When I add a new field that_field as models.BooleanField(default=True) its default is true but this_field is an old field and its its values is not being reflected in django admin . -
How to catch CSRF errors in Django
How would I go about catching CSRF errors in Django? For example, I would like to catch this: Forbidden (CSRF token missing or incorrect.): /asdjasdjk/asdhriheiof I want to do this because I want to ban people who tamper with CSRF codes for my particular case. Any help is appreciated. -
How to Upload image or select from sample images in Django?
I am working on a website where I want to give an option to the customer to Upload the image by him/her or he/she can select images from given samples. Can you help me, how can I provide these options? And also explain to me how should I create a pop-up to display sample images. I am a newbie and working on Django 2.2 with MySQL. -
python requests json api problem. it only returns 1000 enteries
i want to pull this api data https://data.ct.gov/resource/6tja-6vdt.json. There is 19k entries in the website but when I pull through requests.get it returns only 1000. HOw to get all data at once? how to use limits and offsets and loops to get all at once -
ValueError at /save_data/
ValueError at /save_data/ Cannot assign "'IT'": "ProfileModel.itype" must be a "IndustriesModel" instance this is the error i am getting when saving the data to profilemodel could this is my models: def save_data(request): ed=request.POST.get("p1") ph=request.POST.get("p2") re=request.POST.get("p3") ty=request.POST.get("p4") ProfileModel(education=ed,photo=ph,resume=re,itype=ty).save() return render(request,"process_templates/login.html") and the views.py : ''' class IndustriesModel(models.Model): ino=models.AutoField(primary_key=True) type=models.CharField(max_length=100) def __str__(self): return self.type class ProfileModel(models.Model): pno=models.AutoField(primary_key=True) person=models.OneToOneField(RegistrationModel,on_delete=models.CASCADE) education=models.CharField(max_length=100) photo=models.ImageField(upload_to='user_images/') resume=models.FileField(upload_to='user_resumes/') itype=models.OneToOneField(IndustriesModel,on_delete=models.CASCADE) ''' could anyone help me solving the issue i am using html to not the forms. -
how to create related object while uploading csv in django
I am trying to create a foreignkey object when uploading csv as follows, def user_upload(request): data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 9: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], state=column[7], postcode=column[8], country=column[9], ) users.set_password('password') users.save() pricing = Pricing.objects.get(name='Free Trial') for user in users: subscription = Subscription.objects.create(user=user, pricing=pricing) stripe_customer = stripe.Customer.create( email=user.email ) stripe_subscription = stripe.Subscription.create( customer=stripe_customer["id"], items=[{'price': 'price_1HkPcpOS8'}], trial_period_days=7 ) subscription.status = stripe_subscription["status"] subscription.stripe_subscription_id = stripe_subscription["id"] subscription.save() except IntegrityError as e: return render_to_response('snippets/message.html') context = {} return render(request, template, context) User part is working but the related object Subscription is not getting updated as it throws error User is not iterable, how I can upload to related tables, thanks -
Django For Loop Creating Empty Divs
I am trying to loop through a list of items that are associated with a list of orders within my template and the loop is generating empty rows in my html because its looping through ALL OrderItems in my database. div class="container"> {% for order in orders %} <div class="col-lg-6"> <h3>{{order.topic}}, {{order.entry}} - Order #{{order.id}}</h3> <div class="box-element"> <div class="cart-row"> <div style="flex: 2;"></div> <div style="flex: 2;"><strong>Item</strong></div> <div style="flex: 1;"><strong>Price</strong></div> <div style="flex: 1;"><strong>Quantity</strong></div> <div style="flex: 1;"><strong>Total</strong></div> </div> {% for item in items %} <div class="cart-row"> {% if item.order.id == order.id %} <div style="flex: 2"><img class="row-image" src="{{ item.menu_item.image.url }}"></div> <div style="flex: 2">{{item.menu_item.title}}</div> <div style="flex: 1">{{item.menu_item.price}}</div> <div style="flex: 1"> <p class="quantity">{{order.get_cart_items}}</p> </div> <div style="flex: 1">${{order.get_cart_total}}</div> {% else %} {% endif %} </div> {% empty %} {% endfor %} </div> </div> {% empty %} <p>No Orders exist</p> {% endfor %} </div> I think the problem is that the items Queryset (shown in my view below) is returning all Orderitems in my DB and then i am looping through them in the template. How can I perform this loop in my view so i don't run into this problem (and future performance bottleneck) in my template? def orders(request): """View open orders for a customer""" if request.user.is_authenticated: … -
count total object in foreign key - drf
i want to count comments for every single Post in models.py: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] class Comment(models.Model): body = models.TextField(max_length=1000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) class Meta: ordering = ['-date'] in serializers.py: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class PostSerializer(serializers.ModelSerializer): #comments = CommentSerializer() user = UserSerializers() total_likes = serializers.SerializerMethodField() liked_by = SimpleUserSerializer(many=True, read_only=True) total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('body','date','user', 'total_likes', 'liked_by','total_comments') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comments.count() when i run this code, it shows, AttributeError: 'Post' object has no attribute 'comments'. how do i count comments of a post? -
Create a 'post' object and initialize a m2m attribute with post id and author id
I am trying to accomplish the following in Django: An app that allows users to create image posts. They can view any post that is in the system and add those posts to their bookmarks. When a user creates a post, the post is automatically added to their bookmarks. Model class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) post_image = models.ImageField(max_length=255, upload_to='images/content/', blank=False, null=False) author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='authors') tags = TaggableManager(through=UUIDTaggedItem, help_text=_('Maximum of 5 tags allowed')) created = models.DateTimeField(auto_now_add=True) bookmarks = models.ManyToManyField(User, related_name='bookmarked', blank=True) bookmark_count = models.IntegerField(default=0) def get_create_date(self): return self.created.strftime("%B %Y") ordering = ['-created'] View @login_required def post_add_view(request, *args, **kwargs): context = {} user = request.user if request.method == 'POST': form = PostAddForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.author = user new_post.save() form.save_m2m() context['form'] = form messages.add_message(request, messages.SUCCESS, 'Image uploaded successfuly!') return redirect('library:posts') context['form'] = form return render(request, 'library/post_add.html', context) else: form = PostAddForm() context['form'] = form return render(request, 'library/post_add.html', context) When a user creates a new post, that post will be associated with an additional attribute in the Post object called 'bookmarks'. The 'bookmarks' attribute has a many-to-many relationship with author and post. I can easily create the post object, associate it with the author and save … -
Django: Javascript error with alert box displaying values
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference. views.py def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return redirect('blog-home') home.html {% extends "blog/base.html" %} {% load static %} {% block content %} <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button id="btn" type="submit" form="menuForm">Confirm Purchase</button> </form> <script src="{% static "JS/javascript.js" %}" type="text/javascript"></script> … -
How do I solve this error of Pymongo? cursor id not found pymongo
I'm getting the whole data of some collection in MongoDB and after a while (like 30 or 60 minutes), the script raises the following error: pymongo.errors.CursorNotFound: cursor id 1801580172063793986 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 1801580172063793986 not found', 'code': 43, 'codeName': 'CursorNotFound'} This error occurs after the 24k documents. I'm using Django and Pymongo connected to the database in the local server. The collection has like 60k documents. This is how I'm getting the data: client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) collection = client[settings.MONGO_DB].users cursor = users.find(no_cursor_timeout=True) for user in cursor: # getting the data from the user Just in case, I'm using: Python 3.8 Django 3.1.4 Pymongo 3.11.0 Mongod 4.4.2 (for the local server) Ubuntu 20.04 -
Django: preserving GET parameters in URL template tag
I'm using a GET parameter in my Django app to pass in information, that I want to be preserved in future links using Django's {% url %} template tag. In my case, this is to allow view-only access within the app. Example URL: https://my.app/entry/123?key=abcdef An example link on that page is already created like this: <a href="{% url 'entry_detail' entry.id %}">View more details</a> Desired result: I would like Django's URL template tag to automatically preserve any GET parameters named key throughout the app. In this case, it would generate new URLs with that same parameter applied. For example: https://my.app/entry/123/details?key=abcdef Workarounds This blog post and this gist solve the problem by creating a new template tag and using that instead of Django's url template tag. Is that really the best solution? I'd end up having to replace every instance of {% url %} throughout my app with my own tag. It also wouldn't fix the use of reverse(). -
Set the min attribute HTML form value of a field in views.py
I was looking through this article to figure out how to set a field's value after a form is initialized. I don't see this in Django's docs, or maybe I'm putting in the wrong query, but is there a way to set the 'min' attribute value of a field in views.py? I'm asking because the min value can change constantly since it's a bid amount that is set each time a user bids above the highest_bid variable value in the view_listing function. models.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) listing = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True) bid_amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return f"{self.user}'s bid on {self.listing} is {self.bid_amount}" forms.py class BidForm(ModelForm): class Meta: model = Bid fields = ('bid_amount',) labels = { 'bid_amount': ('Your Bid'), } widgets = { 'bid_amount': forms.NumberInput(attrs={'step': 00.50, 'class': 'form-control', 'style': 'width:50%', 'min': 0, 'title': '', 'placeholder': '' }) } views.py @login_required def view_listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) bids = Bid.objects.filter(listing=listing) all_bids = [] # Set an empty bid list to get all bids if any exist highest_bid = listing.starting_price # Set highest bid to 0 in case there are no bids if bids: bid_list = list(bids) # Convert Queryset to a list for index … -
How to restrict users from seeing swagger endpoint docs but not using them?
We want users to be able to see only a few swagger docs based a django permission given to them, but we don't want to restrict them from using other endpoints that they don't have permission to view. Swagger docs don't provide a way to do this (or at least I haven't seen). Has anyone done this? -
Django DataError index out of range with postrgresql
Good evening, I realise that this question may have been asked in the past, but I am getting the following errors "psycopg2.errors.NumericValueOutOfRange: integer out of range" and "django.db.utils.DataError: integer out of range" when using postgresql with Django. Other responses to similar queries all seem to suggest that I am reaching very large id's or pk's. This is not the case. My database is very small, and I am just trying to save objects to it, and I cannot possibly be reaching 2^31-1 id's. Some objects save ok, others do not and raise the error. There seems to be no pattern to it, and its infuriating. I have until recently been using sqlite for this, and I have never ever had this problem. I am new to postgresql but the database exists, is migrated to successfully and I can see the fields inside pgAdmin. The project is quite complex and I am unable to provide a minimum reproducible example without posting much code, but I am happy to elaborate. What could possibly by the reason for the above? Portion of models.py as requested: class Requirement(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, null=False) signups = models.ManyToManyField('Student', through='SignUp', blank=True) etc. class Student(models.Model): first_name = models.CharField(max_length=50, …