Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to validate a parent form with its subforms django
i made a management system for a store , sometimes happen a sold product will be return , and then i will add the sold product to storage , but i want to make sure the filled Return product form are correct , with absolute product which sold in that form class Products(models.Model): name = models.CharField(max_length=20) quantity = models.IntegerField() class ProductInvoice(models.Model): customer = models.CharField(max_length=30) product= models.ManyToManyField(Products,through='SelectProduct') def __str__(self): return str(self.id) class SelectProduct(models.Model): product= models.ForeignKey(Products, on_delete=models.CASCADE) item = models.ForeignKey(ProductInvoice,on_delete=models.CASCADE,default='') qnt= models.IntegerField() price = models.IntegerField() cash= models.IntegerField() in a single invoice we can sell multiproducts with different quantities ! , i have done all as i wanted , but now i need to make a new Invoice to those products which return by customers after bought , class ReturnProduct(models.Model): customer = models.ForeignKey(ProductInvoice,on_delete=models.CASCADE,related_name='customer_returns') product = models.ManyToManyField(Products,through='ProductQuantity') class ProductQuantity(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) item = models.ForeignKey(ReturnProduct,on_delete=models.CASCADE) quantity = models.IntegerField() price = models.IntegerField() i want check if the selected product inside ProductQuantity with its ReturnProduct customer(id of ProductInvoice) are not the same then raise an error and i added return products to the storage correctly def save_post(sender,instance,created,**kwargs): if created: Products.objects.filter(pk=instance.product_id).update( quantity=F('quantity')+instance.quantity) post_save.connect(save_post,sender=ProductQuantity) and this is my forms.py to return products class ReturnProductForm(ModelForm): customer = ModelChoiceField(queryset=ProductInvoice.objects.all()) class … -
is there a way to create a folder on aws S3 Buckets if it doesn't exist via Django
newbie here < learning python/django. I am trying to create a barcode image file that will save to a folder on my aws s3 bucket. I don't know how to link to it. My media and static files are already on aws and are working perfectly but I don't know how to set the path for this barcodemaker function to save to the aws s3 bucket. Thank you for your patience and guidance. my barcode function in my view def barcodemaker(): barcodemodel = apps.get_model('barcoder', 'barcodeModel') employee = apps.get_model('employees', 'Employee') data = employee.objects.filter(id=1) try: data2 = barcodemodel.objects.latest('id') except: data2 = 1002390000 naa = str(data2) naa = int(naa[-10:]) for i in data: id_name= str(i.id) naa += random.randint(500, 900) mocode = 'M-'+ id_name + '-'+ str(naa) b = barcodemodel(barcode_num=str(mocode)) b.save() path = (>>>PATH to aws<<<,'static','media','barcodes', mocode+'.png') with open(path, 'wb') as f: Code128(mocode, writer=ImageWriter()).write(f) barcode_context = { 'mocode':mocode, 'f':f } return barcode_context My Static file settings in my settings file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/profile_image/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') #S3 BUCKETS CONFIG # S3 logins Data AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' … -
MySQL query gives not enough arguments error on Django
I have the following MySQL query: SELECT FROM_UNIXTIME (unixtime, '%Y/%m/%d') AS ndate, count(id) AS query_count FROM myTable GROUP BY ndate ORDER BY query_count DESC When i execute this query on PHPMyadmin it will work without any problem. When i try to execute it from Django i get the following error: Summary = myTable.objects.raw("SELECT FROM_UNIXTIME (unixtime, '%Y/%m/%d') AS ndate, count(id) AS query_count FROM myTable GROUP BY ndate ORDER BY query_count DESC") >>not enough arguments for format string I don't understand why does that happen, since Django should just esecute the raw MySQL query. Can anyone help me out on this? -
coupon codes into cart
I'm trying to make a coupon code system in an eCommerce website, when i try to submit the form of my coupon system with a valid code, my app gives me an 302 error-code in the cli, but when i submit an incorrect/unregistered coupon code it gives me a basic error message. so why is this happening ? models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) valid_from = models.DateTimeField() valid_to = models.DateTimeField() active = models.BooleanField(default=True) def __str__(self): return self.code forms.py from django.contrib.gis import forms from .models import Coupon class CouponApplyForm(forms.ModelForm): code = forms.CharField(label="", widget = forms.TextInput(attrs = {'class':"coupon-bar form-control", 'placeholder':"enter Coupon here"})) class Meta: fields=('code',) model = Coupon views.py from django.shortcuts import render, redirect from .models import Coupon from .forms import CouponApplyForm from django.contrib import messages from django.views.decorators.http import require_POST from django.utils import timezone from shop.models import Order @require_POST def coupon_apply(request): now = timezone.now() form = CouponApplyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] try: coupon = Coupon.objects.get(code__iexact=code, valid_from__lte=now, valid_to__gte=now, active=True) request.session['coupon_id'] = coupon.id messages.success(request, 'Added successfully') except: request.session['coupon_id'] = None messages.warning(request, 'unAvailable') return redirect('checkout') views of my checkout page @login_required @customer_required def checkout(request): coupon_apply_form = CouponApplyForm()#deleted unrelated code... try:#coupon … -
Django Rest Framework access by Android and IOs app
I am made a decoupled project where the backend api is written in django using django rest framework. The webapp is made with react which is live at a certain url in a different server. So CORS comes into play. When i send http requests from the webapp the origin stays at www.domain.com. What will be the the request origin in case of an android and ios client ? How can i make sure the api is not accessible outside of these three client's i.e webapp, android app and ios app. Thanks in advance. -
Django : non iterable object into QuerySet
I'm trying to unpack a non iterable object into a QuerySet. This is my code : from django.shortcuts import render, get_object_or_404 from rest_framework.response import Response ... @api_view(['GET']) def order(request): '''Get all the orders for a user''' context = [] if request.GET.get('user'): #If we make a request type ?user=... id_user = request.GET.get('user') user = get_object_or_404(espace_membre, pk=id_user) if request.GET.get('order'): #If we make specific request on an order id_order = request.GET.get('order') orders = commande.objects.get(id=id_order, membre_id=id_user) else: orders = commande.objects.filter(membre_id=id_user) ... I would like to unpack orders when I get in the request ...?user=1&order=2. Thanks by advance -
which is best editor ckediter or tinyMCE on django framework
INSTALLED_APPS = [ 'ckeditor' ] or INSTALLED_APPS = [ 'tinyMce' ] -
Django Url redirecting problem when trying to log out user
How do i create a button that sends user to a specific URL? I tried doing it with simple a tag for example if I'm at accounts/ and click on it it redirects me to accounts/whatever i put in a tag. Why can't I just make a link that goes to logout/ when I'm currently at accounts/ instead of accounts/logout? -
How to fetch data from multiple model and display in single row?
I don't know how to set the value of the different key of dict in HTML. All I want is that fetch data from 3 different modules and display it in a single HTML ROW. But the problem is that I can These are the 3 models from which I want t to fetch data and display in a single row of single HTML table class Residence(models.Model): residence_name = models.CharField(max_length=30) residence_address = models.CharField(max_length=30) residence_city = models.CharField(max_length=20) residence_state = models.CharField(max_length=20) residence_pincode = models.IntegerField() description = models.CharField(max_length=255) rent = models.IntegerField() image = models.ImageField(upload_to='Images') class Facility(models.Model): residence_id = models.ForeignKey('Residence', on_delete=models.CASCADE) facility_type = models.CharField(max_length=30) class Residence_type(models.Model): residence_id = models.ForeignKey('Residence', on_delete=models.CASCADE) residence_type = models.CharField(max_length=7) This is my class in view.py in which I have already fetch data from all 3 models and already pass the duct to HTML file def view_all(request): residenceList = Residence.objects.all() typeList = Residence_type.objects.all() facilityList = Facility.objects.all() residenceDict = { "Residence": residenceList } typeList = { "Type": typeList } facilityDict = { "Facility": facilityList } return render(request, 'view-all.html', residencedict, typeList, facilityList) This is my HTML fine in which I want to display data of all 3 models into single row of HTML table <table class="grid-table"> <tr> <th>Name</th> <th>Address</th> <th>Description</th> <th>Rent</th> <th>Facility</th> <th>Residence … -
click image and have it to send data to view.py django
this is my img in my two.html https://i.stack.imgur.com/FhKlz.png <td> <img src="http://127.0.0.1:8000/imageAll/101.png" width="100"; height="300"> </td> i want to send data = 101 to my view.py when i click in my img because i want to use data. how i can do in django. i have to tried in onclick but is not work. view.py def two(request): return render(request,'two.html') def add(request): x =request.GET['name'] Name = obj.Name return render(request,'show.html',{"name" : Name} urls.py path('two/',views.two), path('add',views.add), -
Getting data to generate HTML: Ajax or Jinja?
I'm gonna use the Vue.js and Django framework to develop my project. So, here a question: which a below solution is better for generate the HTML-code: Pasting the data into Vue-objects by Jinja2 ( {% for d in data ... %} ) in other words, generate the Vue-code by Jinja; Getting the data by Ajax-request from Vue to my web-service API, that return the data in JSON format. I'm a new in frontend development, but I think, sending Ajax-request can be danger way to getting data. -
Multiple Tasks in Serial Order Python Django Framework
I have an android app that consumes Django REST APIs. The app is capturing several parameters and has 50-60 images captured. The data is being sent to the server which then parses JSON, uploads all images to cdn server and inserts that data into PostgreSQL tables depending on some logic. I am generating a PDF report using WK-HTML fetching back the same data. This PDF needs to be sent as response to API call. This entire process is taking time while the user is waiting on the app for PDF file. One thing I could do is use the JSON to generate PDF but I am not sure if all the images have been uploaded to CDN and can be used in PDF report. How can I achieve better results? Any guidance will be really appreciated. TIA. -
In a Django formset, how to display a model field as a Text instead of Choosing between options?
I have these Models: class ProductModel(models.Model): name = models.CharField(null=False, blank=False, max_length=20) code = models.CharField(null=False, blank=False, max_length=20) def __str__(self): return f'{self.name}' class OrderDetailModel(models.Model): product = models.ForeignKey(ProductModel, default ='', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0, null=False, blank=False) order = models.ForeignKey(OrderModel, null=False, blank=False) def __str__(self): return f'{self.order}' This in views.py: products = ProductModel.objects.all() FormSet = modelformset_factory(OrderDetailModel, fields=("product","quantity"), extra=0) form = FormSet(queryset=products) And in my template: <form method="POST"> <h3>Consumo</h3> <hr> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Próximo</button> </form> I get this: As you can see, the Product appears as a DropDown list and the user have to choose between the available products. How can I list all of them, and expect the user enter only their quantities? Like this... Please, how can I achieve this?? I've tried to use inlineformset_factory too without success (it display no fields for the product). I can something similar with a ModelForm, but I need this Form dynamically changing when a new product is registered. -
MultipleObjectsReturned at /cart/ get() returned more than one Customer -- it returned 3
store/models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user=models.OneToOneField(User , on_delete=models.CASCADE , null=True , blank=True) name=models.CharField(max_length=200) email=models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name=models.CharField(max_length=200) price=models.FloatField(max_length=200) digital=models.BooleanField(default=True , null=True , blank=True) image=models.ImageField(null=True) def __str__(self): return self.name class Order(models.Model): customer=models.ForeignKey(Customer , on_delete=models.SET_NULL , blank=True , null=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=True , null=True , blank=True) transaction_id=models.CharField(max_length=200 , null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product=models.ForeignKey(Product , on_delete=models.SET_NULL , blank=True , null=True) order=models.ForeignKey(Order , on_delete=models.SET_NULL , blank=True , null=True) qauntity=models.IntegerField(default=0 , null=True , blank=True) date_added=models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer=models.ForeignKey(Customer , on_delete=models.SET_NULL , blank=True , null=True) order=models.ForeignKey(Order , on_delete=models.SET_NULL , blank=True , null=True) address=models.CharField(max_length=200) city=models.CharField(max_length=200) state=models.CharField(max_length=200) zipcode=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) def __str__(self): return self.address store/views.py from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer=request.user.customer order , created=Order.objects.filter(customer=customer , complete=False) items = order.orderitem_set.all() else: items = [] context = {'items':items} return render(request, 'store/cart.html', context) def checkout(request): context = {} return render(request, 'store/checkout.html', context) -
How to change the way the output is printed?
I am entering text via a form and the text is being broken down into specific keywords within the sentence. Those keywords are associated with company names which are stored in a msql table. For example right now If I enter "need a plumber to get the pipe fixed'" I get the output b"[('WeHateSinksPlumbing',), ('FamilyPlumbers',)]\n" printed to my Django webpage. How would I clean up this output and just get the names of the companies separated by commas? I want the output just to be "WeHateSinksPlumbing, FamilyPlumbers". Let me know if you need to see any more code to help solve this issue. Here is the method that is getting the company names from the db table def match_tweet_for_website(self,weboutput): #this method uses the list impwords and matches the keywords from it #to the db and gets the company keywords for the keywords in the sentance #output= WebOutput.WebOutput(input("Enter Tweet ")) # print(weboutput.impWords) info = ', '.join(weboutput.impWords) self.cursor = self.connection.cursor(buffered=True) # print(', '.join(weboutput.impWords)) query= f"SELECT DISTINCT company_name FROM CompanyKeywords where keyword IN ({info})" self.cursor.execute(query,(info)) result = self.cursor.fetchall() print(result) code for the object import DatabaseInteractor import nltk class WebOutput: #still need to add hashtag functionality def __init__(self,text): self.text= text db = DatabaseInteractor.DatabaseInteractor() self.keywords= … -
how to read and display text file contain using javascript and django, Django i am using as back-end and javascript for fronend
I am using simple javascript/Jquery/CSS as frontend technology and Django as backend . calling ajax to send request to Django and defined rest based APIs in Django. i want to read one file in python and want to send it to frontend and wnat to display it in new window . please help with details or may be some hint . -
Have a create view for related field
How can I have a create view for the comment in RetrieveUpdateDestroyAPIView of the post? at this point, I have all the comments back in a list and can't create a single one. I know that I can have a seperate CreateApiView for Comment model and pass the pk of the post manually. but how can I do this is post detail view? Thanks. my post model: class Post(models.Model): title = models.CharField(max_length=250) body = models.TextField() [...] my comment model: 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() [...] post detail serializer class: 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', 'comments', ] and post detail view class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.published.all() serializer_class = PostDetailSerializer permission_classes = [IsAuthenticatedOrReadOnly] -
Unable to show cart data base on category (Django)
I have these Three models class Category(models.Model): name = models.CharField(max_length=255, blank=True, null=True) details = models.CharField(max_length=500, blank=True, null=True) photo= models.ImageField(upload_to = 'image/', default = 'None/no-img.jpg') create_date = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return self.name Category has data of ------- name ------- 1 Clothing 2 Electronics 3 Phones 4 Books 5 Home decors ------------ class Item(models.Model): item_name = models.CharField(max_length=255, blank=True, null=True) local_name = models.CharField(max_length=255, blank=True, null=True) scientific_name = models.CharField(max_length=255, blank=True, null=True) c_id = models.ForeignKey(Category, related_name='c_id_typtype', on_delete=models.CASCADE) short_details = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.name Item has data of type ------- item_name category(fk) ------- 1. Levies jeans 1(Clothing) 2. UCB T-shirts 1(Clothing) 3. Samsung M10 Phone 3(Phones) 4. ASUS T123 Phone 3(Phones) ... ... ------------ class DisplayCart(models.Model): item_id = models.ForeignKey(Item, related_name='cart_item',blank=True, null=True, on_delete=models.CASCADE) category_id = models.ForeignKey(Category, related_name='cart_cat',blank=True, null=True, on_delete=models.CASCADE) user_id = models.ForeignKey(User, related_name='cart_user_id',blank=True, null=True, on_delete=models.CASCADE) quantity = models.CharField(max_length=50,blank=True, null=True) cart_item_updated_date = models.CharField(max_length=50,blank=True, null=True) updated_date = models.DateTimeField(auto_now=True) create_date = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return self.item_id.item_name DisplayCart has data of type with user_id of this ----------------------------------- item_id category_id qty user_id ----------------------------------- 1(Levies jeans) 1 2 32 2(Samsung M10) 3 1 32 ... ... ---------------------------------- This is my View part def showcart(request): categories = Category.objects.all() items = Item.objects.all() loginuser = request.user.id cart_items = DisplayCart.objects.all().filter(user_id=loginuser) print("C users … -
Django RF, Error in Date comparison in serializer validation field
I have implimented below serializer validation to check if user entered date (yyyy-mm-dd) is within this week or at least by today. But getting error KeyError at 'today' class TableCreateUpdateserializer(serializers.ModelSerializer): tablerequireDate = serializers.DateField() today = datetime.datetime.today() class Meta: model = Tables fields = ['tablerequireDate', 'tablerequiretime'] def validate(self, data): if data['tablerequireDate'] >= data['today']: raise serializers.ValidationError( "Date must be today or within 7 days") return data -
Do we have some package or module in django through which we can see real-time changes of our html files in django?
as we have lite-server in Node to monitor real-time changes of our files, do we have anything similar to it in Django? -
Getting values from multiple tables with a single INNER JOIN like query in Django
I am trying to create a simple Hangman game in Django. I have two models, one for the list of words and one for the games played by users, with a foreign key relationship defined between them. This is the model definition: class WordMaster(models.Model): word = models.CharField("Secret Word", max_length=100) category = models.CharField("Category", max_length=20) sub_category = models.CharField("Sub-category", max_length=50) class GamesPlayed(models.Model): word_id = models.ForeignKey(WordMaster, on_delete=models.DO_NOTHING) guessed_letters = models.CharField("Guessed letters", max_length=72, null=True) guesses = models.IntegerField("Number of guesses", null=True) won = models.BooleanField("Won", null=True) start_time = models.DateTimeField("Started", auto_now=True, auto_now_add=False, null=True) Now when the game is being played, I need the word along with the guessed letters and number of guesses. I would do this using pure SQL as follows: SELECT * from gamesplayed gp JOIN wordmaster wm on gp.word_id = wm.id where gp.id = 5 However, I have failed to find an equivalent query in Django ORM despite looking in many places. So I finally used a filter query and got the results of one in a dictionary, then updated the dictionary to add the values from the other table. Here's the code I used: g = GamesPlayed.objects.filter(pk=5) game = list(g.values())[0] game.update(list(WordMaster.objects.filter(pk=game['word_id_id']).values())[0]) But this seems like a rather redundant way of doing things for two … -
Remove bottom branding from tiny mce in django templates
I am using tiny mce HtmlField() in my django models. Every thing works file but the bottom branding in the field annoys me. Is there any way to remove branding in django template. -
How can I solve the problem: NOT NULL constraint failed error? [Django]
while ago I created user_id to locate the question in URL now I replaced user_id by user_slug when I used user_id I had to use the following line: comment_form.instance.userasking_id = user_id now I have to use user_slug but it returns me that error: NOT NULL constraint failed: community_comment.userasking_id what I understand that it wants me to pass id through argument but I didn't because I used user_slug instead so, How can I fix this issue? views.py from django.shortcuts import render, redirect from .forms import UserAskingForm, CommentForm from .models import UserAsking, Comment from django.contrib.auth.decorators import login_required from django.http import HttpResponse from account.models import UserProfile from django.contrib.auth.models import User @login_required def user_asking(request): form = UserAskingForm if request.method == 'POST': form = UserAskingForm(request.POST, instance=request.user.userprofile) if form.is_valid(): asking = form.save(commit=False) asking.title = form.cleaned_data['title'] asking.question = form.cleaned_data['question'] asking.field = form.cleaned_data['field'] asking = UserAsking.objects.create(userprofile=request.user.userprofile, title=asking.title, question=asking.question, field=asking.field) asking.save() return redirect('community:user_questions') else: form = UserAskingForm() return render(request, 'community/asking_question.html', {'form': form}) return render(request, 'community/asking_question.html', {'form': form}) @login_required def user_questions(request): all_objects = UserAsking.objects.all().order_by('-title') context = { 'all_objects': all_objects, } return render(request, 'community/user_questions.html', context) # Delete post @login_required def delete_post(request, post_id=None, **kwargs): post_to_delete = UserAsking.objects.get(id=post_id) my_post = UserAsking.objects.get(id=post_id) if request.user == my_post.userprofile.user: try: post_to_delete.delete() return redirect('community:user_asking') except: return HttpResponse('something wrong') … -
Followers profile page in django
i am new to Django. i want create a social media like web application in Django. can you please guide me how can i create a page to view profile page of followers like Instagram using Django. -
Date field validation in Django
I have a model where users can enter date in (yyyy-mm-dd). How do I make sure that date is not past days and within next 7 days including today? class Tables(models.Model): tablerequiretime = models.TimeField() For example, If user enter 2020-6-26, it should raise error as date is yesterday; If user enter 2020-6-27, it should accept as date is today. If user enter 2020-7-4, it should accept as date is within this weak. Is it possible implement logic in model layer ? Or should I opt for serializer fields ?