Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cron jobs run ok as script but not @reboot
I'm running a Django (v3.1.7) application on a headless remote Ubuntu (v20.04.3) that I'm looking to have start at reboot using crontab. The script below runs all ok from the command line. I've been through here crontabs-reboot-only-works-for-root and the linked suggestions as well but still haven't identified the issue. I've added logging (see *.log below) but do not get any helpful output. /home/myapp/reboot.sh #!/bin/bash echo "$(date) Starting reboot.sh" start_django () { echo "$(date) Entering start_django" screen -S django -dm bash -c 'cd /home/myapp && /usr/local/bin/gunicorn myapp.wsgi:application --bind 0.0.0.0:8000' > /home/myapp/django_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_django" } start_stream () { echo "$(date) Entering start_stream" screen -S streaming -dm bash -c 'cd /home/myapp/data_api && python3 api_stream_client.py' > /home/myapp/stream_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_stream" } start_test () { echo "$(date) Entering start_test" screen -S testa -dm bash -c 'cd /home/myapp && exec bash' > /home/myapp/test_cron.log 2>&1 sleep 1 echo "$(date) Exiting start_test" } if screen -list | grep -q "No Sockets found"; then echo "$(date) No screens available" echo "$(date) Starting test" start_test echo "$(date) Starting django" start_django echo "$(date) Starting stream" start_stream else if screen -list | grep -q "django"; then echo "$(date) django exists" else echo "$(date) … -
Caching TemplateView
I want to use cache from django to cache one template that makes expensive queries. I am not sure if I can just use render() in the get handler as in snippet below: class MyTemplateView(TemplateView): template_name = "my-template.html" def get(self, request, *args, **kwargs): cached = cache.get("my-view-response") if cached: return cached response = super().get(request, *args, **kwargs).render() # <--- cache.set("my-view-response", response) return response def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... # expensive queries return context Normally TemplateView.get returns TemplateResponse instance so by calling render it feels like I am skipping some steps. So my question is: is it ok to return string from TemplateView.get? inb4: The webpage loads correctly; I can't cache the TemplateResponse instance itself because it throws an exception; I have to use "low-level" cache API cause I am invalidating it when rows are added/deleted or modified (which will not happen often) -
How to list information on another page for a form
I am trying to make a question page where a user can click the questions ID. Upon clicking they will be redirected to another page to answer this question with the question text appearing and showing the multiple choice questions. How would I go around doing this? So far I have this Clicking number one will take the user to the question with the multiple choices for this question and question text Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, … -
display video using django FileField uri [react-native]
Hi I'm working on a react-native and I want to display a video, using expo-av, a django FileField uri, here's my code: <Video source={{ uri: "my/django/HE7sU4ABuNRAvwpFfW3qME.MP4" }} onError={(e) => { console.log(e); }} /> Now the problem is that if I try to load a video using uri for django FileField video the following error occurs: The server is not correctly configured. - The AVPlayerItem instance has failed with the error code -11850 and domain "AVFoundationErrorDomain". How can I configure django to allow video displaying in react-native? -
Django Rest Framework Nested Comments
i am trying to create a backend for blog website. I created a comment model and i have associated with blog post it. When I list the comments, I can also list the answers that have been made to the comment. But there is a problem that even though it appears in the comment as an answer, it also looks like it was the main comment again. How can I solve this. I would appreciate it if someone could help. I may have mistakes in English, I hope I was able to tell you what I wanted to tell you. Thanks in advance. Comment Model: class Comments(models.Model): class Meta: verbose_name = 'Yorum' verbose_name_plural = 'Yorumlar' user = models.ForeignKey(User, verbose_name='Yorum sahibi', on_delete=models.CASCADE) post = models.ForeignKey(Post, verbose_name='Yorum yapılacak Post', on_delete=models.CASCADE,related_name='comments') parent_id = models.ForeignKey('self', verbose_name='Parent Yorum', related_name='subcomments',on_delete=models.CASCADE, null=True, blank=True) comment = models.TextField(verbose_name='Yorum') [enter image description here][1]created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.user.first_name + " " + self.user.last_name + " | " + self.post.title Comment Serializer: class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comments fields = '__all__' def get_fields(self): fields = super(CommentSerializer, self).get_fields() fields['subcomments'] = CommentSerializer(many=True, read_only=True) return fields Post Serializer class PostSerializer(serializers.ModelSerializer): tag = serializers.StringRelatedField(many=True, read_only=True) comments = CommentSerializer(many=True, … -
How to connect 2 forms in HTML and Django?
I am creating a web page and i'm wondering if i could make sure that the data on the left is filled before pressing the blue button. On the left you can see a form to pay by entering your address, city etc. but on the right you can see another form with stripe implemented to pay with credit card. I don't know how to get the data from the left and save it in the database so I can create a receipt after successful payment. Here is the code down below. <div class="container-2"> <div class="gray-hover"> <form method="POST"> <div class="item" id="payment"> <div class="row"> <h4>Možnost nakupa 1: Plačilo po povzetju <small><i>(Za plačevanje s kartico je treba izbrati samo količino in vrsto izdelka!)</i></small></h4> {% csrf_token %} {% if form %} <div class="input-group"> <div style="color: red;">{{ form.name.errors }}</div> {{ form.name }} </div> <div class="input-group"> <div style="color: red;">{{ form.last_name.errors }}</div> {{ form.last_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.street_name.errors }}</div> {{ form.street_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.city_name.errors }}</div> {{ form.city_name }} </div> <div class="input-group"> <div style="color: red;">{{ form.email.errors }}</div> {{ form.email }} </div> <div class="input-group"> <div style="color: red;">{{ form.number.errors }}</div> {{ form.number }} </div> {% endif %} </div> </div> <div … -
How do I get the instances of a class with some certain conditions?
I have a model Order from which I want to get all the data in the "ref_code" field but then I want to filter it by the item. So basically what I mean is I want to get all the ref_code of a particular items (which is also a field by a manytomany). I don't know how to tweak it to work. I can only get all the ref_code so far. Any help will be appreciated. Model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(eOrderItem) item = models.ForeignKey( 'blog.Post', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) refund_requested = models.BooleanField(default=False) refund_granted = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True, blank=True) qr_code = models.ImageField(upload_to='qrcode', blank=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.ref_code) canvas = Image.new('RGB', (290, 290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = f'qr_code-{self.ref_code}.png' buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) def get_total(self): total = 0 for order_item … -
how to pass without double " " pass parameters an function in python Django Command
manage.py> generate_stock_nodes --no_of_bays 1 --no_of_racks 5 --no_of_rows 5 --no_of_columns 5 --last_bay_no 17 --creation_type 2 --last_bin_number 0501 --type_id 68 --stock_point_name INDO WESTERN -
How to cache django permissions?
I have implemented permission in django. But for example, {% if perms.application %} <li> </li> {% endif %} Django fetches the permission every time user makes a request, so which means am getting two extra queries: How to cache these permission so that the whole session uses the same ? Is there any better solutions for this ? -
Manually referencing dummy file in Django HttpRequest for testing form submission
In Django, I am trying to create automated tests for a project that includes a file submission via ModelForm. One of the model fields is a FileField, and a test file has already been placed into the project directory so it can be referenced. In order to test the form submission I am creating a dummy user and manually generating an HttpRequest() containing POST data. However, I am unsure of how to manually insert the file into the FileField portion -- I assume I need to reference it somehow, but I don't know exactly how to do that. The test is below: def test_form_submit(self): user = User.objects.create_user( username="testuser", email="asdfasdf@asdf.com", password="asdfasdf" ) request = HttpRequest() request.POST = { "file": [insert file here], # is a FileField "name": "Richard", "date": "2022-01-28", "desc": "A test submission." } form = FileSubmissionForm(request.POST, user=user) form.save() self.assertEqual(Submission.objects.count(), 1) How do I properly reference the file for this test case? The dummy file is located at $MEDIA_ROOT/testing/dummy_file.txt. Thanks! -
django admin mptt: how to show TreeNodeChoiceField instead of ModelChoiceField when add/change with FK
I'm working on a django app that includes some mptt based tree models. I have these models (simplified): class Asset_Type(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', verbose_name='Parent') name = models.CharField(max_length=64, unique=True, verbose_name='Asset Type Name') class Asset(models.Model): name = models.CharField(max_length=64, unique=True, verbose_name='Asset Name') type = models.ForeignKey(Asset_Type, on_delete=models.CASCADE, blank=False, null=False) I have these admin classes declared (simplified): class Asset_TypeAdmin(DraggableMPTTAdmin): mptt_level_indent = 20 admin.site.register(models.Asset_Type, Asset_TypeAdmin) class AssetAdmin(admin.ModelAdmin): list_display = ['name','type'] list_display_links = ['name'] admin.site.register(models.Asset, AssetAdmin) Everything works almost perfect, except this: When I add a new asset I get a template/form with a drop-down list where I can select the Asset_Type. The issue is that the drop-down list is of the class ModelChoiceField so it does not show the tree hierarchy. It shows this in the drop-down list: --------- Root 1 Child 1.1 Child 1.1.1 Root 2 Child 2.1 Child 2.1.1 I would like it to be class TreeNodeChoiceField so it shows this: Root 1 --- Child 1.1 ------ Child 1.1.1 Root 2 --- Child 2.1 ------ Child 2.1.1 I've found information related to this here: https://django-mptt.readthedocs.io/en/latest/forms.html#id4, but honestly I have no clue on how/where should I tell django that the field to use in the add/change form should be TreeNodeChoiceField. I've … -
ModuleNotFoundError: No module named 'spotify'
guys. I made a mistake, when i was creating the file to access the spotify api with my application i accidentally created the folder 'spotify' inside my app folder. Now i tried to move the spotify folder into the django folder, so it would be in the same directory as my app. The issue is that when i try to migrate it shows: "ModuleNotFoundError: No module named 'spotify'. Do you guys have a tip? Thanks in advance! -
annotate - Django ORM optimization
I want to annotate similar product from Order-Line.where Line has a foreign-key relation with products. im showing what ive done so far. recommended_product_ids = Line.objects.all() recommended_product_ids = recommended_product_ids.annotate( rank=Sum('quantity'), ).filter(rank__gte=2).order_by('-rank')[:max_count] -
Django and redis adding :1 to keys
I'm using django-redis to store some data on my website, and I have a problem where Redis is adding :1 at the beginning so my key looks like this: :1:my_key I'm not sure why is it doing this, I've read the documentation on django-redis and I couldn't find anything related, so my guess it has something to do with redis but I can't figure out what. In my settings.py I have the regular: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://xxxxx/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } And in my tasks.py I set keys like the documentation says: from django.core.cache import cache cache.set(my_key, my_value, 3600) So now I can't get the values using the cache.get(my_key) -
Django gives error at {% result_list cl %} when accessing models
unsupported operand type(s) for +: 'Listing' and 'float' Error Django admin The error seems to only happen when trying to access the models on the admin page, whats the cause? Views.py -
Unable to log-in in admi site using aadhaar no in django using custom model
I created a custom django model where I used aadhar number as USER_FIELD which does not give me any error but after creating the superuser I can't log-in in the admin site of django. -
How to solve 'NoneType' object has no attribute 'fields' in Graphene-django
Have this mutation class AddStudentMutation(graphene.Mutation): class Arguments: input = StudentInputType() student = graphene.Field(StudentType) @classmethod @staff_member_required def mutate(cls, root, info, input): try: _student = Student.objects.create(**input) except IntegrityError: raise Exception("Student already created") return AddStudentMutation(student=_student) Before executing the above mutation in graphiql, I add the request header "Authorization": "JWT <token>" so that the user is authorized. But I get the error graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'fields'. The error doesn't occur when I remove the header. It also works fine when I include it in requests for queries. Am I doing something wrong? I need the authorization to happen for mutations too. I tracked the Traceback and it leads to file .../site-packages\graphql_jwt\middleware.py. It appears it's a bug in the package in function allow_any() line 18 field = info.schema.get_type(operation_name).fields.get(info.field_name). New to this I need help. I'm using graphene-django==2.15.0 and django-graphql-jwt==0.3.4 -
Django with django-tenant, unable to perform migrations
Context I am trying to setup django-tenants for my Django application by following the official installation guide. My Django app used to run perfectly fine when I ran manage.py runserver. My settings.py looks exactly as in the guide: SHARED_APPS = ( 'django_tenants', 'iam', # the tenant models (Client & Domain) reside in this app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... ) TENANT_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', ... ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... # rest of middleware ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # the option for django-tenant 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { "ENGINE": 'django_tenants.postgresql_backend', ... # other db settings } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) TENANT_MODEL = "iam.Client" TENANT_DOMAIN_MODEL = "iam.Domain" Problem After following all the steps in the installation guide I try to use python manage.py migrate_schemas --shared. This results in the following stacktrace: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File … -
Django inline formsets with Class-based view
I'm trying to do Django class-based CreateView inline formsets. I have a product model and a productImage model and productImage is inline everything looks fine but after i submit my product the images that are selected in formset will not save. Here is my code models.py: class Product(models.Model): name=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True), description=models.TextField(blank=True), vector_column=SearchVectorField(null=True, editable=False), meta={"indexes": (GinIndex(fields=["vector_column"]),)} category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) class ProductImage(models.Model): product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%y/%m/%d') def __str__(self): return self.product.name views.py class ProductCreate(StaffAccessMixin, ProductFormValidMixin, ProductFieldsMixin, CreateView): model = Product def get_context_data(self, **kwargs): context = super(ProductCreate, self).get_context_data(**kwargs) if self.request.POST: context['product_image_formset'] = ProductImageFormset(self.request.POST) else: context['product_image_formset'] = ProductImageFormset() return context template_name = 'products/product-create-update.html' ProductFormValidMixin: class ProductFormValidMixin(): def form_valid(self, form): context = self.get_context_data() product_image_formset = context['product_image_formset'] if self.request.user.is_superuser: self.obj = form.save() if product_image_formset.is_valid(): product_image_formset.instance = self.obj product_image_formset.save() return redirect('administration:product-update', pk=self.obj.pk) else: self.obj = form.save(commit=False) self.obj.available = False return super().form_valid(form) ProductFieldsMixin: class ProductFieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["name", "slug", "description", "category", "price", "available", "image", ] else: raise Http404 return super().dispatch(request, *args, **kwargs) forms.py: from django.forms.models import inlineformset_factory from .models import Product, ProductImage ProductImageFormset = inlineformset_factory(Product, ProductImage, fields=('image',), extra=3) Formset template: … -
How to automatically add repeated data migrations in Django using Djangos ORM?
I am new to Django and have read the basic and advanced tutorial along with some parts of the documentation on migrations and data migrations: https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations Also, I have read about fixtures but this seems to be suitable only for initial data provision: https://docs.djangoproject.com/en/4.0/howto/initial-data/#providing-data-with-fixtures The task I want to accomplish is to bulk insert data repeatedly from "outside" in a clean way using using Djangos ORM and all the benefits of migrations. So far, I haven't found a full example on how to do this because using the first option of data migration would require to touch a file everytime I insert/migrate new data. Any hints on how to accomplish this or am I missing something? Thanks in advance! -
django passing id in popup
In my Django project, I want to edit users from the user list on the popup {%for data in data%} <tr> <td>{{data.firstname}}</td> <td>{{data.phonenumber}}</td> <td> <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> view Savings </button> </td> </tr> {%endfor%} popup <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header" style="background-color:#136de4;color:white" > <h5 class="modal-title" id="staticBackdropLabel">Edit Profile</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="card-body"> <form method="post" id="formOne"> {% csrf_token %} {{form.as_p}} <div class="modal-footer"> <a href="{%url 'customer:savingsprofile' data.id%}"><button type="submit" class=" btn bg-gradient-info text-white btn-sm m-1" data-bs-dismiss="modal">Save Changes</button></a> </div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> but on the popup it is showing only the first (while clicking another row) data of the table -
Django customize Label of form
whenever I add a Labels to ModelForm, the Label will look in the HTML like this: #v check this colon <label for="id_url">URL:</label> When I created the labels like this: class FieldForm(forms.ModelForm): class Meta: model = Field fields = ( 'title', 'url', ) labels = { 'title': 'Title', 'url': 'URL' Where do the colons at the end of the Label in the HTML come from and how to remove them? -
Run periodic celery task with a dynamic schedule in django application
I am wondering if it is possible to have my end users dynamically adjust the schedule of a periodic task. So something along these lines: # celery.py def get_schedule(): config = get_user_config() # returns a model object of sorts return config.frequency_in_seconds app.conf.beat_schedule = { 'my_periodic_task': { 'task': 'my_periodic_task', 'schedule': get_schedule, # schedule updated based on `get_schedule` function }, } This way, if a user were to change the frequency_in_seconds field in their user config setting, it would dynamically update the beat schedule. My preference would be to do this outside of the Django Admin site and without any additional packages (e.g. django-celery-beat). Any thoughts or ideas would be much appreciated. Thanks -
How can I join two serilaizers in django rest framework that have a similar field value
I have two models in my Django Restframework. In my views I want to get all properties and for each property I get Profile data of that user who created it. How can I achieve this? example: #models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=200) location = models.CharField(max_length=200) class Properties(models.Model): title = models.CharField(max_length=200) price = models.CharField(max_length=200) category = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) #serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = [ 'title','price','category','created_by' ] #views.py class PropertiesView(generics.ListAPIView): serializer = PropertySerializer queryset = Property.objects.all() -
User generated item multiple choice field Django
I am looking for a way to have a multiple choice field populated with choices made by a user. For example, they could have the following 3 entries: Yes, No, Unsure. I want a way to be translate this to a model. I understand this can be done with pre-defined options using a CharField, or ChoiceField, but I haven't seen anything with "dynamic" data, such as user-generated data.