Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to upload video file with timestamp in Django Rest Framework?
Is there any way in DRF or just python to post mp4 video with set up timestamp? For example i want to post a video that will start at 10 second if user will display it on frontend. -
Add cluster information to table after KMeans
I am building a django application that uses Kmeans to cluster a particular table in the database. I'd like to add the clusters to the table in the database after the clustering process is done. Here is a sample of the code. This code runs every time someone registers This prints the data frame adding an extra column to show which cluster they belong to. How would I go about it if I want to add those clusters to the original data frame, the table in the database. -
I get AnonymusUser in Ajax GET request DJANGO
I am working in a Django application and I need to get some data with a GET request from a template. I have set up a AJAX get request as follows: $.ajax({ type: 'GET', dataType: "json", url: "https://www.url.com/enpd/var1/var2/var3", xhrFields: { withCredentials: true }, success: function(obj) { ... }, error: function(data) { ... } }); And in the views.py I have the following: @login_required(login_url='/login') def getReq(request, var1, var2, var3): user = request.user if user.is_authenticated: ... else: return HttpResponse({user}) And I always get the request user as "AnonymusUser". It's like the AJAX get request is not sending the user details in the request. Why is that happening? I have read through many posts and nothing helped... PD: I created a custom user, don't know if that may cause any issue? -
Django django-filters ipaddress mysql
filter for ip not working properly model.py class Network(models.Model): start_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) end_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) filters.py class NetworkFilter(django_filters.FilterSet): f_by_address = django_filters.CharFilter(method='filter_by_address', label="BY ADDRESS") def filter_by_address(self, queryset, name, value): return queryset.filter(start_ip_address__lt=value, end_ip_address__gt=value) class Meta: model = Network fields = ['id', 'start_ip_address',] filter by address result to SELECT `network_network`.`id`, start_ip_address, `network_network`.`end_ip_address` FROM `network_network` WHERE (`network_network`.`end_ip_address` > 10.172.148.12 AND `network_network`.`start_ip_address` < 10.172.148.12) ORDER BY `network_network`.`id` ASC my table doesn contains so much records, but even now I got into the troubles. mysql> SELECT start_ip_address, end_ip_address from network_network where (end_ip_address > '10.172.148.12' AND start_ip_address < '10.172.148.12'); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.14.1 | 10.172.15.254 | | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 2 rows in set (0.01 sec) mysql> SELECT start_ip_address, end_ip_address FROM network_network WHERE (INET_ATON("10.172.148.12") BETWEEN INET_ATON(start_ip_address) AND INET_ATON(end_ip_address)); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 1 row in set (0.01 sec) Not sure what to do in order to make this filter working accurate over django ORM. Can't use raw SQL as example is simplified. -
Large JSON data over POST request
I have a system working as a swarm, with a lot of independent devices running Django and a main Queen (running Django as well) gathering data from the swam. Each device from the swarm is sending the new data to the queen using a POST request with the data in a json. Each data recorded in the device is then updated to mark it as sent to the queen and doesn't need to be resent later. the problem is that each dataset is about 10 MB and I am getting a timeout error while processing the post request. The solution I got at the moment is far from optimal: I split the upload in batches of 500 records and send several post requests. After each successful upload, I update each record 1 by 1. This solution has some performance issues. Things I would need to improve: manage to send all data in 1 single request Reduce the data volume to be sent Update the data faster on each device after so the questions are: Is there a way to keep the post request alive for longer? I am thinking of using gzip to send the data. Is it something to … -
how to view the extension file mention below?
I would like to view (.tiff .ecw) extension files, orthoimage [large files] through online with map integration using python JavaScript ...any one can help or suggest some to create the Web Apps -
ImportError: cannot import name 'Profile' from partially initialized module 'profiles.models' (most likely due to a circular import)
I am importing Profile from profiles.models into meta.models, but showing the subject error. Can't find cutom solution, even though there are similar problems with different solutions out there but not working in my case. Here is my profiles.models from django.db import models from django.contrib.auth.models import User from meta.models import Designation class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, help_text = 'Foreign Key From User') avatar = models.ImageField(upload_to='avatars', default='no_picture.png') designation = models.ForeignKey(Designation, on_delete = models.CASCADE, null=True) def __str__(self): return str(self.user) Here is my meta.models, where i am importing from profiles.models from django.db import models from profiles.models import Profile class Designation(models.Model): DesignationName = models.CharField(max_length = 20, blank=True,null= True) DesignationScale = models.PositiveIntegerField() def __str__(self): return str(self.DesignationName) class DutyPlaceSensitivity(models.Model): sensitivity = models.CharField(max_length = 12, blank=True, null = True) def __str__(self): return str(self.sensitivity) class DutyPlaces(models.Model): DutyPlaceName = models.CharField(max_length =20, blank = True, null = True) sensitivity = models.ForeignKey(DutyPlaceSensitivity, on_delete=models.CASCADE) class ActingAs(models.Model): acting_as_title = models.CharField(max_length = 12) def __str__(self): return str(self.acting_as_title) class PlaceOfPosting(models.Model): UserProfile = models.OneToOneField(Profile, on_delete=models.CASCADE) acting_as = models.ForeignKey(ActingAs, on_delete = models.CASCADE) def __str__(self): return f"{self.UserProfile} - {self.acting_as}" class TaskType(models.Model): taskTypeName = models.CharField(max_length=20) taskDescription = models.TextField(null = True, blank=True) def __str__(self): return str(self.taskTypeName) class TaskPriority(models.Model): priority_title = models.CharField(max_length = 12) def __str__(self): return str(self.priority_title) class Tasks(models.Model): task_name … -
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?