Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Struggling with AWS S3 storage
My concern is about media images on AWS S3 from a Django based website. I'm able to view images from and save them to S3 when I'm on localhost, everything works well. However when the app is deployed and the website is running live on the internet, actual link: I'm only able to view the images that are on S3, but NOT able to save images to S3 bucket, though the AWS S3 bucket has full public access. I get the following error while trying to save images to S3: 2)Error Error message ClientError at / An error occurred (400) when calling the HeadObject operation: Bad Request It highlights this line of my code: form_instance.save() My code: (views.py) def make_and_see(request): if request.method == 'POST': form_instance = ProductForm(request.POST, request.FILES) if form_instance.is_valid(): form_instance.save() messages.success(request, 'Picture is saved') return redirect('home') else: messages.error(request, form_instance.errors) return redirect('home') else: context = {'data': Product.objects.all().order_by('?').first(), 'my_form': ProductForm(), 'time': timezone.now} return render(request, 'app1/home.html', context) (settings.py) STORAGES = {"default": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage"}, "staticfiles": {"BACKEND": "storages.backends.s3boto3.S3StaticStorage"}} AWS_ACCESS_KEY_ID = os.environ["MY_AWS_ACCESS_KEY_ID"] AWS_SECRET_ACCESS_KEY = os.environ["MY_AWS_SECRET_ACCESS_KEY"] AWS_STORAGE_BUCKET_NAME = '****' AWS_S3_REGION_NAME = 'ap-south-1' AWS_QUERYSTRING_AUTH = False AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" My webite is hosted on Vercel via Github, the Postgresql db hosted … -
Celery tasks succeeding in Django but not showing on Flower or Celery Logs
I have a Django project using cookiecutter's template, I have been trying to get celery working with it. I have done the setup according to the celery docs and when I run a task, on Django's output it shows as succeeded but if I check the terminal running celery, celery logs don't even show if it received the tasks, I am running it using celery -A proj_name worker -l DEBUG. I also tried it with INFO but same thing. The tasks also dont show up on the Flower dashboard and I am using django-celery-results with both redis/postgres backends and both don't get the results populated. I am not really sure what's going on but as far as I can tell celery is not receiving the tasks at all despite what Django's logs show. Also, when I try to print the task's state using AsyncResult it always shows PENDING despite django again saying it succeeded. Here's my celery.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj_name.config.settings.local") app = Celery("proj_name") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and my celery related configs if USE_TZ: CELERY_TIMEZONE = TIME_ZONE CELERY_BROKER_URL = env("CELERY_BROKER_URL", default="redis://localhost:6379/0") # CELERY_RESULT_BACKEND = f"db+postgresql://{env('POSTGRES_DB_USER')}:{env('POSTGRES_DB_PWD')}@localhost/{env('POSTGRES_DB_NAME')}" CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_CACHE_BACKEND = 'django-cache' … -
How do I iterate through a QuerySet of a QuerySet?
I'm trying to iterate through a Review QuerySet associated to an Album QuerySet in order to gather the total amount of ratings within the Review QuerySet. (9 + 8 + 7 + 9 = 33, for instance.) Here are my models: class Album(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) artist = models.CharField(max_length=255) title = models.CharField(max_length=255) # image = rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) ... class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) ... Here are my attempts at for loops to try and get these totals: # Attempts working off of: `all_albums = Album.objects.all()` # Attempt 1 >>> for album in all_albums: ... review_ratings_amount = album.review_set.rating.all() ... print(review_ratings_amount) # Attempt #2 >>> for album in all_albums: ... review_ratings = album.review_set.filter("rating") ... print(review_ratings) # Attempt #3 >>> for album in all_albums: ... review_ratings = album.review_set.get(rating) ... print(review_ratings) # Attempt #4 >>> for album in album_ratings: ... review_ratings = album.review_set.get("rating") ... for rating in review_ratings: ... print(rating) # Attempt 5 (this was an attempt to see if ANYTHING would return, and I actually got some QuerySets in … -
Trigger htmx with radio button selection
I am using django and htmx to update a field on a form below is the code for displaying the radio buttons and my attempt at trigging. But it does not trigger. What am I doing wrong? {% extends 'core/base.html' %} {% block title %}Booking{% endblock %} {% block content %} <div class="container"> <div class="form-group"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4"> <div class="col text-center p-1"> <form method="POST" action="."> {% csrf_token %} <legend>{{s_form.species.name.title}}</legend> <div hx-get="{% url 'book_services' %}" hx-trigger="change from:find .btn-check" hx-target="#book-services"> {% for choice in s_form.species.field.choices %} <input type="radio" class="btn-check" name="{{s_form.species.name}}" id="id_{{s_form.species.name}}_{{choice.0}}" autocomplete="off"> <label class="btn btn-outline-primary btn-lg m-1 col" for="id_{{s_form.species.name }}_{{choice.0}}"> {{choice.1}}</label> {% endfor %} </div> </form> </div> <div class="col text-center p-1 border"> <h5 class="text-lg">Service</h5> <div id="book-services" data-hx-trigger="load,bookSerivesChanged from:body" data-hx-get="{% url 'book_services' %}" data-hx-target="this"></div> </div> </div> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4"> <div class="col border">Date</div> <div class="col border">Time</div> </div> </div> </div> {% endblock %} I have attempted moving the trigger from a to the form and not luck. -
Retrieve last message for each conversation
I have a chat-like system on my website. I would like to make a list of conversation displaying the last message sent or received with each user I discussed with. Same as you can see on whatsapp or messenger or SMS applications. My Message model looks like this for now: class Message(models.Model): sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='messages_sent') receiver = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='messages_received') content = models.TextField() date = models.DateTimeField(auto_now_add=True) seen = models.BooleanField(default=False) I tried few things, the closest I achieved was this: latest_messages = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('sender', 'receiver', '-date').distinct('sender', 'receiver') The problem is, it returns the last message sent AND the last message received for each user, when I want the last of these 2. Thanks for your help -
admin.StackedInline in the Django Template
I am using Django. I made a Menu class in models.py class Menu(models.Model): nome = models.CharField(max_length=255) data = models.DateTimeField(auto_now=False, auto_now_add=True) class Meta: verbose_name_plural = 'Menu' # Python 2 def __unicode__(self): return self.nome # Python 3 def __str__(self): return self.nome and a Submenu class: class Submenu(models.Model): nome = models.CharField(max_length=255) data = models.DateTimeField(auto_now=False, auto_now_add=True) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Submenu' # Python 2 def __unicode__(self): return self.nome # Python 3 def __str__(self): return self.nome Then in admin.py I added: class SubmenuAdmin(admin.StackedInline): model = Submenu extra = 0 class MenuAdmin(admin.ModelAdmin): list_display = ['__str__'] inlines = [SubmenuAdmin,] class Meta: model = Menu admin.site.register(Menu, MenuAdmin) Now my goal is to be able to print the various menus in the template with a FOR loop, and under each respective menu the various submenus, as in this photo: -
Django makemigration does not detect my models
I have the following structure : DjangoProjectRoot API Peak peak_model.py Waterfall waterfall_model.py models.py ... As you can sea I organized the code to have separate module for each models, containing the model itself as well as the associated serializer and view. When I delete my database schema, all the migrations "makemigrations", the others tables are created, except the waterfall one. api/migrations/0001_initial.py - Create model Book - Create model Department - Create model Natural - Create model Publisher - Create model Region - Create model Cave - Create model Glacier - Create model Lake - Create model Peak - Create model Saddle - Create model Shelter - Create model Municipality - Create model Guide - Add field region to department - Create model Collection - Create model Author Any idea why ? I just refactored my code, before everything was in the model field. I'm also a bit surpised by " - Add field region to department ". My database is empty and I cleaned the migrations. Maybe I should add something in the init.py file ? Seems like django needs to detect my new structure ? waterfall_model.py : from django.db import models from api.natural.natural_model import Natural class Waterfall(Natural): height = … -
ERROR [nginx production-stage 3/4] COPY backend/static /usr/src/app/static/
trying to docker-compose build and get the response: failed to solve: failed to compute cache key: failed to calculate checksum of ref 5adae266-6345-4011-aeaf-cbed2c4d0e45::leen62wz7bu0oi2emahxawc9r: "/backend/static": not found Any idea how to solve the error? -
Profile Page cannot updating
I have a simple profile page and the information filled here comes in the form. The problem is that if I change a value it redirects to pages. I don't get an error but that update is not written to the database views.py def update_user(request): if request.method == 'POST': form = ProfileUpdateForm(request.POST) if form.is_valid(): profile_data = form.cleaned_data profile = get_object_or_404(UserProfile, user=request.user) profile.first_name = profile_data['first_name'] profile.last_name = profile_data['last_name'] profile.save() messages.success(request, "Update is successful") return redirect('/pages/') else: form = ProfileUpdateForm() return render(request, 'profile.html', {'form': form}) template.html <form class="form" method="POST" action='{% url "update" %}'> {% csrf_token %} <div class="row"> <div class="col"> <label>First Name</label> <input class="form-control" type="text" name="first_name" placeholder="{{ user.first_name }}"" value="{{ user.first_name }}"> </div> </div> </div> <div class="col"> <div class="form-group"> <label>Last Name</label> <input class="form-control" type="text" name="last_name" placeholder="{{ user.last_name }}"" value="{{ user.last_name }}"> </div> </div> </div> <div class="row"> <div class="col d-flex justify-content-end"> <button class="btn btn-primary" type="submit" value="profile">Save Changes</button> </div> </div> </form> forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['first_name', 'last_name', 'plz', 'street', 'street_no', 'city'] widgets = { 'first_name': forms.TextInput(attrs={"class": "form-control"}), 'last_name': forms.TextInput(attrs={"class": "form-control"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) any help? -
Django template with BS5 tab-pane for-loop
So I am trying to make a page with tabs and corresponding panes. I used the original BS5-code and also found some guides like this one I adapted the code to fit to the Django template, but it acts quite strangely: Initially no pane is shown when selecting another tab and then the first one again all panes are shown simultaneously. <div class="row"> <div class="card-header"> <ul class="nav nav-tabs" id="specimen_tab" data-bs-tabs="tabs"> {% for a_s in analyte_specimen %} <li class="nav-item"> <a class="nav-link{% if forloop.first %} active" aria-current="true {% endif %}" data-bs-toggle="tab" href="#pane-{{ a_s.specimen.sg_id }}">{{ a_s.specimen.name }}</a> </li> {% endfor %} </ul> <div class="tab-content card-body" id="specimen_tabContent"> {% for a_s in analyte_specimen %} <div class="tab-pane fade{% if forloop.first %} active{% endif %}" id="pane-{{ a_s.specimen.sg_id }}"> <-- Content here --> </div> ...... -
'snyk' says my django view code is dangerous, is it?
I have a Django file-sharing app and snyk.io keep reporting me there is Path Traversal Vuln. So I added some 'safe validation functions', but he keeps warning me there is a HIGH-LEVEL vulnerability. I want to know if I can just ignore those issues... Any criticism or suggestions would be appreciated the file sharing view def fileshare_details(request): if request.method == 'GET': pk = request.GET.get('id') try: secretfile = SecretFile.objects.get(pk=pk) path = settings.MEDIA_ROOT / secretfile.content.name return FileResponse( open( path, 'rb' ) ) except SecretFile.DoesNotExist: pass return redirect('/file/') with create view def fileshare_create(request): if request.method == 'POST' and request.FILES: # ... some assigns ... content = request.FILES['file'] is_safe_filename = safe_filename(filename=str(content.name)) if not is_safe_filename: return render( request, 'fileShare/failure.html', { # ... some debug info for the user ... } ) SecretFile.objects.create( content=content, # ... some other values ... ) return redirect('/file/') return render(request, 'fileShare/create.html') with 'safe_filename' function def safe_filename(filename): for unsafe in UNSAFES: if unsafe in filename: return False return True and UNSAFES = { 'root', 'ssh', 'key', 'admin', 'password', 'passwd', 'pw', 'id', 'sys', 'env', 'conf', '\\', '/', '%', } I've read articles about path traversal, and it seems my 'safe_filename' function can filter those filenames as well. As far as I think there … -
How can I fetch videos in Django from my media folder?
I want to render my videos and images using a dinamic JS. For that purpose I've done these codes: const fetchMediaFiles = async() => { const response = await fetch('http://127.0.0.1:8000/myApp/get_media_files'); const files = await response.json(); const content = document.getElementById('content'); for (let i = 0; i < 1; i++) { content.innerHTML = ` <div class="video-active"> <video src= "media/${files[i]}' " controls> Your browser does not support video tag. </video> </div> `; } /* .catch(error => console.log(error)); */ console.log(files); } A HTML with well basically a section, this function in views.py `def get_media_files(request): media_folder = os.path.join(settings.MEDIA_ROOT) files = [] for filename in os.listdir(media_folder): files.append(filename) return JsonResponse(files ,safe=False)` and this code in urls.py: path('get_media_files/', get_media_files, name="get_media_files"), The error I get is 404 and it shows me all the paths from Urls.py which of course doesn't match with my video src. I'd like to know how can I connect those videos or make the folder accesible so I can just use a relative path or something to get that. Thank you all! -
Django: Save data in a Table but at the same time edit or modify data from a different table
#I am trying to save data in the constancia_pro table but at the same time I want to edit or modify the status field from "NO" to "YES" of the lpro_reg table when I save it, but it generates this error: The lpro_reg could not be changed because the data didn't validate.# models.py `class lpro_reg(models.Model): id = models.AutoField(primary_key=True) tipodoc = ( ('V', 'V'), ('E', 'E'), ('J', 'J'), ('G', 'G'), ) tipo = models.CharField(max_length=2, choices=tipodoc, default='J') documento= models.CharField(max_length=15, blank=False) nombre = models.CharField(max_length=150, blank=False) presentante = models.CharField(max_length=150, blank=False) fecha_reg= models.DateField(auto_now_add=True) ramos = models.ManyToManyField(ciuu) direccion = models.CharField(max_length=250, blank=False) n_recibo = models.CharField(max_length=50, blank=True) fecha_recibo = models.DateField() fecha_apert = models.DateField() opciones = ( ('SI', 'SI'), ('NO', 'NO'), ) status = models.CharField(max_length=2, choices=opciones, default='NO') responsable = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'prov_reg' ordering = ['id'] def __str__(self): return str(self.id) class constancia_pro(models.Model): licencia2 = models.AutoField(primary_key=True) n_constanica = models.CharField(unique=True, max_length=13) aprobado = models.OneToOneField(lpro_reg, on_delete=models.CASCADE) fecha_reg = models.DateField(auto_now_add=True) class Meta: db_table = 'pro_const' ordering = ['-licencia2'] def __str__(self): return str(self.licencia2)` views.py `verdatos = get_object_or_404(lpro_reg.objects, pk = id) ultimodato = constancia_pro.objects.first() ultima_id = int(ultimodato.n_constanica)` `if request.method == 'POST': formulario = aprobado_form(request.POST) formulario2 = registroprovicional_form(request.POST, request.FILES, instance=verdatos) if formulario.is_valid(): formulario.instance.n_constanica = ultima_id + 1 formulario.instance.aprobado = lpro_reg.objects.filter(pk = id).first()` formulario2.instance.status … -
Makefile error (make: *** [Makefile:31: test] Error -1073741515)
I am trying to set up my local development environment using the make command make setup as and I get this error. Error code: make: *** [Makefile:31: test] Error -1073741515 Make File: This is part of the Makefile content, /Makefile local_config = --settings=config.local ... setup: # Set up the project database python manage.py migrate ${local_config} Config.local: This is the content of the /config/local.py from .settings import * DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(PROJECT_ROOT, "db.sqlite3"), } } CACHES = { "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } DEBUG = True TASTYPIE_FULL_DEBUG = True I expected the command to execute normally and setup my development environment. -
Django - ImportError after Installing Angular and React
My Django Server was working perfectly but after installing Angular and React, my Django Server stopped working and started giving following error: I have already researched a lot but unable to resolve error, pls help... Traceback (most recent call last): File "C:\Users\LM\dj\policyboss\manage.py", line 22, in <module> main() File "C:\Users\LM\dj\policyboss\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'policyboss.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
How to handle different creator type models for post creator in Django?
Suppose I have Porfile, Post, Teacher and Student Django models, I created Profile model to share the common fields that Teacher and Student have. Question: what is the right way to represent the creator relationship in the post model, and if my following code right, How I can identify the type of the Profile I mean if it's teacher or student, when I get the profile instance from post creator?: class Porfile(models.Model): user = models.OneToOneField(User) . . class Post(models.Model): . creator = models.ForeignKey(Profile, on_delete=models.CASCADE) . class Teacher(models.Model): . profile = models.OneToOneField(Profile) . class Student(models.Model): . profile = models.OneToOneField(Profile) . -
additional field not showing in django admin panel
class CustomUser(AbstractUser): is_admin = models.BooleanField(default=False) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True) department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True) contact = models.CharField(max_length=17,null=True) whenever i tried to add a user through Djangoo admin site the contact field is not showing class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = '__all__' class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = '__all__' class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'email', 'is_staff', 'is_admin','department_id','company_id',] list_filter = ['is_staff', 'is_admin'] fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('is_admin','department_id','company_id','contact',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2', 'is_admin','department_id','company_id',), }), ) this is what i used to add field , i tried most of the thing to add this fields to Django user admin but not showing is there any mistake in my code -
DetailView from Django in NextJS 13 (fetching data)
I've got Django based app as my back-end, and NextJS as front-end. I've got a Post model in my Django App with two views - PostDetailView and PostListView. from django.shortcuts import get_object_or_404 from django.template import TemplateDoesNotExist from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Post from .serializers import PostSerializer from rest_framework.renderers import JSONRenderer from django.http import Http404, HttpResponse class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) class PostListView(APIView): def get(self, request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return JSONResponse(serializer.data) class PostDetailView(APIView): def get(self, request, pk): try: post = Post.objects.get(pk=pk) serializer = PostSerializer(post) return Response(serializer.data, status=status.HTTP_200_OK) except Post.DoesNotExist: raise Http404 I've also set up serializers.py and urls.py. #serializers.py from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' #urls.py from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('api/posts/', views.PostListView.as_view(), name='post-list'), path('api/posts/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), ] In my NextJS App I'm using new approach for folder structure with src/app. This is my folder structure. - src/app -- blog --- page.tsx (here is my 'ListView') -- [id] --- page.tsx (here is my 'DetailView') … -
Django Datetime formate DD-MM-YYYY
I want to set the date format DD-MM-YYYY but Error django.core.exceptions.ValidationError: ['“23.07.2023 21:00:11” value has an invalid date format. It must be in YYYY-MM-DD format.'] Help Me create_date = models.DateField(blank=False, default=datetime.now().strftime(("%d.%m.%Y %H:%M:%S")))``` I want to set the date format DD-MM-YYYY but Error django.core.exceptions.ValidationError: ['“23.07.2023 21:00:11” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
How to upload a file from request.FILES using Celery in Django?
There's a model called Post which has an image field. The image field gets its value from a form. I don't want media files to be stored locally. So I'm using S3Boto3Storage as my file storage. Is there a way to save the Post model object using celery (so that the image file gets uploaded by celery to not keep the user waiting). I tried writing a celery task to save the object. But apparently you can't just send a file to Celery as a parameter. This is what I have so far: views.py: tasks.upload_image_task.delay( request.user.pk, request.session["post_body"], request.FILES.get("image"), request.session["post_tags"], ) tasks.py: @shared_task def upload_image_task(user_pk, body, image, tags): user = User.objects.get(pk=user_pk) post = Post.objects.create(user=user, body=body, image=image, post_type="IMG") for tag_pk in tags: post.tags.add(Tag.objects.get(pk=tag_pk)) post.save() This will result in Object of type InMemoryUploadedFile is not JSON serializable. I also read that first you can save the file on local and then upload the file using a task. But I want to upload it directly. -
Writing to SQL yields different results with shell / django
I have a simple model: class myJSONField(models.JSONField): def get_prep_value(self, v): if v is None: return value return json.dumps(v, ensure_ascii = False) class Product(models.Model): data = myJSONField() number = models.PositiveIntegerField() Product.create(number = 1, data = {"direction": "süd"}) yields: "{\"direction\": \"s\u00fcd\"}" Testing with sqlite3: conn = sqlite3.connect('db.sqlite3') c = conn.cursor() test = json.dumps({"direction": "Süd"}, ensure_ascii = False) sql = ("""UPDATE test_product SET data = ? WHERE id=1""") c.execute(sql, [test]) conn.commit() yields: {"direction": "süd"} I am using the same db.sqlite3 file for both tests. I do not understand why the ensure_ascii = False flag is ignored by the django logic. How can I obtain a correct JSON in my JSONField (without the escaped ")? -
How to install Virtualenv globally in windows system?
I've installed virtual environment using pip (pip install virtualenv), and it has installed successfully. Then when I try to find the veriosn of my virtualenv (virtualenv --version), it shows the error messgae - 'virtualenv' is not recognized as an internal or external command I've installed virtualenv, and when I want to check if it has installed correctly, it shows error message - 'virtualenv' is not recognized as an internal or external command, operable program or batch file. -
Python/Django Setting up a database model with conditions inside of it
I am currently writing some sort of simple game, which is set up onto a database backend (using Python with Django). I have a database model called Character, which basically has two fields (there are more, but they are not relevant for my question). It basically looks something like this: # Create your models here class Character(models.Model): HUMAN= 'HM' ELF = 'EF' RACE_CHOICES = [ (HUMAN, 'Human'), (ELF, 'Elf'), ] race = models.CharField(max_length=2, choices=RACE_CHOICES) constitution = models.FloatField Basically you can choose a race from the two given above. I want humans to have more constitution than elfs, so the constitution should be dependent on what race the user picks. I know that this is possible by overwriting the save method, but I am also aware that this is not best practice as it can crash the whole database, should any errors occur. I was told that is is, however, possible to use conditions inside the model definition, what I basically need is: if race == human: constitution = 12.0f else: constitution = 8.0f I really don't know how to set this up inside a Django model. Or would it be a better way to define a meta class "Race" and … -
How to use the Tron API to find a transaction by hash
I am createing and webapp where users are able to submit a transaction hash and it will automaticcally check the hash in the relevant wallet to see if a transaction has been received if yes it cheks the amount transfered and if the amount is equall 50 USDT it will perform some logic. Now i`m struck in creating this webapp and i really want some help, I dont understand anything in the docs of the Tron API. Could anyone help me with this. My code: elif request.POST.get("pay_type") == "binance": transaction_hash = request.POST.get("no") tronlink_api_key = "YOUR_TRONLINK_PRO_API_KEY" api_url = f"https://api.tronlink.org/v1/transaction/{transaction_hash}?apiKey={tronlink_api_key}" response = requests.get(api_url) if response.status_code == 200: if Pin.objects.filter( owner=request.user, status="COMPLETED", transaction_hash=request.POST.get("no"), ).exists(): messages.error( request, "It seems that this Transaction Hash/Trix is relevant to another payment. Please try again.", ) return redirect("create_pin") else: transaction_data = response.json() amount = transaction_data.get("data", {}).get("amount", 0) if amount < int(request.POST.get("package")): messages.error( request, f"You have done a transaction of only {amount} USDT but, you should do a payment of {int(request.POST.get('package')) + 10} USDT. Please try again.", ) return redirect("create_pin") else: Pin.objects.create( owner=request.user, package=request.POST.get("package"), p_type=( "RENEW" if ( Pin.objects.filter( owner=request.user, status="COMPLETED" ).exists() ) else "NEW" ), pay_type="BINANCE", status="COMPLETED", transaction_hash=request.POST.get("no"), ) messages.success(request, "Pin applied successfully.") return redirect("dashboard") else: messages.error( request, … -
django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: id
I have below classes definition: class A(models.Model): created_time = models.DateTimeField(default=now, null=True, blank=True) t = GenericRelation(T, object_id_field='object_id', content_type_field='content_type', related_query_name='a') class B(A): state_path = models.CharField(max_length=256, blank=True, verbose_name="State Path") f = GenericRelation(F, content_type_field='content_type', object_id_field='object_id', related_query_name='b') class C(B): choice = models.BooleanField(default=False, verbose_name="Enabled") class T(models.Model): created_time = models.DateTimeField(auto_now_add=True, verbose_name="Created Time") # GenericForeignKey fields content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField(null=True, blank=True) a = GenericForeignKey('content_type', 'object_id') class E(models.Model): username = models.CharField(max_length=128, verbose_name="Username") key = models.TextField(blank=True, verbose_name="Key") class F(E): content_type = models.OneToOneField(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() b = GenericForeignKey('content_type', 'object_id') c = C.objects.get(pk=c_id) c.delete() It returned error: django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: id I don't quite get it why... as C doesn't have content_type, and T has on_delete=models.DO_NOTHING for its content_type. Please help correct. Thanks.