Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Exception on Pre-existent Database: Cannot resolve keyword 'user' into field. Choices are: organization_id
I'm currently building Django model classes for an already existing database. We have three tables: Organization, User, and UserOrganizationMap. This is because there is a Many-to-Many relationship between the tables Organization and User (a user can belong to multiple organizations and an organization has multiple users). I had to explicitly create the UserOrganizationMap model class since it exists in the database already and I cannot use the one that would be created by Django. This is the code to create those models: This the code to create those models: class Organization(models.Model): organization_id = models.UUIDField(primary_key=True) organization_name = models.TextField() class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'organization' class User(models.Model): user_id = models.UUIDField(primary_key=True) user_name = models.CharField() organizations = models.ManyToManyField( to=Organization, through='UserOrganizationMap', through_fields=('fk_user', 'fk_organization'), ) class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'user' class UserOrganizationMap(models.Model): fk_user = models.ForeignKey( User, on_delete=models.CASCADE, db_column='user_id',) fk_organization = models.ForeignKey( Organization, on_delete=models.CASCADE, db_column='organization_id',) class Meta: app_label = 'myapp' # each model will require this managed = False db_table = 'user_organization_map' When I tried to iterate over the users I get the following Error users = User.objects.all() for user in users: print(user.user_id) print(user.organizations.all()) … -
How to get a fjango file instance from pyexcelerate workbook?
I have recently checked the pyexcelerate to help improve the performace of exporting a pandas data frame to excel file i have the following code values = [my_df.columns] + list(my_df.values) wb = Workbook() wb.new_sheet('outputs', data=values) wb.save('outputfile.xlsx') I have a django model that has a filefield into it how can i save the generated wb to a django file field ? -
Http Response Python
like the response.json() does not display anything but on the other hand the response.text displays the results how to loop through response.text Exemple de mon code def api: url = 'http://api-content/product/GetProduct' x = requests.get(url) content=x.text "produits":[{ "des":"blaa", "cont":"sdf" }] Merci de votre aide -
How can i auto update my database in django rest?
I have to make a order status, where there are 3 columns: orderId, item_name, status. An order can have multiple items, and every item can have diferemt status. So what i have to do is an endpoint that return the status of the order. Example: if the order 1, has 3 items, and 2 of the items have the status: "Shipped" and the other is "Pending", the expected result of that order status is "Pending", because not all the item have been shipped. models.py from django.db import models import requests class OrderStatus(models.Model): choice = (('SHIPPED', 'SHIPPED'), ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED')) OrderNumber = models.CharField(max_length=255, unique=True) status = models.CharField(max_length=255, choices=choice) def __str__(self): return self.OrderNumber class OrderItems(models.Model): id = models.AutoField(primary_key=True) choice = (('SHIPPED', 'SHIPPED'), ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED')) itemName = models.CharField(max_length=255) OrderNumber = models.ForeignKey(OrderStatus, related_name='items', on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=choice) def __str__(self): return self.status Views.py from rest_framework.viewsets import ModelViewSet from OrderStatus.api.serializers import OrderRegisterSerializer, NumberOrderSerializer from OrderStatus.models import OrderItems, OrderStatus class OrderApiViewSet(ModelViewSet): serializer_class = OrderRegisterSerializer queryset = OrderItems.objects.all() class OrderNumberApiviewSet(ModelViewSet): serializer_class = NumberOrderSerializer queryset = OrderStatus.objects.all() serializers.py from OrderStatus.models import OrderItems, OrderStatus from rest_framework import serializers class OrderRegisterSerializer(serializers.ModelSerializer): #items = serializers.RelatedField(many=True, queryset = OrderItems.objects.all()) class Meta: model = OrderItems fields = ['itemName', 'OrderNumber', 'status'] … -
If the username or password is invalid when logging in, how can appear an error on page without refreshing itself, Django
I have a login pop-up and I want after typing wrong username or password to appear a error message, like usual 'Username or password is incorrect', but after pressing button on the site, it is refreshing and I need to open my pop-up again in order to see the error, how can I do the error msg to appear without refreshing the page. Views.py def main(request): form = CreateUserForm() if "register-btn" in request.POST: .... elif "login-btn" in request.POST: username = request.POST.get('username-log') password = request.POST.get('password-log') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/account') else: messages.info(request, 'Username or password is incorrect') #here I don't know what to write for the purpose of appearing the #error messages on the page without refreshing it return render(request, 'accounts/main.html', context) Main.html ( briefly ) <label>Your login</label> <input name="username-log" class="form-control" type="text" placeholder="Enter your login"> <label>Password</label> <input name="password-log" class="form-control" type="password" placeholder="Enter your password"> {% for message in messages %} <p id="messages" class="xerr"> {{message}} </p> {% endfor %} <button name="login-btn" class="btn btn_100" type="submit">LOG IN</button> -
How to return 404 and 500 errors in json formats instead of standard html pages in Django 4.x
I found only very stale articles on the Internet that don't quite solve my problem. I tried this way, but Django still returns html pages: exceptions.py def custom_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: if response.status_code == 500: response.data = {"code": 500, "message": "Internal server error"} if response.status_code == 404: response.data = {"code": 404, "message": "The requested resource was not found on this server"} return response settings.py REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'backend.exceptions.custom_exception_handler', } -
Stripe; Webhook that triggers when the current subscription gets ended (not cancelled)
I know that there is a webhook type customer.subscription.deleted that gets triggered when a user cancels the subscription (that is they don't want the subscription to be auto-renewed after it ends) so at this webhook event, we just update the users subscription state to cancel but they still have the subscription active (and that is expected) but is there any webhook event that gets triggered when the subscription ends or we have to do that manually? I saw this webhook event but i'm not sure if this is the one I'm searching for subscription_schedule.completed Any guidance would be helpful, thank you :) -
Display the number of comments of each post related to the same post in django
Hello friends I am building a blog and I have encountered a problem. My problem is that when I want to display the number of comments for each post, on the main page of the blog number of comments displays all posts that have comments, but the number of comments for each post is the same. In the event that post 2 has 3 comments and the other has 1 comment. You can see in this picture. Image This is my models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() comment = models.CharField(max_length=500) active = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} by {}".format(self.comment, self.name) This is my views.py def post_list(request): posts = models.Post.objects.filter(status='published') paginator = Paginator(posts, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) comment_count = models.Comment.objects.filter(active=True).count() context = { 'page_obj': page_obj, 'comment_count': comment_count, } # print(posts) return render(request, "post_list.html", context=context) And this too post_list.html <article class="col-12 col-md-6 tm-post"> <hr class="tm-hr-primary"> <a href="{{ post.get_absolute_url }}" class="effect-lily tm-post-link tm-pt-60"> <div class="tm-post-link-inner"> <img src="/{{ post.image }}/" alt="Image" class="img-fluid"> </div> <h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2> </a> <p class="tm-pt-30"> {{ post.body|slice:254 }} </p> <div class="d-flex justify-content-between tm-pt-45"> <span class="tm-color-primary">Travel . Events</span> <span class="tm-color-primary">{{ post.created_date.year }}/{{ post.created_date.month }}/{{ post.created_date.day … -
trying to post form data to django rest API by react using axios error buy saying The submitted data was not a file. Check the encodon
I am trying to send the form data( image) using react and Axios to rest API to Django data base I leading an error {photo: ["The submitted data was not a file. Check the encoding type on the form."]}photo ["The submitted data was not a file. Check the encoding type on the form."] "The submitted data was not a file. Check the encoding type on the form." import React, { useState } from "react"; import InputChar from "./SmallComponents/InputChar"; import InputNum from "./SmallComponents/InputNum"; import axios from "axios"; function CreateProduct() { const [productData, setProductData] = useState({ name: "", producttype: "", color: "", brand: "", desc: "", gender: "", offer: 0, price: 0, size: "", photo: "", }); function handleParentCharChange(featureName, featureValue) { setProductData((preProductData) => { return { ...preProductData, [featureName]: featureValue, }; }); console.log("------product data ----", featureName, featureValue); console.log("product data", productData); } function handleFormData(event) { setProductData((preProductData) => { return { ...preProductData, [event.target.name]: event.target.value, }; }); console.log("product data", productData); } function handleImageData(event) { const file = event.target.files[0]; // accessing file console.log("++++++++++image+++++++++++",file); setProductData((preProductData) => { return { ...preProductData, "photo" : file, } }) } function submitHandler(event) { event.preventDefault(); axios .post("http://127.0.0.1:8000/product/productcreate/", productData) .then((response) => { console.log("data is stored", response); }) .catch((error) => { console.log("data is not store", … -
IN ADMIN PANEL __str__ returned non-string (type NoneType)
im new to django tryna build up ecommerce project for education purposes. i got this error "str returned non-string (type NoneType)" from admin panel, when try view/change order or orderItem. I try to return str(self)I cant find error, pls guys help me fix it. I almost google all, but i dont understand how to can be type error if i return str(). Pls guys help my find they way to fix it from django.core.validators import RegexValidator from django.db import models from authentication.models import Customer from catalog.models import Product # Create your models here. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) date_order = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.transaction_id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @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 return total class … -
Render html form in django with forms.py
I have django web application with authentication system in it. I have user registration view, customer model and UserCreationForm in forms.py: class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) # phone_number = forms.CharField(required=True) # location = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') print(user.last_name) user.save() customer = Customer.objects.create(user=user) # customer.phone_number=self.cleaned_data.get('phone_number') # customer.location=self.cleaned_data.get('location') customer.save() return user My model looks like this: ... first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=20) I render form in my customer_register.html: ... <section> <div class="container"> <div class="row"> <div class="col-md-6 mx-auto"> <div class="card"> <div class="card-header text-black"> <h2>Register</h2> </div> <div class="card-body"> <form action="{% url 'customer_register' %}" method="POST" novalidate> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% render_field field class="form-control" %} {% for error in field.errors %} <span style="color:red">{{ error }}</span> {% endfor %} {% endfor %} </div> </form> </div> </div> </div> </div> </div> </div> </section> ... It doesn't look very pretty though. What I want to do is to replace my form in customer_register.html with new form in which I wouldn't use widget_tweaks but just html. -
Django media url from model
I'm working on a simple blog, I have this model for the blog post: class BlogPost(models.Model): title = models.CharField(max_length=150, unique=True) body = models.TextField() cover_image = models.ImageField(upload_to='blogposts/') created_on = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) category = models.ManyToManyField('PostCategory', related_name='posts') slug = models.SlugField(null=True, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("blog_detail", kwargs={"slug": self.slug}) In the settings file, I have the following configuration for static and media files: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I'm creating the blog models and views in a separate app I named "blog" I'm using a Django classed-based list view to display the posts on the page: class BlogListView(ListView): model = BlogPost template_name = "blog/blog_list.html" And I have the URL files working just fine: The problem is in displaying it in my template view, primarily for the post's cover image: {% for post in object_list %} <!-- Single Blog Item --> <div class="single-blog-item style-2 d-flex flex-wrap align-items-center mb-50"> <!-- Blog Thumbnail --> <div class="blog-thumbnail"> <a href="{{ post.get_absolute_url }}"> <img src="{{ post.cover_image }}" alt=""> </a> </div> <!-- Blog Content --> <div class="blog-content"> <a href="{{ post.get_absolute_url }}" class="post-title">{{ post.title }}</a> <p>We'll come back to this...</p> <div class="post-meta"> <a href="#"><i class="icon_clock_alt"></i> {{ post.created_on }}</a> … -
Django - One to One field bug not saving data without error
I am currently experiencing an issue with a one-to-one field in Django where the data was not stored after assigning value and save call is successful without any error. class Model1(models.Model): field1 = models.OneToOneField(Model1, on_delete=models.SET_NULL, null=True, blank=True, default=None) # Some other fields here def link_item(self, model2_id): field1 = Model2.objects.get(id=model2_id) self.field1 = field1 self.save() When I use the link_item of the model from the python shell it was updating the field but when it was used on the normal process the save call is successfully called but when I checked the value again in the shell it didn't update the field1. I have almost 10 million rows of data for Model1 and Model2, I'm not sure if it related to the issue but maybe it could help. -
Django raises set-returning functions are not allowed in WHERE with annotated value
I need to query orders where the shipping address's postcode is between a certain range. In order to do this, I have to cast the postcode (charfield) to a integer by removing the non numeric values. I have written this database function for that which works: class NumericPostcode(models.Func): """ Removes characters from field and converts to integer """ function = "REGEXP_MATCHES" template = "CAST( (%(function)s(%(expressions)s, '\\d+'))[1] as INTEGER )" output_field = models.IntegerField() Then I do the following query: orders_qs = Order.objects.annotate( numeric_postcode=NumericPostcode(models.F("shipping_address__postcode")) ).filter(self.get_range_query()) The get_range_query is a method that builds a dynamic query: def get_range_query(self): """ Build the range query dynamically based on all postcode ranges linked to this transporter https://docs.djangoproject.com/en/dev/ref/models/querysets/#range """ query = models.Q() for postcode_range in self.postcode_ranges.all(): query |= models.Q(numeric_postcode__range=(postcode_range.min_postcode, postcode_range.max_postcode)) return query However, this query raises the error: NotSupportedError at /admin/shop/reports/ set-returning functions are not allowed in WHERE Without the .filter(self.get_range_query()), I can print the annotated field fine and it also works. The raw SQL query is as follows: SELECT "order_order"."id", "order_order"."number", "order_order"."site_id", "order_order"."basket_id", "order_order"."user_id", "order_order"."billing_address_id", "order_order"."currency", "order_order"."total_incl_tax", "order_order"."total_excl_tax", "order_order"."shipping_incl_tax", "order_order"."shipping_excl_tax", "order_order"."shipping_address_id", "order_order"."shipping_method", "order_order"."shipping_code", "order_order"."status", "order_order"."guest_email", "order_order"."date_placed", "order_order"."delivery_time_text", "order_order"."delivery_time_days", cast( (Regexp_matches("order_shippingaddress"."postcode", '\d+'))[1] AS INTEGER ) AS "numeric_postcode" FROM "order_order" LEFT OUTER JOIN "order_shippingaddress" ON ( "order_order"."shipping_address_id" = … -
Python Http Client requests
I would like to retrieve product data using the POST method and passing it the security key on the headers I get an HTTP 400 error def api(request): headers={'content-type':'application/json','security-key': 'valu-key'} url = 'http://api-content/product/GetProduct' x = requests.post(url, headers = headers) content=x.status_code return HttpResponse(content) -
Docker Django Postgres FATAL: password authentication failed for user "postgres
I am dockerizing my Django app. My configs are the following: csgo.env POSTGRES_NAME='postgres' POSTGRES_USER='postgres' POSTGRES_PASSWORD='postgres' POSTGRES_HOST='postgres_db' POSTGRES_PORT='5432' settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('POSTGRES_NAME', 'postgres'), 'USER': os.getenv('POSTGRES_USER', 'postgres'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD', 'postgres'), 'HOST': os.getenv('POSTGRES_HOST', 'postgres_db'), 'PORT': os.getenv('POSTGRES_PORT', '5432'), } } docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile env_file: - csgo.env ports: - '8000:8000' volumes: - .:/code depends_on: - postgres_db postgres_db: image: postgres:13 restart: always ports: - '5432:5432' env_file: - csgo.env environment: - POSTGRES_NAME='postgres' - POSTGRES_USER='postgres' - POSTGRES_PASSWORD='postgres' - POSTGRES_HOST='postgres_db' - POSTGRES_PORT='5432' When I run docker-compose up, I get the typical auth error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" and I am readdly stressed of it. I have been looking for a typo a day long and haven't figured it out. Please help me to debug! Note: I know that this kind of questions are overflowed on the Internet. My post is about finding a typo or a mechanical mistake by me. Thanks for understanding and not assigning the post as a duplicate one! -
KeyError: '__module__' when creating dynamically proxy models
I want to create dynamically proxy models with this code: from django.db import models class BaseId(models.Model): def __str__(self): return self.nom class Meta: app_label = 'sae' abstract = True NOMENCL_LIST = ['CAT', 'CATR', 'CCR', 'ESPIC', 'GRP', 'MFT', 'NAT', 'PERSO', 'STJ', 'STJR'] class Nomenclature(BaseId): code = models.CharField(max_length=20, unique=True) nom = models.CharField( max_length=250) class Valeurs_nomenclature(BaseId): nomenclature = models.ForeignKey(Nomenclature, on_delete=models.PROTECT, related_name='valeurs') code = models.CharField(max_length=20) nom = models.CharField(max_length=250) class NomenclatureManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(nomenclature__code=qs.model.__name__) for nomencl in NOMENCL_LIST: if nomencl not in globals(): meta = type('Meta', (BaseId.Meta,), { 'proxy':True }) model = type(nomencl, (Valeurs_nomenclature,), # this line causes the error { 'Meta':meta, 'objects':NomenclatureManager }) globals()[nomencl] = model This code raises a KeyError the before last line: module = attrs.pop("__module__") KeyError: '__module__' When I set explicitly "module", it works : model = type(nomencl, (Valeurs_nomenclature,), { 'Meta':meta, 'objects':NomenclatureManager, '__module__':'sae.models.id_models' }) My question: in what circumstance 'module' is set implicitly or not ? -
Django Static files Page not found (404)
I am trying to create a website using Django and in my models.py I am using Django's ImageField(upload_to=''), but these files are not being uploaded to their location and I don't know why. That file is empty. So I am getting this error Page not found (404) at http://127.0.0.1:8000/class/instructor_pics/2_c4iU33j.jpg. The other static files are fine like carousel banner and everything but these files are not being uploaded. What should I change to make this work? My models.py: class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) enrolled_students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='enrolled_students', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 285 or img.width > 201: output_size = (285, 201) img.thumbnail(output_size) img.save(self.image.path) img2 = Image.open(self.instructor_image.path) if img2.height > 40 or img2.width > 40: output_size = (40, 40) img2.thumbnail(output_size) img2.save(self.instructor_image.path) My settings.py: """ Django settings for Abrar_Class project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # … -
Django make the object create only once per day
Here is my Django model: class mymodel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) How can I make the object created only once per day? I know it's possible to do with unique_for_date but cannot understand how https://docs.djangoproject.com/en/4.1/ref/models/fields/#unique-for-date Also, I want to show an error if the user wanted to create more than once per day. -
WOPI issue in view and edit mode
I have implemented the wopi in my application, uploaded the new version of document while in the view mode then changed into edit mode new version of the document is not updated old version is displayed and different session is created for the same user -
Why user.has_perm print always True?
A user is assigned to a student group and from the group remove delete_permission, but the below code returns true. student_group = Group.objects.get(name='student') content_type = ContentType.objects.get_for_model(Department) department_permission = Permission.objects.filter(content_type=content_type) user = User.objects.get(email='test@gmail.com') student_group.user_set.add(user) for perm in department_permission: if perm.codename == "delete_department": student_group.permissions.remove(perm) print(user.has_perm("quiz.delete_department"), "Quiz Permission after") -
Change API_BASEURL
I'm doing a project on Django REST Framework. I need the project to run not on standard "http://127.0.0.1:8000 /", but on the server "http://localhost:8080 ". Please tell me where it needs to be corrected in my project files? -
django model AttributeError: 'str' object has no attribute 'clone'
two off my models in Django are getting the AttributeError: 'str' object has no attribute 'clone' while a run makemigration command class Statuses(models.TextChoices): publish = _('publish') archive = _('archive') draft = _('draft') category = models.ForeignKey(BlogCategory, on_delete=models.DO_NOTHING, verbose_name=_("blog category")) title = models.CharField(max_length=64, null=False, blank=False, verbose_name=_("blog title")) slug = models.SlugField(null=False, blank=False, allow_unicode=True, verbose_name=_("blog slug")) intro = models.TextField(null=False, blank=False, verbose_name=_("blog introduction")) body = models.TextField(null=False, blank=False, verbose_name=_("blog body")) created = models.TimeField(auto_now_add=True, verbose_name=_("blog creation time")) pubdate = models.TimeField(auto_now=True, verbose_name=_("blog publish time")) status = models.CharField(max_length=12, choices=Statuses.choices, verbose_name=_("blog publish status")) class Meta: ordering = ['-pubdate'] indexes = ['title'] verbose_name = _('blog') verbose_name_plural = _('blogs') and class Products(models.Model): productName = models.CharField(max_length=32, blank=False, null=False, verbose_name=_("product name")) productImage = models.ImageField(upload_to='medias/images/products/') category = models.ForeignKey(ProductCategories, on_delete=models.DO_NOTHING, verbose_name=_("product category")) weights = models.ForeignKey(Weights, on_delete=models.DO_NOTHING, verbose_name=_("product weights")) package = models.ForeignKey(Packages, on_delete=models.DO_NOTHING, verbose_name=_("product package")) class Meta: ordering = ['productName'] indexes = ['productName'] verbose_name = _('product') verbose_name_plural = _('products') and didn't find any good answer for the problem -
file.truncate doesn't clear file content
I'm using python and django for an application, and I have to stock informations in a text file. So I've done this : def write_in_file(data): stock_file = open(os.path.join(sys.path[0], "static/imported_data.txt"), "w") stock_file.truncate() stock_file.write(data) stock_file.close() It's working like I want and my file contains 'data'. But when I refresh the page, the content of the file is not cleared, and 'data' is rewrited at the end of the file. And when I print something to debug, I see that the function is called every time I refresh the page. The only time my file is properly cleared is when I modify the 'write_in_file' function. Does anyone know from where this might come from ? -
How to get pk from url in django rest framework?
I have 2 apps Ticket and Comment, with url: http://127.0.0.1:8000/api/tickets/<int:pk>/comments/<int:pk>/. comment.views class CommentAPIList(ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer permission_classes = (IsAuthenticatedOrReadOnly,) pagination_class = CommentAPIListPagination I want to get first int:pk in my url for filter my queryset, like: queryset = Comment.objects.filter(ticket=MY_GOAL_PK) comment.models class Comment(models.Model): text = models.TextField() ticket = models.ForeignKey( Ticket, on_delete=models.CASCADE, ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.text ticket.models class Ticket(models.Model): title = models.CharField(max_length=150) text = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.title I don't know what other information I can give, but I can give it at your request. May be you have another solution for filtering my Comment.objects. Filtering should provide comments related only to this Ticket