Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get data from OrderItem object ()
I'm creating an ecommerce app. And right now I'm trying to send the Items to Order with an Email to me. I want to send a message with the items. The email is send with a form to the backend which sends the email over sendmail() to me. Sending the Email works but getting the items in the Email does not. I use some Javascript to handle the sending of the email and updating the cart. Here are my models.py: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) # Nicht nötig image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url 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=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity … -
Converting a 'go home' button from jquery to django
I am a beginning programmer trying to learn Django. I have a 'go home' button that worked fine in jquery: $("#goHomeButton").on('click', function(){ goHome(); }); function goHome() { location.replace("../public/home.html"); I am trying to do the same thing with Django, but after several days (and many online searches) I still have not found a way to do this. I suspect it is as simple in Django as it is in jquery, -
how can i make someone on another network access my website with django
hello guys I'm trying to make another one to access my Django website I host it on my localhost by type python manage.py runserver 0.0.0.0:8000 and i set the ALLOWED_HOSTS = ['*'] when I trying to connect with my IP it's says refused to connect. can someone help me -
django Form values are empty
I have a problem with the home page displaying form values. Although on the search page the values are fine. What could be the problem here? I copied the same form from the search page to the homepage but still, it doesn't work, the values are empty. Any hint is appreciated, thank you! search page: <form action="{% url 'search' %}"> <div class='flx around px'> <input type='text' id='search-keyword' class='search-keyword form-control' placeholder='keywords (pool,garage)'> <select name='area' id='search-area' class='form-control'> <option selected="true" disabled="disabled" selected>Area(All)</option> {% for key,value in area_choices.items %} <option value="{{ key }}" {% if key == values.area %} selected {% endif %}>{{ value }}</option> {% endfor%} </select> </div> <div class='flx around'> <select name="bedrooms" class="form-control"> <option selected="true" disabled="disabled" selected>Bedrooms(All)</option> {% for key,value in bedroom_choices.items %} <option value = "{{ key }}" {% if key == values.bedrooms %} selected {% endif %} >{{ value }}</option> {% endfor %} </select> <select name="price" class="form-control "> <option selected="true" disabled="disabled" selected>Price(All)</option> {% for key,value in price_choices.items %} <option value = "{{ key }}" {% if key == values.price %} selected {% endif %} >{{ value }}</option> {% endfor %} </select> </div> <button type = "submit" class='btn fntmk my2 size'>Search&nbsp;<i class="fas fa-search size"></i></button> </form> home page: <form action="{% url 'search' … -
Getting Image in django teplate from ManyToMany field
It is returning an error : Not Found: /post-detail/6/images/wallpaper002.jpg. I have tried to show image through {{ post_detail.img.all.first.url }} but I could show image in the template, it returns None value. news.html ''' <div class="text-center"> <img class="detail_picture img-thumbnail" src="{{ post_detail.img.all.first }}"> </div> ''' models.py ''' class Pictures(TimestampedModel): img = models.ImageField(upload_to='images') def __str__(self): return str(self.img) class Post(TimestampedModel): title = models.CharField(max_length=128) lang = models.IntegerField(choices=LANGUAGES, default=1) short_description = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) category = models.ManyToManyField(PostCategoies, blank=True) img = models.ManyToManyField(Pictures, blank=True) icon = models.CharField(max_length=128, blank=True, null=True, help_text="Example: fa fa-info") is_active = models.BooleanField(default=True) def __str__(self): return self.title ''' views.py ''' from django.shortcuts import render, redirect from django.contrib import messages from django.views import View from .models import Post, Pictures from django.views.generic import DetailView from . import models from django.shortcuts import get_object_or_404 class HomePageView(View): def get(self, request): posts = Post.objects.all()[:4] context = {'posts': posts} return render(request, 'index.html', context) class PostDetailView(DetailView): context_object_name = "post_detail" model = models.Post template_name = 'news.html' ''' urls.py ''' app_name = 'posts' urlpatterns = [ path('', HomePageView.as_view(), name=""), path('post-detail/<int:pk>/', PostDetailView.as_view(), name="post_detail") ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ''' -
Download file from a django UpdateView template
I'm new to django, and I've a little problem. I've a model with a FileField field, using generic views and ModelForm, I can upload a file to the server. In a modify page using an UpdateView I've a link to my document (e.g. http://127.0.0.1:8000/static-storage/file_name),but if I try to download I get an error page not found. Maybe I need to write an url path but I can't understand how to implement. Could someone give me an help ? Thanks. -
how convert data to string in django templae
I have a trouble in my django template, the below code don't work <td> {% if product.size %} {% for size in product.size.__str()__.split(",") %} <span style="border:1px solid red;"> {{size}} </span> {% endfor %} {% endif %} </td> what can I do to work my code ? -
How to render HTML comment tag in Django
I am writting some html for emails using django, and I want to use the <!--[if !mso]><!--> (required for conditional rendering for outlook desktop client) The problem is when I print the html_content obtained after django render_to_string(), the HTML comment tag is missing. I tried to put my html comment inside a {%autoescape off%}{%endautoescape%} but for some reason it does not work. Anyone having an idea on how to how to achieve my goal here? Thanks -
How to get foreign key value from within refereed class
Say I have a model Foo that needs to refer to a value that can be one of several datatypes. To account for that I have several models for each datatype. Is it possible from within the Foo model to create a getValue method that would return the value from the first value method it can find connected with it? example: class Foo(models.Model): def getValue(self): if self.hasatr('foovalueint'): return self.foovalueint elif self.hasatr('foovaluestring'): return self.foovaluestring elif self.hasatr('foovaluedatetime'): return self.foovaluedatetime class FooValueInt(models.Model): foo = models.OneToOneField(Foo, on_delete=CASCADE, primary_key=True) value = models.IntegerField() class FooValueString(models.Model): foo = models.OneToOneField(Foo, on_delete=CASCADE, primary_key=True) value = models.CharField(max_length=50) class FooValueDateTime(models.Model): foo = models.OneToOneField(Foo, on_delete=CASCADE, primary_key=True) value = models.DateTimeField() Or is there a better way to solve this multiple datatype issue? -
queryset average values of column
I´m trying to make an queryset with Django but I have no clue how to do that. The query that I want to do is: select format(avg(progress),1) as progreso from c_lp_view where user_id = 21 and c_id = 1; Now in Django my queryset looks like this: CLpView.objects.filter(user_id = user_id).filter(c_id__in=lRels).aggregate(avg_progress=Avg('progress')) Thanks for the help -
I am a beginner and I was trying to start local django server [closed]
D:\Talha\lecture3>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python\Python39\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(check_resolver(pattern)) File "C:\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'hello.urls' from 'D:\Talha\lecture3\hello\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Upload images to django from axios
I am trying to send images from axios client to server with django. At completeInfo function at views.py when I set a print(request.FILES) <MultiValueDict: {'imagen': [<InMemoryUploadedFile: blob (text/html)>]}> So what instinct is that the image is empty. Also the media folder on the django server is never created. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'media') STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'static-only') STATICFILES_DIRS = ( os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'static'), ) urls.py urlpatterns = [ path('completarinfo/',completeInfo) ] Models.py class clientData(models.Model): user=models.ForeignKey(client, on_delete=models.CASCADE, null=True) client_picture=models.ImageField(default=None, upload_to='images/') def __str__(self): return selft.user.user forms.py from django import forms from .models import * class clientDataForm(forms.ModelForm): class Meta: model = clientData fields = ['name', 'client_picture'] views.py @csrf_exempt def completeInfo (request): print(request.FILES) if request.method == 'POST': form = clientDataForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('successfully uploaded') else: form = clientDataForm() return HttpResponse("imagen") This is the axios code: const axios = require('axios'); axios({ url:url, method:'POST', headers: { "content-type": "multipart/form-data" }, data:formData }).then(function(res: any){ console.log(res) }).catch((error: any) =>{ console.log(error) //Network error comes in }); Someone could help me? Thanks in advance -
Many fields. Validate them so that errors should be next to problematic fields
Django 3.1.6 class RasterImageForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img_fields = self._get_img_fields() def _get_img_fields(self): result = [field[0] for field in self.fields.items() if "img" in field[0]] return result def _validate_equality_of_file_name_and_field_name(self): for img_field in self.img_fields: val = self.cleaned_data[img_field] full_file_name = os.path.basename(val.name) full_file_name_without_ext = os.path.splitext(full_file_name)[0] if full_file_name_without_ext != img_field: raise ValidationError( '%(filename)s: ' + str(_('File name is incorrect. It must coincide with the field name.')), params={"filename": full_file_name_without_ext}) def clean(self): self._validate_equality_of_file_name_and_field_name() I want to force users to name uploaded files exactly as the field name. This code works. But the error is shown at the top of the form. There are a lot of such fields. Say, 20-30. If if there were a couple of fields, I'd use clean_(). But I can't manage it with so many fields. Could you help me organize form validation so that an error should be not next to problematic fields. -
How to return username instead of ID
Before calling this a repeat question please have a look at my code. I have a Blog Model and here is the Favourites part of it: class Fav(models.Model) : post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: unique_together = ('post', 'user') def __str__(self) : return str(self.user.username) My serializer looks like this: class FavSerializer(serializers.ModelSerializer): class Meta: model = Fav fields = ['post', 'user'] I assumed because of the __str__ part, that this API will return the username but instead it returns only the user_id. How can I return the username? -
Django Display Multiple Values from Dependent Dropdown
I'm using Python 3.8 & Django 3.0 and need multiple values (volume & volume size) to go to a dependent dropdown. I've been able to populate the dependent dropdown with a single value (volume). I found posts that work with a dropdown sending multiple values from django dropdown and retrieve multiple values from Dropdown menu in Django but these don't work with a dependent dropdown. Here is my code: models.py class ArrayVolumes(models.Model): array = models.ForeignKey(Array, on_delete=models.CASCADE) volume = models.CharField(max_length=50, default=None) vol_size = models.CharField(max_length=10, default=None) def __str__(self): return self.volume views.py from .models import ArrayVolumes def load_volumes(request): array_id = request.GET.get('array') vols = ArrayVolumes.objects.filter(array_id=array_id).order_by('volume') # vol_size = ArrayVolumes.objects.filter(array_id=array_id).value('vol_size') return render(request, 'pure/volume_dropdown_list_options.html', {'vols': vols}) urls.py urlpatterns = [ path('ajax/load-volumes/', views.load_volumes, name='ajax_load_volumes'), ] dropdown_list_options.html <option value="">---------</option> {% for vol, size in vols %} <option value="{{ vol.pk }}#{{ size }}">{{ vol.volume }} ( {{ size.vol_size }} )</option> {% endfor %} main.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> {% crispy form form.helper %} <form method="post" id=volForm data-volumes-url="{% url 'ajax_load_volumes' %}" novalidate> <br><br> <h4>{{ note }}</h4> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_array").change(function () { var url = $("#volForm").attr("data-volumes-url"); var arrayId = $(this).val(); $.ajax({ url: url, data: { 'array': arrayId }, … -
Django - how to create multiple select (on CreateView) to a foreign key on the related model?
I have those two models: Student class Student(models.Model): name = models.CharField(max_length=50, default='') class = models.ForeignKey(Class, related_name='students', on_delete=models.SET_NULL, blank=True, null=True) Class class Class(models.Model): code = models.CharField(primary_key=True,verbose_name='Code', max_length=50) When the user creates a new Class, I need them to be able to choose the students that it's going to be in the class. And they should be able to add students later. How would I create this view? -
UniqueValidator in drf
my model has a field: name = models.CharField(max_length=255, blank=True, null=True) in serializer, I am trying to raise a unique validation error name = serializers.CharField(validators=[UniqueValidator(queryset=Department.objects.all(), message=("Name already exists"))]) but it does not work, because the data comes to the serializer in this format name: {en: "drink"} I can raise an error in the create method, but I want to raise the error on the serializer. appreciate any advice. I'm in a hurry. sorry for any inconvenience. Thanks in advance -
JSON parsing using Python Django
I am trying to create dynamic database tables based on user import file. I have done excel import using react and store the json data(below json data) to my db. I have creating a restapi with function, if i received datum from user wants to create dynamic tables and data insertion. I have tried without rest with model json data its working fine. Request your suggestion please. I have received following json data from react. { "tableInfo": { "dbName": "ws1_kalairaman_sv", "tableData": [ [ { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker1": "722410010726613", "currency": 16687, "datetime": "01/01/2021 02:01:00" }, { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker1": "722410010729091", "currency": 16687, "datetime": "01/01/2021 02:01:00" } ], [ { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker2": "722410010726613", "currency": 16687, "datetime": "01/01/2021 02:01:00" }, { "date": "01/01/2021", "fewr": "SCRATCH", "gerw": "99999", "numbr": "45", "ticker2": "722410010729091", "currency": 16687, "datetime": "01/01/2021 02:01:00" } ] ], "tableName": [ "Sheet8", "Sheet9" ], "tableColumn": [ [ { "type": "CHAR (60)", "field": "ticker1", "title": "ticker1", "width": "auto", "hidden": False, "tooltip": "ticker1", "cellStyle": { "whiteSpace": "nowrap" } }, { "type": "CHAR (60)", "field": "gerw", "title": "gerw", "width": "auto", "hidden": False, "tooltip": "gerw", "cellStyle": { "whiteSpace": … -
What does JWT being stateless really means?
Hi and thanks in advance, I've successfully setup JWT authentication using django-rest-framework-simplejwt and React but I'm still very confused about the advantages and specifically database hits. I'm using simplejwt with ROTATE_REFRESH_TOKENS': True 'BLACKLIST_AFTER_ROTATION': True, when my access_token expire I ask for a new one through /api/token/refresh and it blacklist old tokens, I'm using axios interceptors to perform that automatically. But in my understanding the benefits of JWt is that they are stateless, meaning I don't have to hit the user database table everytime I want to make an a request that needs authentication permission. The problem is even with a simple view like this : class IsConnecteddAPI(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, *args, **kwargs): data = "You seem to be connected" return Response(data, status=status.HTTP_200_OK) using django-silk I see that it still performs 1 query to my user table when I call it with a valid access token, is that normal ? If so why do we say that JWT are stateless ? I'm really confused. That's my axios code if needed : import axios from "axios"; const baseURL = "http://localhost:5000"; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem("accesstoken") ? "JWT " + localStorage.getItem("accesstoken") : null, … -
no user matches the given query
hi everyone i am building a ecommerce webapp where everything is done except this. i want the user to get the product that it posted by itself my views.py file is: class UserPostListView(ListView): model = Product template_name = 'product/user-posts.html' def get_queryset(self): user = get_object_or_404(User, email=self.kwargs.get('email')) return Product.objects.filter(user=user , is_staff=True).order_by('-date_posted') my urls.py file is: urlpatterns = [ # path('featured/' , ProductFeaturedListView.as_view()), #path('featured/<int:pk>' , ProductFeaturedDetailView.as_view()), path('' , ProductListView.as_view(), name= "list"), path('new/' , ProductCreateView.as_view() , name="product-create"), path('<slug:slug>/update/' , ProductUpdateView.as_view() , name="product-update"), path('<slug:slug>/delete/' , ProductDeleteView.as_view() , name="product-delete"), #path('product-fbv/' , product_list_view), #path('product/<int:pk>' , ProductDetailView.as_view()), path('<slug:slug>/comment' , CommentCreateView.as_view() , name="add-comment"), path('<slug:slug>' , ProductDetailSlugView.as_view() , name="detail"), path('userpost/', UserPostListView.as_view(), name='user-post'), # path('product-fbv/<int:pk>' , product_detail_view), ] and my user model is: class User(AbstractBaseUser): email = models.EmailField(max_length=255 ,unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non super user admin = models.BooleanField(default=False) #superuser time_stamp = models.DateTimeField(auto_now_add=True) and it give me the error that no user matches the given query -
Passing selected arguments with a multi-select to a page in Django
I have a webpage with elements that I select and that serve to make calculations and give results in another page. However, I don't seem to be able to get them when I press the send button... In fact, I send my elements from quiz2.html: <form action = "/getmatch" method="POST"> {% for keyword in keywords %} <div class="elements"> <ul class="items col-xs-6 col-sm-3 col-md-3 col-lg-3"> <li class="item"> <label> <input class="item-check" name="keywords[]" type="checkbox" value= {{ keyword.title }} /> <div class="item-name">{{ keyword.title }}</div> </label> </li> </ul> </div> {% endfor %} {% csrf_token %} <button type="submit">Envoyer</button> </form> And here is the getmatch() function in views.py: def quiz(request): with open('todo/templates/todo/data/keywords.json') as f: keywords = json.load(f) if request.method == 'POST': form = QuizForm(request.POST) if form.is_valid(): keywords_selected = form.cleaned_data['keywords_selected'] print("keywords_selected: ", keywords_selected) form = QuizForm() return render(request, 'todo/quiz2.html', {'form': form, 'keywords': keywords}) def getmatch(request): if request.method == 'POST': result = request.GET.get('keywords[]') print("result: ", result) However, it returns None en result -
Postgres data_type modification in Django
The web application I'm working on in Django ran into a bug when I attempted modifying the data type of a field(column). I got some advice to drop/delete the table which didn't end up very well. Now I'm stuck. I tried creating a new table manually but its still giving me the same error. I tried changing the name of the previous table from its models.py, but that didn't work either. The website is giving me this error, 'Server Error (500),' as it is in production mode and the debug is set to false. I've tried. 'python manage.py makemigrations,' but it says no changes. Also, 'python manage.py migrate,' but that gives an error. -
Django can't create sqlite database in app directory, only create default one
Here is the DATABASES dictionary in settings.py in a django project root: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'tinysteps': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / "project2/tinysteps.sqlite3" } } I want tinysteps database to be initialized in project2 app directory, but only default database is created, also I've checked the NAME and it's ok, don't get why this is happened -
django template access url kwargs
I want to access kwargs with their names in url from "django template tags". for example i have a url as below: path('sample_view/<slug:my_custom_slug>/', views.sample_view.as_view(), name='sample_view') what should I write in my html template to access "my_custom_slug"? -
Python braincube-connector date slicing
I have been successful in obtaining data via the package. I am now attempting to retrieve data based on a desired date range. The methods provided with the braincube_connector pypi project description site do not work properly to my knowledge. The parse_date parameter does not seem to work. Setting the condition to true using parameters.set_parameter({"parse_date": True}) does not actually return dates when using .get_data(). There is a timestamp variable in the data set I am trying to obtain. To my knowledge I should then be able to use a filter with the “BETWEEN” keyword to retrieve the data in the desired date range. The timestamp data is of a “DATETIME” type according to .get_type(). When I parse a datetime element the following error appears: TypeError: Object of type datetime is not JSON serializable I then attempted to use the DjangoJSONEncoder to no avail and various other methods of parsing a start and end timestamp.