Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker Build sorunu lütfen yardım edin
ERROR: Cannot install -r requirements.txt (line 15), -r requirements.txt (line 21) and python-dateutil==1.5 because these package versions have conflicting dependencies. ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 Buda Benim requirements altgraph==0.17 asgiref==3.3.4 beautifulsoup4==4.9.3 certifi==2020.12.5 cffi==1.14.6 chardet==4.0.0 click==7.1.2 cryptography==3.4.7 Django==3.2.3 dnspython==1.16.0 future==0.18.2 gitdb==4.0.7 GitPython==3.1.18 gunicorn==20.1.0 heroku==0.1.4 html5lib==1.1 idna==2.10 install==1.3.4 mysql-connector==2.2.9 numpy==1.20.2 pandas==1.2.4 pefile==2021.5.24 pycparser==2.20 pyinstaller==4.4 pyinstaller-hooks-contrib==2021.2 pymongo==3.11.4 PyQt5==5.15.4 pyqt5-plugins==5.15.4.2.1.0 PyQt5-Qt5==5.15.2 PyQt5-sip==12.8.1 pyqt5-tools==5.15.4.3.0.3 python-dateutil==1.5 python-dotenv==0.17.1 pytz==2021.1 pywin32-ctypes==0.2.0 qt5-applications==5.15.2.2.1 qt5-tools==5.15.2.1.0.1 requests==2.25.1 selenium==3.141.0 six==1.15.0 smmap==4.0.0 soupsieve==2.2.1 sqlparse==0.4.1 style==1.1.0 typing-extensions==3.10.0.0 update==0.0.1 urllib3==1.26.4 webencodings==0.5.1 gunicorn -
How to integrate Django rest api in cpanel?
Thank You in advance, I am new to programming and I have made my frontend in Reactjs and backend in Django and It is possible to integrate my Django rest and Reactjs frontend in the same Cpanel. Most of the tutorials show the integration of Django with templates but I want to integrate my Django rest API, not with templates. -
Django: Fetch logged in user information from database and show them in html
I've menaged to create a form that allow me to save my website user information in the database. Right now I'd like to create a page where the saved info are showed to my user also. Of course I want my user to be able to see only their own information. This is what I came up with until now, it doesn't wotk and unfortunly I'm not getting any error, just a blanck html page aside for the title. How can I solve this? Thank you all! model.py class Info(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) phone = models.CharField(max_length=10) views.py def show(request): info = Info.objects.all().filter(first_name=request.user) return render(request, 'profile/show.html', {'info': info}) info.html <h1> Profile </h1> </br></br> {% if user.is_authenticated %} {% for info in info %} <li>First Name: {{ info.first_name }}</li> <li>Last Name: {{ info.last_name }}</li> <li>Phone Number: {{ info.phone }}</li> {% endfor %} {% endif %} -
How to print Json data to Django template
{'4': [1, 'Product New', '450.00', '4'], '6': [1, 'Products Hello', '4500.00', '6']} I receive data in my view.py: using products = json.loads(data) After that, i am trying to show each item's in Django templates. 4 and 6 is pro -
error while getting foreignkey id in django
I am new in django.i am trying to make a invoice generator app with django . where an employee inputs the customer id and it takes to the invoice page.in the invoice page the employe can enter a product id and the product and customer info will be added to invoice model object .so i want to add all the products for the same invoice id or want to filter by customer id which will get all the invoices for the customer id here is the code models.py from django.db import models from account.models import Customer from product.models import Product class Invoice(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE, default=1) customers = models.ForeignKey(Customer, on_delete=models.CASCADE, default=4) date = models.DateTimeField(auto_now_add=True) total = models.BigIntegerField(default=0) quantity = models.IntegerField(default=0) views.py def billingform(request): if request.method == "POST": cid = request.POST["customerId"] customer = Customer.objects.get(id=cid) request.session['customerId'] = cid return redirect('invoice') return render(request, 'bform.html') def invoice(request): cid = request.session.get('customerId') customer = Customer.objects.get(id=cid) if request.method == "POST": pd = request.POST["product_id"] qt = int(request.POST["quantity"]) product = Product.objects.get(id=pd) pd_price = int(product.selling_price) total = pd_price*qt pd_name = product.name Invoice.objects.create(products = product, quantity = qt, total=total, customers = customer) cust_id = Invoice.objects.get(id, customers=customer.id) product_name = cust_id.products product_quantity = cust_id.quantity product_total = cust_id.total return render(request, 'invoice.html', { "total":product_total, … -
I am using proxy model, Seller(CustomUser) and Customer(CustomUser), I am getting 'SellerManager' object has no attribute 'normalize_email' error
Error occurs when I create CustomUser by subclassing AbstractUser , but I don't get error when Create customuser by sublassing AbstractBaseUser. Why? class CustomUser(AbstractUser): # making default username to none instead using email as username field username = None email = models.EmailField(_('email address'),unique=True) name = models.CharField(max_length=255) """ Multiple user type without extra fields # 1. Boolean Select Field # option to make if user is seller or customer is_customer = models.BooleanField(default=True) is_seller = models.BooleanField(default=False) # 2 Choice Field with djnago multiselect # type = ( # (1, 'Seller'), # (2, 'Customer') # ) # to select one of two choice, to select multi instal package django-multiselectfield # user_type = models.IntegerField(choices=type, default=1) # 3 Separate class for different rolles and many to many field in user model # usertype = models.ManyToManyField(UserType) """ # Multiple user with extra field # 1 boolean field with class for different role # is_customer = models.BooleanField(default=True) # is_seller = models.BooleanField(default=False) # Proxy model class Types(models.TextChoices): CUSTOMER = "Customer", "CUSTOMER" SELLER = "Seller","SELLER" default_type = Types.CUSTOMER type = models.CharField(_('Type'),max_length=255, choices=Types.choices, default=default_type) # if not code below then taking default value in user model not in proxy in model # The point is that we do not know … -
Hello, Please i am using ajax to display date in django template it is giving me long unformatted date
for example var temp=""+response.messages[key].date+" result: 2021-10-02T09:53:27.896Z how do I make it to show the same as django -- {{date|timesince}} -
How to implement the mouseover product zoom functionality like amazon in slick sync slider? Not working jquery zoom plugins with this slider.possible?
I have done with the default slick sync slider. But cannot implement the jquery zoom plugins inside this slick slider. I want product zoom functionality like amazon..with this slick slider.please anyone tell me, what would be the best option for this.? -
How to restrict Media Folder using Django ? Is it a way?
I tried several tutorials using "FileResponse" to restrict the access to the MediaFolder only on authenticated User... But it does'nt run well online. It ran on localhost, but definitly not online. Is it a way or an App which can restrict the Media folder ? -
The QuerySet value for an exact lookup must be limited to one result using slicing in django
I was trying to do a system that will delete an item from our cart .so I made a url and I pass the slug of the item into it to delete it from the Cart . bit there is a problem . can you help please? views.py def remove_cart(request , slug): url = request.META.get('HTTP_REFERER') ca = product.objects.filter(slug = slug) Cart.objects.filter(produ = ca).delete() return redirect(url) urls.py app_name = 'cart' urlpatterns = [ path('' , views.cart_detail , name='cart_deatil'), re_path(r'^add/(?P<slug>[\w-]+)/$' , views.add_cart , name='add_cart'), re_path(r'^remove/(?P<slug>[\w-]+)/$' , views.remove_cart , name='remove_cart') ] models.py class Cart(models.Model): produ = models.ForeignKey(product , on_delete=models.CASCADE) user = models.ForeignKey(User , on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class CartForm(ModelForm): class Meta: model = Cart fields = ['quantity'] -
Restrict user from accessing form
Good day everyone! I'm a python Django web app developer and I ran into a problem recently which is to restrict a user from accessing a form twice untill after a given time. I've tried using Django sessions.accessed but I don't get what I want. I would appreciate if anyone could help me out with this. -
why getting Complex aggregates require an alias error?
I am working on Django where I have two models Gigs and Orders and I am calculating average Completion time of order of every gig. in order model I have two fields order start time (which I'm sending whenever seller accepts the order) and order completed time (which I'm sending when seller delivered) the order. but the problem is that if I have data in Orders table related to some gig and I retrieve the gig then it worked perfectly but if I tries to retrieve a gig with no orders yet ( in orders table there is no record/field containing that item/gig) then it gives me following error Complex aggregates require an alias Models.py class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if getattr(self, '_average_completionTime', None): return self._average_completionTime return self.gig.aggregate(Avg(F('orderCompletedTime') - F('orderStartTime'))) class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') orderStartTime = models.DateTimeField(default=timezone.now) orderCompletedTime = models.DateTimeField(default=timezone.now) isCompleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) Views.py class … -
Django add to cart form
i have a product model : class Product(models.Model): thumbnail =models.ImageField(upload_to=upload_image_path,null=True,blank=True) title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) discount = models.DecimalField(decimal_places=2, max_digits=20, default=00.00) slug = models.SlugField(blank=True, unique=True) and I want to add make an add to cart form so the user can add products to his cart, the problem is that the add to cart form is diffèrent for each product example: for product A: available colors: blue and yellow, available size: S, M for product B: available colors: black and white, available size: L, XL what I did is create another model: class Color(models.Model): Color = models.CharField(max_length=120) def __str__(self): return self.Color and then add a ManyToMany relation to the product model: class Product(models.Model): thumbnail =models.ImageField(upload_to=upload_image_path,null=True,blank=True) title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) discount = models.DecimalField(decimal_places=2, max_digits=20, default=00.00) slug = models.SlugField(blank=True, unique=True) Color = models.ManyToManyField(Color) so now when i am creating a product i can chose the avaible colors, but for the add to cart form I have to hard code it in html in the products.html template products.html : {% for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{product.thumbnail.url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{product}}</h5> <p class="card-text">{{product.description}}</p> <form … -
Create a dynamic launch URL for Power BI with tabular data
I have a WEB app where there is a table with data (the data is filtered using Python (Django), the database is Azure SQL Database) and I want to send this table using a link to the Power BI program, I mean after clicking a certain button so that it opens Power BI with the same data. For example, I can cite the work of the Teams program when we open the link in the browser, it wants to redirect us to the program itself, or open it in the browser itself Maybe someone will have ideas on how to implement this? -
POST request resulting logout in django
POST request resulting logout in django views.py @login_required def employerprofile(request): submitted=False if request.method == 'POST': form=EmployerProfileForm(request.POST,request.FILE) if form.is_valid(): form.save() return HttpResponseRedirect('/employerprofile?submitted=True') else: form=EmployerProfileForm if 'submitted' in request.GET: submitted=True return render(request,'employer/employer-profile.html', {'form':form,'submitted':submitted}) ------------------------------------------------------------------------ -
Is there a way to pass certain info, that is specific to a user, to the fields of a (new) django form?
I have the following "problem": I have automated a "prediction-game" where users can win points when they predict the correct winners in a sports event over multiple weeks (for example: Tour de France). They are allowed to choose 5 athletes of which they think that will win in the races. At the end of every week, the users are allowed to make some changes in their prediction for the next week. Until a certain date (start of the event or week), the users can choose athletes for their prediction. The users can fill in the form and if they change their minds before the start, they are still able to change/update their prediction. But after the start, they can't change it anymore and their input will be used to calculate their score. After the first week (in which their scores are calculate with the input they made in the "PredictionWeek1" model), they will have a change to make a new prediction for the next week ("PredictionWeek2" model) for which they also have the change to update it as much as they want before a certain date. In reality, the input for the second week, will be very similar to the … -
Django - How to make UNIQUE constraint not apply across inherited models?
There's a PlainModel that has attributes like name, color - and a slug, which has to be unique. I want to make my own version of it, an ExtendedModel that also has size. So, I made the model inherit from PlainModel: class ExtendedModel(PlainModel): size = models.IntegerField(...) However, I ran into an issue - because of the way Django model inheritance works, ExtendedModel's database table only has two columns - one for size, and one for a pointer to the original PlainModel table. This means that the unique constraint on slug applies for both models, and there can't be an ExtendedModel with the same slug as an already existing PlainModel. I don't want this behavior, the slugs are only going to ever appear in the context of each model separately (e.g. /products/{slug} and /products/extended/{extended_slug}), so there's no reason to ensure uniqueness across them both. Is it possible to make the constraint apply only for each model respectively? An obvious way would be to have the tables be completely separate, which Django does not seem to support, however. PlainModel would have to be an "Abstract Model", which I can't control. (PlainModel is defined in an external library.) Another way would be to … -
Event management system django booking model and booking function?
How to create a Booking model for event management sys and conform booking msg display to a user with booking id and the user also cancel booking using Django? -
response returning no data django-rest
i don't know whats wrong with this code, previously i was getting assertion error and now this class OrganisationSerializer(ModelSerializer): products = ProductSerializer(many=True) #manytomany field pictures = PicturesSerializer(source ='pictures_set',many=True) #foreign key field class Meta: modal = Organisation fields = ['name','address' ,'products','pictures'] @api_view(['GET']) def get_data(request): data = None query_set = Organisation.objects.all() serialized_data = OrganisationSerializer(data = query_set,many =True) if serialized_data.is_valid(): data = serialized_data.data print(data) return Response(data,status=status.HTTP_200_OK) problem returning no data -
Is a subquery of this kind possible in django?
In sql I could can do something like this - select a, b, c from ( select a, b, c from table_a ) where a = something Is this possible with django? I've only ever used subquery of the type where the primary key of the subquery for example maps to a column of a row in the parent query. I don't want this though on this occasion. Here is the context. I have a query which has annotated column which uses a Window frame. Such an expression cannot be included in a WHERE clause because sql evaluates the where clause first. So it is necessary to perform this query first as a subquery and then use the result like it is its own table. On this parent query I can then filter. -
I want to use the foreign key model in as forms in Django forms
i have two models in django farmer and tractor and i want to use both the models in single form on webpage so that with all the properties as there inputs like name, phone, email , id, price etc. my models.py class Farmer(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone =models.CharField(max_length=10) address = models.TextField(max_length=200) email_address = models.EmailField() def full_name(self): return f"{self.first_name} {self.last_name}" def __str__(self): return self.full_name() class Post(models.Model): tractor_price = models.IntegerField(max_length=150) implimentaion = models.CharField(max_length=50) purchase_date = models.DateField(auto_now=False) slug = models.SlugField(unique=True, db_index=True, null=True,blank=True) tractor_company = models.CharField(max_length=50) tractor_model = models.CharField(max_length=50) description = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now=False) farmer = models.ForeignKey( Farmer, on_delete=models.SET_NULL, null=True, related_name="posts") forms.py from .models import Post,Farmer class TractorForm(ModelForm): class Meta: model = (Post,Farmer) fields = ("tractor_price","implimentaion","purchase_date","tractor_company","tractor_model","description") here I also want to use Farmer model so that i can take input from that also -
uploaded file wont save
Im trying to add a feature to my app that allows users to upload their cv file. I created a model like this: class ResumeDocument(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) cvfile = models.FileField(upload_to="documents", null=True) and created a model form like below: class DocumentForm(forms.ModelForm): class Meta: model = ResumeDocument fields = ['cvfile'] my views.py: def pdf_resume(request): if request.method == 'POST': form = DocumentForm(request.POST or None ,request.FILES or None , instance=request.user) if form.is_valid(): form.save() messages.success(request, f'Done!!!!') return redirect('pdf_resume') else: form = DocumentForm(instance=request.user) context = {'form':form} return render(request, 'reg/pdf_resume.html', context) and finally my HTML: {% if messages %} {% for m in messages %} {{m}} {% endfor %} {% endif %} <form method="POST" action="{% url 'pdf_resume' %}" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ form }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit ">Update</button> </div> </form> when I click Update, it redirects to the page and messages me with success and no error. but the file doesn't get saved in media. however, when I upload the file from admin page it gets uploaded and saved. what am I doing wrong? please help me -
How do I add an extra button next to a specific field in django admin?
I added a button to django admin, but I don't know how to place this button next to the field. admin.py class ProductAdmin(admin.ModelAdmin): readonly_fields = ('created_date', 'updated_date') list_display = ('code', 'category', 'manufacturer', 'quantity', 'price', 'created_date', 'updated_date') list_filter = ('created_date', 'updated_date') change_form_template = "admin/quantity_change_form.html" def response_change(self, request, obj): if '_add-ten' in request.POST: obj.quantity += 10 obj.save() self.message_user(request, 'Добавлено 10 единиц') return HttpResponseRedirect(".") return super().response_change(request, obj) quantity_change_form.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Добавить 10 единиц" name="_add-ten"> </div> {% endblock %} Please, tell me how can I do this? -
How to make embedded document in mongodb using django models?
I have connected mongodb database to django using djongo. I have created 2 apps 'Artist' and 'Album' which have a one to many relation. I want to make embedded document in below structure: { ArtistName : "Ariana", Albums : [ { SerialNo : 1, AlbumName : "Positions" }, { SerialNo : 2, AlbumName : "thank u, next" } ] } How do I write django model in order to get document in the above structure? -
Django RedirectView.as_view always return parameter as lower case
I am using RedirectView.as_view to redirect my local url to external website The external url is case sensitive, however whenever I pass the 'Upper' case parameter to url , seems like RedirectView transfer it to 'lower case' Here is my code: re_path('externlink/(?P<platform>\w+)/(?P<uuid>\w+)/$', RedirectView.as_view(url='https://externlink/%(platform)s/%(uuid)s'), name='firebase') When I pass platform as 'Android' , the '%(platform)s' in RedirectView returned 'android' , it is not what I want, how can I prevent it from auto transfer ?