Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Move Settings folder to settings.py
Recently I received a started project with Django and Python, the project is constantly giving us errors, but some of them are probably because the last programmer made a directory of settings instead a settings.py. My question is if there is some way of move all this .py in the settings folder to a new python file called settings.py, to optimize it. Thanks! -
Django - Unable to find object using pk (Matching query DoesNotExist)
Whenever I try to create a "Tour" for a "User" I get this error: "DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist." Specifically the problems seems to come from this line of code: user = User.objects.get(pk=pk) models.py class Tour(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tour_date = models.DateField(default=date.today) tour_fans = models.ForeignKey(FanAccount, on_delete=models.PROTECT) def __str__(self): return f"{self.user} del {self.tour_date}" views.py def tour_new(request, pk): user = User.objects.get(pk=pk) if request.method == "POST": form = TourForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.tour_fans = request.user form.instance.user = user instance.save() form.save() return render(request, "tour.html", {"form": TourForm(), "success": True}) else: form = TourForm() return render(request, "tour.html", {"form": form}) For "User" I'm using a custom Primary Key (ShortUUID). I'm new to Python and Django so it may be something easily solvable, but after hours of attempts I seem unable to solve it. -
Django best way to stream video to your frontend (php or react.js)
I want to make a website for watching videos like vimeo or youtube but i have no idea how to watch/stream the videos on the frontend from my django backend. So i have the videos in my database how will someone watch them from his browser -
Edit a foreign key's fields in a template
I'm unsure of how I can edit a foreign key's fields from the template of another model - my changes do not update the model on post, see below. models class Projects(models.Model): name = models.CharField(max_length=250) class Current(models.Model): fk_user = models.OneToOneField(User, on_delete=models.CASCADE) fk_project = models.ForeignKey(projects, default='1', on_delete=models.CASCADE) views class current(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Current fields = [ 'fk_project' ] template_name = 'users/current.html' context_object_name = 'current' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False current.html <form method="POST">{% csrf_token %} <input type="text" value="{{ current.fk_project.name }}"/> <button type="submit">post</button> -
Django UnicodeEncodeError, can't encode special czech characters
i built application in django that gives the user a table of employees, it works okay to a point when i want to filter this table - basically I'm sending HTTP GET request with a name or part of a name as one of the parameters. Problem is, I'm czech and we use weird characters in our names like Ř/ř or Ě/ě, i cannot filter these people because there's an encoding problem. UnicodeEncodeError: 'latin-1' codec can't encode character '\u0161' in position 324: ordinal not in range(256) My understanding is that django is trying to use latin-1 which doesn't contain those characters, so it cannot handle them. How would i change that? I'm lost, please help me, thank you. This is my view function i use: def track1(request): year = int(request.COOKIES.get('year', str(date.today().year))) month = int(request.COOKIES.get('month', str(date.today().month - 1))) name = request.COOKIES.get('name', '') project = request.COOKIES.get('project', '') if month == 0: month = 12 sql_query = """select p.name project, p.id projectid, i.title issue, i.id issueid, u.id userid, u.name, replace(ROUND(t.time_spent/3600.0, 1)::text, '.', ',') as spent, TO_CHAR(t.spent_at + interval '2h', 'dd.mm.yyyy HH24:MI:SS') date_spent, substring(n.note for 300) note from issues i left join projects p on p.id = i.project_id left join timelogs t on t.issue_id … -
In Python Django , in my views I cannot access my templates outside of the app which my views are in .How do I do that?
I have simplified the code in order to make it easier to replicate the issue. I have tried putting my templates folder in the same app as the views and that works fine. But when I place the templates folder outside off it , it cant seem to reach it. Base urls code : from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] project urls code : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] This is the code for my settings (relevant parts): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'personal_site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Passing a related field ID to an API endpoint in Django REST
I will try my best to make this easy to understand: [ { "id": 1, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet.pdf", "module": 3 }, { "id": 2, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet_Pck5SQy.pdf", "module": 5 }, { "id": 3, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/Trina_670Wp_from_Gamechange_abXvA3H.pdf", "module": 5 } ] Basically, if I can go to an endpoint using the id like this: http://127.0.0.1:8000/store/cable_datasheets/1/. Result would be this: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 1, "data_sheet": "http://127.0.0.1:27038/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet.pdf", "module": 3 } But am unable to achieve the same using the module id. say for instance: http://127.0.0.1:8000/store/cable_datasheets/5/ results in this: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } the module happens to be a related field I have no idea how I can use it and pass it as part of the queryset. My models.py: class Cable(models.Model): id = models.BigAutoField(primary_key=True) def __str__(self): return f"Cable ({self.tag}, {self.manufacturer}, {self.model})" def supports_arch(self, arch): return self.architecture[arch] == '1' class CableDataSheet(models.Model): module = models.ForeignKey(Cable, on_delete=models.CASCADE, related_name='data_sheets') data_sheet = models.FileField( upload_to='store/data_sheets', validators=[ validate_file_size, FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']) ] ) my views.py: class CableViewSet(ModelViewSet): http_method_names = ['get', 'head', 'options'] serializer_class = CableSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] permission_classes = [IsApplicationOrAdmin] def get_queryset(self): queryset = Cable.objects.all() arch = … -
Django how can i find_all book by сategory = None
How can i take all books when i pass None, cuz in Ruby if i write something like that Book.where(category = None) => Give all Books I try this Book.objects.filter(category = None) => empty QuerySet In general, there is some method in django that covers this logic -
have an event handler read a value in a html list and display some html on this condition
Apologies my experience with html and javascript is limited so I am trying to figure out the best way to do this. Essentially I am dealing with some html that creates a form for users to send messages. The form allows the selection of the subject and text to be input. <td>Subject</td> <td> <select id="subject"> <option selected="selected" value="none">Please select a subject</option> {% for subject in MESSAGE_SUBJECTS %} <option value="{{subject}}">{{subject}}</option> {% endfor %} </select> <!-- <input type="text" id="subject" size="80" value='No Subject' onfocus="if(this.value==this.defaultValue)this.value='';" name="subject" /> --> </td> </tr> <tr> <td>Message</td> <td><textarea id="newmessage" cols="80" rows="6" onfocus="if(this.value==this.defaultValue)this.value='';" name="newmessage">Please type your message here</textarea></td> </tr> Without going into too much detail the subjects are just a series of strings. For the purposes of this we can just call them 'sub1' and 'sub2'. I want to make it so the textarea only appears when 'sub1' is selected from the dropdown list. I believe a javascript event handler is the way to go here and there is an associated javascript file with some functions but I can't figure out what the syntax would look like. I assume it is something like: function conditionalMessage() { if( subject == "sub2" ) { //some code that defines displaying text to explain … -
python -m django startproject vs django-admin startproject
hi everyone what is difference between python -m django startproject and django-admin startproject if it have any different so which one is better for use ? -
CustomUser and Roles ManyToMany Relation in models shows in RoleAdmin and CustomUserAdmin
Models.py: class Role(models.Model): id = models.AutoField(primary_key=True, null=False) name = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return str(self.name) class CustomUser(AbstractUser): role = models.ManyToManyField(Role, blank=True) Admin.py: class CustomUserAdmin(UserAdmin): fieldsets = (*UserAdmin.fieldsets, ("Roles", {"fields": ("role",)})) admin.site.register(CustomUser, CustomUserAdmin) CustomUserAdmin.list_display = ( "username", "email", "first_name", "last_name", "is_staff", "is_active", ) class CustomUserInLine(admin.StackedInline): model = CustomUser.role.through class RoleAdmin(admin.ModelAdmin): list_filter = ("name",) list_display = ("id", "name", ) inlines = [CustomUserInLine,] admin.site.register(Role, RoleAdmin) I would like to change admin TabularInLine rendered Structure with admin.StackedInLine adding inlines=[CustomerInLines] into RoleAdmin: to admin.StackedInLine proper render: -
Append to queryset object in Django
My Django Model: class Job(models.Model): title = models.CharField(_('Job Title'),max_length=150, blank=True, default="") description = models.CharField(_('Description'), max_length=250, blank=True, default="") user = models.ForeignKey('User', verbose_name="User", on_delete=models.CASCADE, null=True) def __str__(self): return self.title I have a queryset of django objects: >>> jobs = Job.objects.all() <QuerySet [<Job: university>, <Job: companies>, <Job: inside>, <Job: outside>]> I want to iterate over them, and update their dict (merge their dict with a new dict) with a key that they don't have. Is it possible to do something like this? for job in jobs: job.update('new_key' : 'new_value') #This returns error To obtain the job object with the following keys: title, description, user, new_value. Why do I want to do this? To be easier to iterate over those values that are correlated with jobs with only one for loop in the templates. I don't want to use Job.objects.all().values() because that way I can't do job.user.name in the templates and get user name or user information. -
Trying to show created date of order on another view i get KeyERROR "list_id"
Been trying to show the created_date of the customer order on another view, kindly help much appreciated. ListListView class ListListView(generic.ListView): model = HBTYList template_name = "accounts/modals/nomodal/index.html" paginate_by = 3 def get_queryset(self): qs = self.model.objects.all().order_by('-id') p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset()) return context ItemListView class ItemListView(ListView): model = HBTYItem template_name = "accounts/modals/nomodal/todo_list.html" paginate_by = 2 ordering = ['id'] def get_queryset(self): return HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) def get_context_data(self): context = super().get_context_data() context['t_sum'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]).aggregate(Sum('price')) context["hbty_list"] = HBTYList.objects.get(id=self.kwargs["list_id"]) return context Urls.py path("hbtylist/", views.ListListView.as_view(), name="hbtylist"), path("list/<int:list_id>/", views.ItemListView.as_view(), name="list"), # CRUD URL FOR HBTYCUSTOMERS path("list/add/", views.ListCreate.as_view(), name="list-add"), path("list/<int:pk>/delete/", views.ListDelete.as_view(), name="list-delete"), # CRUD URL FOR HBTYCUSTOMERSAPPOINMENTS path("list/<int:list_id>/item/add/", views.ItemCreate.as_view(),name="item-add",), path("list/<int:list_id>/item/<int:pk>/",views.ItemUpdate.as_view(),name="item-update",), path("list/<int:list_id>/item/<int:pk>/delete/",views.ItemDelete.as_view(),name="item-delete",), Thank You For The Help. -
Django Error: 'dict' object has no attribute 'availability'
I have a cart view where I'm trying to check if the products added to the cart have even one item in the list that has product.availability set to False and work accordingly in Template, the problem is with accessing the product availability in cart object list, So how do I check the availability of products that people added to cart? P.S I shortened the code for utils, I'll add more if needed for understanding Model class Product(models.Model): availability = models.BooleanField() Utils def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} items = [] for i in cart: try: product = Product.objects.get(id=i) item = { 'product':{ 'id':product.id, 'name':product.name, 'final_price':product.final_price, 'image_URL':product.image_URL, 'availability':product.availability, }, } items.append(item) except: pass return {"items": items} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: cookieData = cookieCart(request) items = cookieData['items'] return {'items':items} Views def cart(request): data = cartData(request) #products added to cart items = data['items'] #Checking if even one product added to cart has availability set to False available = all(x.availability for x in items) context = {'items': items, 'available': available} Template <p>{{items.product.name}}</p> {% if available %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} … -
Manage.py runserver -> Returns "manage.py : The term 'manage.py' is not recognized as the name of a cmdlet"
I am new to programming and i am currently doing the programming with Mosh: Mastering Python course. I am trying to make a web application with Django. When I write the command "Manage.py runserver" in my terminal I get the following message: "manage.py : The term 'manage.py' is not recognized as the name of a cmdlet [...]". How do i fix this? -
Is there a way to automate the process of django templates translation?
I would like to translate all my Django templates, Which means I need to go through every word or sentence in my templates and add the code _() to it. For ex This: <h1>hello</h1> Will be this: <h1>_("hello")</h1> But I would like to do it automatically since I have many many sentences, It doesn't matter if it's software or an online tool or a text editor that can automate the process. -
Error 404 NOT FOUND occurs when trying to GET from django
I am getting the 404 error Failed to load resource: the server responded with a status of 404 (Not Found) 127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D:1 my code for product/models.py: from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category (models.Model): name = models.CharField(max_length=255) slug = models.SlugField(null=True) class Meta: ordering = ('name',) def __str__(self) : return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField(null=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self) : return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}/' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if self.thumbnail: return 'http://127.0.0.1:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.make_thumbnail(self.image) self.save() return 'http://127.0.0.1:8000' + self.thumbnail.url else: return '' def make_thumbnail(self, image, size=(300, 200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail the product page,product.vue code: <template> <div class="page-product"> <div class="column is-multiline"> <div class="column is-9"> <figure class="image mb-6"> <img v-bind:src="product.get_image"> </figure> <h1 class="title">{{ product.name }}</h1> <p>{{ product.description }}</p> </div> <div class="column is-3"> <h2 class="subtitle">Information</h2> <p><strong>Price: </strong>Ksh{{ … -
How to Populate ImageFIeld Value when Adding Model Instance in Django Admin with Query Param?
I have a model like this: class MyModel(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images') When going to http://127.0.0.1:8000/admin/myapp/mymodel/add, I can add a new instance of MyModel. I know that there is a way to populate the name field by adding the following query param: ?name=myname, but when I try to do ?image=images%2Fmyimage.jpg, it doesn't work. I also tried ?image__url=images%2Fmyimage.jpg but it didn't work either. Does anyone know how to populate an ImageField value with a query paramater when adding a new model instance in Django admin? -
Python Package gets removed when azure app restarts
I have uploaded Django app on azure server web app using Zip Deploy. After deploying it gives error that "sndlibrary not found" so i need to go to ssh and install it manually by using command "apt update && apt-get -y install libsndfile1-dev".So The problem is that whenever the app gets restarted it again shows the same error and i again need to install the package from ssh.The package does not persist on restart.So is there any way to persist the package on app restart? I have also tried using startup.sh script on the wwwroot path but when run it shows error that "could not locate the package". -
Djnago send mail not working, also not showing any error
Settings.py DEFAULT_FROM_EMAIL = 'testing.email2908@gmail.com' SERVER_EMAIL = 'testing.email2908@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'testing.email2908@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAILL_USE_TLS = True views.py print('Helloo') send_mail( 'Testing', 'Hi', 'testing.email2908@gmail.com', ['xyz@gmail.com'], #my personal gmail id fail_silently=False, ) print('Hiiii') When i run this code, only Helloo is getting printed, I've imported send_mail as well,tried using smtplib as well but that was giving smpt auth extension error so i'm trying send_mail method but it also doesn't seem to work, don't know what is the exact issue. -
Return decimal fields from list
I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal def my_generator(): yield amount, name def get_amount(obj): p = list() gen = obj.my_generator() for i in gen: p.append(i) return p get_amount() now it is returning [(Decimal('1950.00'), '06/16/2020'), (Decimal('4500.00'), '06/16/2020')] I want the list to be returned as formatted how can i do that '${:0,.2f}'.format(Decimal('1950.00') which is in my list) so the end result would be like $1,950.00 if the the return has two yields it should return like. $1,950.00, $4,500.00 -
Remove '*' from required fields
I have a form in django in which there are some demographics. I want those fields to be required but if I set them as such from the model I get the * special character after every field label in the form. How do i remove that character but still have those fields as required? My model fields: location = models.CharField(max_length=254, choices=COUNTRIES, null=True) homeowner = models.CharField(max_length=254, choices=HOME_STATUS, null=True, blank=True) form: class UserDemographicsForm(forms.ModelForm): class Meta: model = Demographics fields = ['age', 'sex', 'yearly_income', 'employment', 'location', 'homeowner', 'education', 'home_adults', 'home_children'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_tag = False and the result i try to omit : -
How to restrict users to only type English in Django forms?
i have a model form with field (forms.textinput) and i want users just can type english in this field and if they want type with another language get a error thank you -
Why is my linode domain not working in my browser?
I just bought a domain to fit with my new web application which is hosted on a linode. I proceeded to the configuration on the domain manage panel by setting the server adresses to "ns1.linode.com", "ns2.linode.com",.... and i correctly added the domain on linode with new AAAA/A. I know that this changes can take several hours to be applied, but now, when I enter the domain in my browser, it displays the message " does not allow connection". I wanted to know if this result was a normal part of the step that should happen during the configuration and i just have to wait a few more hours, or if i did something wrong somewhere. (i precise that the linode is running correctly, when i enter the IP adress on the 8000 port it works, the problem is just with the domain). Could the problem happen because on my domain setting pannel, i only have 4 fields for the adresses so i can not enter de fivth "ns5.linode.com" ? Thanks a lot for your answer. -
How to make a (Dapp) with Django?
How to integrate Django with blockchain and build a decentralized application? Are there any packages for this? Is there a tutorial about this?