Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error during installing requirements.txt in Django (metadata generation failed)
I tried installing requirements.txt in Django. Virtual env is activated. This error is showing after I tried pip install -r requirements.txt After that I also tried to migrate but still not working. This is github fork I downloaded, it has a pickle file as well as its based on ML model. -
Django is redirecting me to sublime text and the last raises import error
Have chosen Sublime as core git editor. And now after every move I do in Django virtual project, i'm being redirecting to sublime text with such error: 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?" -
Django: how to save data to database in django when a condition is met?
i am writing a logic to allow user pay for items using thier debit card, the logic is working fine. Now i want to save some data to the database when the status=successful. When a user purchase a course i want to add the course and the user who purchased the course to a model that i have created called UserCourse. I have tried adding slug to the process_payment view that i created but it seems not to be working. I also have another view called payment_response that checks if a payment was success or not. How do i add the purchased course and the user that purchase the course in the db? views.py # The course detail view def course_details(request, course_slug): if request.user.is_authenticated: user = request.user course = Course.objects.get(slug=course_slug) @login_required def course_checkout(request, slug): course = Course.objects.get(slug=slug) user = request.user # form to get the student's name, email, amount of course if request.method == "POST": course = Course.objects.get(slug=slug) name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment(name,email,amount, course))) else: pass # how to handle courses that are free if amount == 0: course = Course.objects.get(slug=slug) userCourse = UserCourse(user=user, course=course) userCourse.save() return redirect('course:course-content', course.slug) # View that processes the … -
Django-postgress: Partial Index on timestamp
Consider queryset = queryset.filter( Q(enabled=False) | Q(expires_at__isnull=False) & Q(expires_at__lte=timezone.now()) | ) I would like to have a partial index to support this query. AFAIK, this index will not be used during the execution of the above query because the value of timezone.now() changes. On the other hand, if I just index enabled that is also not useful because the query planner has to go through the second condition anyway. -
Heroku Deployment: Failed to load resource: the server responded with a status of 404 (Not Found)
I initially deployed my app successfully to heroku but then I edited some text and redeployed it to heroku yesterday only for the js file not to load completely. It tells me failed to load resource on the chrome developer console (It was built using next.js, django and postgresql). I have checked everything and can't seem to find the error, Please I'm really confused and would be some help? favourndubuisi.herokuapp.com -
How to serialize a model with many to maany relashionship?
I have this function in my model, def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': self.likes.all(), 'likes_number': len(self.likes.all()), } but likes is actualy a many to many relashionship with User. How can I serialize it to get something like this? def serialize(self): return { 'id': self.id, 'author': self.author.username, 'text': self.text, 'timestamp': self.timestamp.strftime("%b %d %Y, %I:%M %p"), 'likes': [ user1, user2, etc. ], } So that I can also get rid of the 'likes number' property. -
Handling images via REST API
I'm trying to create a REST API with django-rest-framework which will be handling a few things, the one being sending and receiving images from the frontend. I found this article which tries to explain the idea, but it uses class-based approach in its' views.py and ideally I'd like to stick to a function-based one as I've already done some work that way (not including JWT authorization) and I'd prefer it to stay. I have no clue how to make my backend legible of receiving and sending images, could you please try to provide me with some code snippets (or better yet, articles) on how to do so? Thanks in advance! One thing to mention is that ideally I want to have an endpoint which will handle creating a new object which will come with an image (a plant to be specific) and an endpoint which would handle updating (changing) the object's image. My models.py: class Plant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=150) date_added = models.DateField(auto_now_add=True) description = models.TextField() img = models.ImageField(blank=True, null=True, upload_to=upload_path) plant_species = models.CharField(max_length=150) last_watered = models.IntegerField(default=0) how_often = models.IntegerField(default=0) tracked=models.BooleanField(default=True) My views.py: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username return … -
Django is treating same field which are lowercase and upper case as 2 different entities
I am creating models in django and then entering data in admin panel class Song(models.Model): name = models.CharField(max_length=30,validators=[alphanumeric]).title() slug=models.SlugField(default="",blank=True,null=False,db_index=True) artist = models.CharField(max_length=30,validators=[alphanumeric]) genre = models.CharField(max_length=30,validators=[alphanumeric]) language = models.CharField(max_length=30,validators=[alphanumeric]) image = models.ImageField(null=True,blank=True) But the issue is when I am entering "AceHunter" or "acehunter" as artist it is treating as different artists although I want them as one.... Please can someone help me what error I am making? -
Efficient Way to Search Complex Database
I have a database with 2 data tables: Messages and Annotations. A summary of the models is below. Only the important fields are included. message text = models.CharField(max_length=250, blank=False) accepted_annotation = models.OneToOneField( to='Annotation', related_name='original_msg', on_delete=models.SET_DEFAULT, default=None, null=True ) ...other fields annotation message = models.ForeignKey(to=Message, on_delete=models.CASCADE) user = models.ForeignKey(to=User, to_field='username', on_delete=models.SET_NULL, null=True) text = models.CharField(max_length=249, blank=False) reviewed = models.BooleanField(default=False) ...other fields I would like to search by text and also by the other fields. The complication is that, depending on who requested the data, different information is returned for each message in the database. The following pieces of information determine what is returned: users privilege whether the annotation is marked as reviewed whether there is an accepted annotation whether the user made an annotation Therefore when I search by text, I can't simply search the message text because the logic may determine that an annotation should be displayed for this user instead with completely different text. Currently what I am doing is using prefetch and annotations on the queryset to run through the logic and populate a field called "text_to_search" for each message before sorting and filtering. However, these require subqueries and will be very slow once there are millions of … -
Django Paginator is not giving output
Hope you are doing great. So there is a projects page where there are different number of projects on that page. Currently I am displaying 3 projects per page. Now I want to display number of pages that I have right now. Like there are 9 projects so there should be 3 pages. But My paginator is not displaying any number button on the bottom of the page. Here is the code(Sorry For the bad English I tried my best to explain) View.PY def projects(request): page = request.GET.get('page') results = 3 paginator = Paginator(obj, results) try: obj = paginator.page(page) except PageNotAnInteger: page = 1 obj = paginator.page(page) except EmptyPage: page = paginator.num_pages obj = paginator.page(page) return render(request, 'projects/projects.html',{'list': obj}) Projects.html <div class="pagination"> <ul class="container"> <li><a href="#" class="btn btn--disabled">&#10094; Prev</a></li> {% for page in paginator.page_range %} <li><a href="?page={{page}}" class="btn btn--sub">{{ page }}</a></li> {% endfor %} <li><a href="#" class="btn">Next &#10095;</a></li> </ul> </div> Can you guys tell what could be the issue? -
how to filter columns for each in the same model in Django admin
I have a model called Product. I am using StackedInline to display ProductCostCalculator in my admin panel. The problem that I have is that I will have 20+ columns in my ProductCostCalculator model. Some columns from ProductCostCalculator are not needed in every item in the Product model so I want to exclude all columns that are not needed. I know that I could just put 0 or '-' as default and insert values in proper columns in the admin panel but I would like to make it more dynamic so the user echo will be adding calculator components will not have to do it manually. For example, I want to add 2 items to my Product model. Let's call them Item 1 and Item 2. In Item 1 I will need to insert values in field_1, field_2, and field_3. In Item 2 in my Product model, I will need to insert values only for field_3, field_4 and field_5. Question: How can I assign a column from ProductCostCalculator to an item in the Product model or how can I filter all columns that are not needed in the specific item in the Product model. I am not sure if something like … -
React - How to login a user through Django backend?
Backstory as a learning exercise, I first built a website using only Django; then, I learned React (still in the process) and I was moving the frontend part in it and using Django only as backend. I have them on 2 different addresses 127.0.0.1:3000 and 8000. Now, I created all sort of API where React can fetch and send data to Django in order to read and manipulate the DB, the Login it is mainly the only thing that I'm still missing. I think this is probably due to the fact that I let Django handle all the things for the login, doing minimal work. The situation So, at the moment, in Django the login works this way: settings.py: LOGIN_URL = '/users/login/' LOGIN_REDIRECT_URL = '/users/' url.py: path('login/', auth_views.LoginView.as_view(template_name='registration/user_login.html'), name='user_login'), user_login.html (shorted): {% block body %} {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% endif %} <form method="post"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% else %} <input type="hidden" name="next" value="{% url 'registration:main_page' … -
AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard'
traceback File "/Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/channels/generic/websocket.py", line 238, in websocket_disconnect await self.disconnect(message["code"]) File "/Applications/MAMP/htdocs/canvas/src/zzd/zzd/notes/consumers.py", line 20, in disconnect await self.channel_layer.group_disgard( AttributeError: 'RedisChannelLayer' object has no attribute 'group_disgard' consumer class NoteConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['pk'] self.room_group_name = 'note_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_disgard( self.room_group_name, self.channel_name, ) async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'system_message', 'message': message, } ) async def system_message(self, event): # print(event) message = event['message'] await self.send(text_data=json.dumps({ 'message': message, })) versions (env) 🌹 python Python 3.7.11 (default, Jul 27 2021, 07:03:16) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> import channels >>> import asgiref >>> django.__version__ '3.2.8' >>> channels.__version__ '3.0.5' >>> asgiref.__version__ '3.3.4' config CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } Why the method is undefined, how can I dismiss the bug? -
django.db.utils.ProgrammingError: (1146, "Table 'main.socialaccount_socialapp_sites' doesn't exist")
I'm trying to implement Google Login on my Django production website. It works fine on development server, but on my production server, I face this issue after having run python manage.py migrate. I'm not sure what to do, I already tried deleting all the migrations and re-running makemigrations and migrate. -
Django: asynchronous service development through task list sharing
I am creating a web application with Django 3.1.0 and Python 3.8. This application requires the execution of a very long back-office operation and of which I am interested in knowing the percentage of progress. To do this, the server exposes two services: www.contoso.com/process_start: returns a string to indicate the id assigned to the task; www.contoso.com/process_status/taskid: returns a number from 0 to 1 to indicate the progress (as a taskid I use the id returned by the process_start call); To do this I have created the following Python class TASKS = dict() # list of tasks in progress class Task(): def __init__(self): id = get_uid() # generation of a random string TASKS[id] = self # added to the list of tasks in progress self.id = id self.percentage = 0.0 self.thread = Thread(name=self.id, target=self.execute) self.thread.start() @staticmethod def get_status(id: str) -> float: task = TASKS.get(id, None) return (1.0 if task == None else task.percentage) def execute(self) -> None: try: ... finally: TASKS.pop(self.id, None) # removal from the list of tasks in progress The first service creates the task like this: def post(self, request: Request) -> Response: task = TaskReslice() return Response(status=status.HTTP_200_OK, data=task.id) the second service returns the status of the task in … -
'datetime.timedelta' object has no attribute 'isoformat'
I am trying to annotate time field to sum the total time in a week in the following getting the above error class StaffWorkTimeSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField(format="%d-%m-%Y", read_only=True) total = serializers.TimeField() work_time = serializers.TimeField(format="%H:%M:%S", read_only=True) user = UserSerializer2(many=False, read_only=True) class Meta: model = StaffWorkTime fields = ['id', 'timestamp', 'work_time', 'user', 'total'] class StaffWorkTimeSerializerView(generics.ListAPIView): model = StaffWorkTime serializer_class = StaffWorkTimeSerializer def get_queryset(self): week_start = datetime.date.today() - datetime.timedelta(days=datetime.date.today().weekday()) week_end = week_start + datetime.timedelta(days=6) queryset = StaffWorkTime.objects.filter(user_id=self.kwargs['pk'])\ .filter(timestamp__range=[week_start, week_end])\ .values(week=TruncWeek('timestamp'))\ .annotate(total=Sum('work_time')).order_by('timestamp') return queryset Any help is appreciated to solve the error. -
How could I add timestamps feature to my djangocms project for videos?
i' m trying to add a feature (like "key moments" on Youtube videos ) to my django-cms project but i couldn't find any idea on net. so, i need your helps. -
Using argparse.REMAINDER to get the rest of the parameters breaks my other parameters
So I have this piece of code which just takes my parameters. class InteractiveTenantOption(object): def add_arguments(self, parser): parser.add_argument("command") parser.add_argument( "-s", "--schema", dest="schema_name", help="specify tenant schema" ) parser.add_argument("command_args", nargs=argparse.REMAINDER) The command looks like this: class Command(InteractiveTenantOption, BaseCommand): requires_system_checks = [] help = "Wrapper around django commands for use with an individual tenant" def handle(self, command, schema_name, command_args, *args, **options): print(schema_name) tenant = self.get_tenant_from_options_or_interactive( schema_name=schema_name, **options ) connection.set_tenant(tenant) call_command(command, *command_args, *args, **options) the problem is that print(schema_name) returns None for every command. Before I added parser.add_argument("command_args", nargs=argparse.REMAINDER) that print was not returning None. For example, if I run: python manage.py tenant_command test_command -s demoproject print result before adding parser.add_argument("command_args", nargs=argparse.REMAINDER): demoproject print result after adding parser.add_argument("command_args", nargs=argparse.REMAINDER): None Why did it change and how can I fix it? Thanks. -
How to open postgres db and see the tables (Django+Postgres+Docker)
I start learning docker with Django+PostgreSQL, I did all steps from there https://docs.docker.com/samples/django/ How can I open created database on terminal or pgAdmin to see tables and change them? I use: Ubuntu 22.04 / Docker Engine 20.10.17 / Docker Compose version v2.6.1 / psycopg2-binary==2.9.3 / Django==4.0.6 / psql (13.7 (Ubuntu 13.7-1.pgdg22.04+1)) my docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } some info if needed, postgres file created are owned by root: postgres file 1/2 postgres file 2/2 Thanks for answers! -
Django convert image to webp
I have service in my Django project's app, that upload images, and I need to convert all images to webp to optimize further work with these files on the frontend side. Draft of _convert_to_webp method: # imports from pathlib import Path from django.core.files import temp as tempfile from django.core.files.uploadedfile import InMemoryUploadedFile from PIL import Image # some service class ... def _convert_to_webp(self, f_object: InMemoryUploadedFile): new_file_name = str(Path(f_object._name).with_suffix('.webp')) temp_file = tempfile.NamedTemporaryFile(suffix='.temp.webp') # FIXME: on other OS may cause FileNotFoundError with open(temp_file 'wb') as f: for line in f_object.file.readlines(): ... # will it works good? new_file = ... new_f_object = InMemoryUploadedFile( new_file, f_object.field_name, new_file_name, f_object.content_type, f_object.size, f_object.charset, f_object.content_type_extra ) return new_file_name, new_f_object ... f_object is InMemoryUploadedFile instance from POST request body (Django automatically create it). My idea is to create a temporary file, write data from f_object.file.readlines() to it, open this file with PIL.Image.open and save with format="webp". Is this idea a good one or there is another way to make file converting? -
ModuleNotFoundError: No module named 'winreg' on Mac? (But winreg is a windows thing)
I am receiving the following error when I try to run a django shell. I am on a Mac though and everything that I can find says that this is associated with Windows and that winreg should be installed by default. Suggestions as to what I should be looking at? Traceback (most recent call last): File "/Users/j/code/myproject/core/manage.py", line 22, in <module> main() File "/Users/j/code/myproject/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/shell.py", line 127, in handle exec(sys.stdin.read(), globals()) File "<string>", line 5, in <module> ModuleNotFoundError: No module named 'winreg' -
Why can't I use "profile" as an app name?
I need a profile to extend the Django User object, so I thought to create an app to contain the profile object and related views then proceed as per the Django doc, but I get ./manage.py startapp profile CommandError: 'profile' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I don't have an app called profile in INSTALLED_APPS and I don't know what context this message should be interpreted in. Can anybody help? (Yes, I could call it userprofile or xxx_profile instead, but I'd like to understand why I need to) -
Unable to view database object in django in html
The object in the database is not visible in the html. Model class OutFormatTemplate(models.Model): title = models.CharField(max_length=80) template = models.FileField(upload_to='out_put_temp/') def __str__(self): return f"{self.title}" View def upload_form(request): out_form = OutFormatTemplate.objects.all() for i in out_form: print(i.id, i.title) form = UploadBookForm() context = { 'form': form, 'outform': out_form } return render(request, 'file_uploader.html', context) HTML {% if outfrom %} <p>Out Form Exist</p> {% else %} <p>Not Exist</p> {% endif %} <div class="mt-2" id="out-template"> <label for="template-out" class="form-label">Select Output Template</label> <select class="form-select" aria-label="Default out select example" name="out_template_id" id="template-out"> <option value="0" selected></option> {% for out in outfrom %} <option value="{{ out.id }}">{{ out.title }}</option> {% endfor %} </select> </div> The database value Table values But in the webpage these values are not shown Form Iam new to django, I need help. Have i done anything wrong here. -
python decimal place changes after 0
hello, i am new one in programming i am sending a request from postman with payload {"member_id":10,"value": 30.00} but when i receiving it in api by using request.data {'member_id': 10, 'value': 30.0} the decimal place changes to 1 position after zero but i need same decimal values as sending in request which i need to verify signature. thanks -
How to update foreign key value django
Let say I have following models: models.py First of all I have to do a subtraction between quantity_in_store (from stockList models) and shipping_qty(from stockout models) and to get the final quantity that left in store. However, I have get the final quantity but I would like to update the value of final quantity into the quantity_in_store(from stockList models) How would I go about doing this? Thanks admin.py