Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django uploads Gif as JPG despite a function to add it as video
I'm trying to upload a .gif to my django 3.2 api. I have already ran troubleshoots through Postman and came to the conclusion that my flutter app sends it as a .gif and it gets returned as a .jpg. The problem is on the backend. Here is my relevant code from add media function which checks for file_meme subtype and converts the incoming .gif to a video(There is a separate block for checking if its video and add the video) : def add_media(): if file_mime_subtype == 'gif': if is_in_memory_file: file = write_in_memory_file_to_disk(file) temp_dir = tempfile.gettempdir() converted_gif_file_name = os.path.join(temp_dir, str(uuid.uuid4()) + '.mp4') ff = ffmpy.FFmpeg( inputs={file.temporary_file_path() if hasattr(file, 'temporary_file_path') else file.name: None}, outputs={converted_gif_file_name: None}) ff.run() converted_gif_file = open(converted_gif_file_name, 'rb') temp_files_to_close.append(converted_gif_file) file = File(file=converted_gif_file) file_mime_type = 'video' has_other_media = self.media.exists() self.save() I'm not sure where the problem is. From my limited understanding, it is taking only the first frame of the .gif and uploading it as an image. -
How to upload multiple images or files in a single input field using Django forms?
Could you please provide more context or specific details about the issue you're facing with Django forms? This will help me understand your problem better and provide you with a more accurate solution. I attempted to implement the MultiFileInput widget from the django-multiupload package within my Django form. I expected the widget to allow users to upload multiple images or files through a single input field. However, I faced challenges integrating this widget within my existing form structure. While the widget appeared on the page, I couldn't figure out how to handle the uploaded files and save them to the database. The documentation for the package lacked detailed examples for this specific use case. n short, I tried using the MultiFileInput widget but struggled with its integration and file handling. Any guidance or code snippets to achieve this functionality would be greatly appreciated -
Multiple User Foreign Keys to Same Model?
I'm attempting to create a simple web application (first django personal project) for my friends and I to log our casual sporting bets against eachother. Currently I have the model like this using django's auth User model: class Bet(models.Model): bettor1 = models.ForeignKey(User, related_name='bets', on_delete=models.CASCADE) bettor2 = models.CharField(max_length=256) bet_description = models.TextField() bet_amount = models.PositiveIntegerField() win_amount = models.PositiveIntegerField() create_date = models.DateTimeField(auto_now=True) Currently bettor1 is correctly linked to the user that is logged into the application, but I would like to make it so that bettor 2 is also a foreign key (i think?) connecting to another user's account that exists on the application. (So bettor 1 can choose the opponent he is wagering against from a dropdown menu of the other users with existing accounts). How can I do this? Tried setting another foreign key to user but got errors. Not sure how this is done. -
Non existing value for foreign key in django
I would like know if I can make django accept values for foreign key that doesn't exist in the column referenced. The problem in the business logic is that a model can point to the phone number of a user that doesn't exist yet -
cannot import name in a file?
Hello I am trying to run my django application but its saying: cannot import name 'd' from 'niu' (C:\Users\amber\Umaido\niu_init_.py) which is strange. I have created d in my code file: [ and importet it than into views.py ( The problem now is that it usually works on the Terminal but my Command prompt Terminal is telling me that its an error. I have tried to change form code import d to from . import d but it does not work either -
How to reload the app on Django after changed files?
I have been studying Django lately. The novice tutorials are good, but from a student perspective, there are some steps which are black boxes. One of them is file monitoring: every time I need to update the application, my heart beats faster, I stop the ongoing process and run python manage.py runserver. In real world, I have worked with solutions using Django, but was never clever enough to know how the github pull requests would update the actual hosted app. Would you please help me understand this knowledge gap? Remark: On NodeJS, we use the library nodemon to monitor changes on files. -
Why am I not receiving any data from my forms when using a dropdown with django
Hi guys I'm trying to create a form with a dropdown and other fields, I'm trying to get the data from the form but for some reason I'm not getting anything This the template tha I'm using {% extends "main_page_layout.dj.html" %} {% block content %} <form id="comunicate" method="post">{% csrf_token %} <select name="company"> {% for company in companies %} <option value={{company.id}}>{{ company.name }}</option> {% endfor %} </select> <button id="comunicate" type="submit">Submit</button> </form> {% endblock %} I'm using this piece of code to try to get the data from the form but it's not working This is the form that I'm using in django class PruebaForm(forms.Form): company = company = forms.ModelChoiceField( queryset=CompanyInfo.objects.all(), widget=forms.Select(attrs={"hx-get": "/load_users/", "hx-target": "#id_user"}), ) user = forms.ModelChoiceField( queryset=UserLicense.objects.all(), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['user'].queryset = UserLicense.objects.none() if "company" in self.data: company_id = self.data.get('company') self.fields["user"].queryset = UserLicense.objects.filter(company_id=company_id) If someone can explain why I'm not getting anything it would be helful since I'm new with this -
Slice capacity in go
I recently studying go in w3schools and I can't able to understand capacity of slice in go? How the cap() of myslice1 is 12.Slice in go I expect that the cap() of myslice1 is 8 because I append the two numbers on previously created slice.But the cap() myslice1 before append is 6. And after appended the cap()of myslice is 12. -
I can't link CSS file to HTML file in Django project
HTML file is working well. But it's not linking with CSS, what I make in CSS simply does not work. HTML PAGE <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TheWebPub</title> <link rel="stylesheet" href="stylepage.css"> </head> <body> {% if name %} <h1 class='title'>Hello {{name}}. </h1> {% else %} <h1>Hello world.</h1> {% endif %} <p>Thank you for being here in my website, it's my first one. I'm creating this website with django/python.</p> </body> </html> everything seems to be ok. it's my views.py file in my django project from django.shortcuts import render from django.http import request # Create your views here. def say_hello(request): return render(request, 'index.html', {'name':'Adryan'}) -
In Edit-Form I must enter a tab to make fields return with values but they return "None" where I didn't enter them tabs in django forms
I have a problem with my forms (I fixed it) by an idea I’ll mention here, But I think I miss something or Django Forms have a another good solution for it. I have one page with(many tabs and as a result many forms and many inputs also). All forms must save by one save button under one form <form class="add-product-form"></form> And <form class="edit-product-form"></form> The next image illustrate what I mean. My Problem : In add-product-form everything is OK(Saving process has been done perfectly till now) but in edit-product-form I noticed that (Any inputs present in a tab I don’t enter, every input in this tab return "None" and the update process of edit-product-form leads to make the original data that I have saved in add-product-form return to None or to default - As clean_field(self) method stated) Here is some of code of my forms.py file class ProductForm(forms.ModelForm): name = forms.CharField( required=False, widget=forms.TextInput( attrs={ # "class": "form-control", "placeholder": "Write the product English name here ...", } ), ) name_ar = forms.CharField( required=False, widget=forms.TextInput( attrs={ # "class": "form-control", "placeholder": "Write the product Arabic name here ...", } ), ) class Meta: model = Product fields = ( 'name', 'name_ar', 'branch', 'pos_station', … -
Django model's string representation creates duplicates queries
Working on Airport API Service task. Can not solve N+1 problem for Flights: moldels.py: class Flight(models.Model): route = models.ForeignKey(Route, related_name="flights", on_delete=models.CASCADE) airplane = models.ForeignKey(Airplane, related_name="flights", on_delete=models.CASCADE) crew = models.ManyToManyField(Crew, related_name="flights") departure_time = models.DateTimeField() arrival_time = models.DateTimeField() class Meta: ordering = ["departure_time"] def __str__(self): return f"{self.route} ({self.departure_time})" serializers.py: class FlightListSerializer(FlightSerializer): route = serializers.StringRelatedField(many=False, read_only=True) airplane_name = serializers.CharField(source="airplane.name", read_only=True) tickets_available = serializers.IntegerField(read_only=True) class Meta: model = Flight fields = ( "id", "route", "airplane_name", "departure_time", "arrival_time", "tickets_available", ) views.py: class FlightViewSet(viewsets.ModelViewSet): queryset = Flight.objects.all() serializer_class = FlightSerializer permission_classes = (IsAdminOrIsAuthenticatedReadOnly,) def get_queryset(self): queryset = self.queryset if self.action == "list": queryset = ( queryset .select_related("airplane", "route__destination", "route__source") .annotate( tickets_available=( F("airplane__rows") * F("airplane__seats_in_row")) - Count("tickets") ) ) return queryset return queryset def get_serializer_class(self): if self.action == "list": return FlightListSerializer # if self.action == "retrieve": # return TripDetailSerializer return FlightSerializer Problem: I checking endpoint with debug_toolbar and it shows 7 duplicates. Before it was much more, but I fixed some by add selected_related method and decrease it from 25 to 17. I noticed, that this problem comes from "route" field. This is Route model: class Route(models.Model): source = models.ForeignKey( Airport, on_delete=models.CASCADE, related_name="sources" ) destination = models.ForeignKey( Airport, on_delete=models.CASCADE, related_name="destinations" ) distance = models.IntegerField() class Meta: unique_together … -
Django symmetrical tabularinline m2m
Just starting in Python/Django framework so sorry if this is dumb... but i cant find any solution. model.py class Apk(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, unique=True, verbose_name='XXXX') class ListProductConnections(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey(Apk, on_delete=models.CASCADE) related_products = models.ManyToManyField(Apk, related_name='related_product', verbose_name='Є компонентом',) My admin.py class ListProductConnectionsInline(admin.TabularInline): model = ListProductConnections filter_horizontal = ('related_products',) extra = 0 max_num = 1 verbose_name = 'XXX' verbose_name_plural = 'XXX' class ListProductConnectionsForm(forms.ModelForm): class Meta: model = ListProductConnections fields = '__all__' related_products = forms.ModelMultipleChoiceField( queryset=Opk.objects.all(), widget=FilteredSelectMultiple('YYY', is_stacked=False), required=False, ) def __init__(self, *args, **kwargs ): super().__init__(*args, **kwargs) current_product_id = ListProductConnectionsReversInline.global_variable if current_product_id is not None: related_products_data = ListProductConnections.related_products.through.objects.filter( opk_id=current_product_id ).values_list('listproductconnections_id', flat=True) related_products_data_new = ListProductConnections.objects.filter(id__in=related_products_data).values_list('product_id', flat=True) initial_product_ids = list(related_products_data_new) self.initial['related_products'] = initial_product_ids class ListProductConnectionsReversInline(admin.TabularInline): model = ListProductConnections form = ListProductConnectionsForm extra = 0 max_num = 1 verbose_name = 'YYY' verbose_name_plural = 'YYY' global_variable = None def get_formset(self, request, obj, **kwargs): formset = super(ListProductConnectionsReversInline, self).get_formset(request, obj, **kwargs) try: self.__class__.global_variable = obj.id except: pass return formset @admin.register(Opk) class OpkAdmin(ImportExportModelAdmin): form = FactoryForm .... inlines = [ListProductConnectionsInline, ListProductConnectionsReversInline] I have a Product, and I want to do the following: In the ListProductConnectionsInline, select which Products use the Product we are currently editing. This is working perfectly now. In the ListProductConnectionsReversInline, select … -
A testcase for a guest user trying to edit another user's post
I'm working on a Web site (in Django) which is a very simple social network with authentication (i.e. if you want to edit a post you should login into the Web site, although you can see all the posts even if you aren't logged into the site). I´m preparing a set of testcases for my Web site and I would like to include one for a guest user cannot edit another user's post (e.g. a user who is not logged in into the Web site is not able to edit any post). How can I get it? Below my code: urls.py (app) from django.urls import path from . import views #app_name = "network" urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newPost", views.newPost, name="newPost"), path("profile/<int:user_id>", views.profile, name="profile"), path("unfollow", views.unfollow, name="unfollow"), path("follow", views.follow, name="follow"), path("following", views.following, name="following"), path("edit/<int:post_id>", views.edit, name="edit"), path("remove_like/<int:post_id>", views.remove_like, name="remove_like"), path("add_like/<int:post_id>", views.add_like, name="add_like"), ] urls.py (project) from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("", include("network.urls")), ] views.py def index(request): allPosts = Post.objects.all().order_by("id").reverse() # Pagination paginator = Paginator(allPosts, 10) page_number = request.GET.get('page') posts_of_the_page = paginator.get_page(page_number) # Likes allLikes = Like.objects.all() whoYouLiked = [] try: for … -
Redirect To Root Not Happening In Custom User Login View function
I am newbie to python and Django. I tried every tool (chatgpt, Youtube, blogs) but I was unable to find the solution. Problem Statement: When I fill the sign-up form, after submission, I am directed to login page. Here when I enetr correct credentials, instead of redirecting me to "home" view function, the login page remain appearing/stayed on the screen.I asked Chatgpt, according to it, redirection is not happening properly. Please help when I typed correct credentials in login form and hit the submit button following error appears in the terminal [27/Aug/2023 05:22:34] "POST /login/ HTTP/1.1" 200 1078] Models.py from django.db import models from django.contrib.auth.models import AbstractUser,Group, Permission class CustomUser(AbstractUser): email = models.EmailField("email address", unique=True) username= models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text= 'Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, null=True, verbose_name='username') groups = models.ManyToManyField( Group, verbose_name='groups', blank=True, help_text='The groups this user belongs to.', related_name='custom_users', # Add a unique related_name ) user_permissions = models.ManyToManyField( Permission, verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name='custom_users', ) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['username'] Forms.py from django import forms from .models import CustomUser class SignUpForm(forms.ModelForm): class Meta: model = CustomUser fields = ("username", 'password', "email",'first_name', 'last_name',) … -
Server error(500) after deployment to railway in django
I was working on A Django project and it worked perfectly fine on the local server, especially when it came to form handling like user signup, login even admin login. But after I deployed it to Railway, first i got the error of csrf token, so it could not load any forms, which i solved with CSRF_TRUSTED_ORIGINS = ['https://domain_name.com'] which worked and now the forms load up but when after I fill in the details, the admin login, user sign up and login pages, and I hit the save but it throws back and error "SERVER ERROR(500)" I am really confused on what to do... someone please point me in the right direction please -
problem with logic in django code. read data from redis and database
I have this django code and it take data from redis by inscode and return. if redis is down it should jump out of try,expect block and read data from database (postgresql). class GetOrderBook(APIView): def get(self, request, format=None): # get parameters inscode = None if 'i' in request.GET: inscode = request.GET['i'] if inscode != None: try: #raise ('disabling redis!') r_handle = redis.Redis( host=r_handles['orderbook_host'], port=r_handles['orderbook_port'], socket_timeout=REDIS_TIMEOUT, charset='utf-8', decode_responses=True) data = r_handle.get(inscode) if data != None: return Response(json.loads(data), status=status.HTTP_200_OK) else: print('GetOrderBook: data not found in cache') except BaseException as err: print(err) orderbook = OrderBook.objects.filter( symbol__inscode=inscode).order_by('rownum') if len(orderbook) > 0: data = OrderBookSer(orderbook, many=True).data data_formatted = {'buynum': [0]*5, 'buyvol': [0]*5, 'buyprice': [ 0]*5, 'sellnum': [0]*5, 'sellvol': [0]*5, 'sellprice': [0]*5} for row in data: rownum = row['rownum'] - 1 data_formatted['buynum'][rownum] = row['buynum'] data_formatted['buyvol'][rownum] = row['buyvol'] data_formatted['buyprice'][rownum] = row['buyprice'] data_formatted['sellnum'][rownum] = row['sellnum'] data_formatted['sellvol'][rownum] = row['sellvol'] data_formatted['sellprice'][rownum] = row['sellprice'] return Response(data_formatted, status=status.HTTP_200_OK) else: return Response({'Bad Request': 'invalid input'}, status=status.HTTP_404_NOT_FOUND) return Response({'Bad Request': 'incomplete input data'}, status=status.HTTP_400_BAD_REQUEST) but problem is that it not reading from database also I write this test for it to return 200 if you read data. but when redis is down it dont read data and return 404 to me . def test_redis_function(self, … -
When I migrate I get this error django.db.utils.DataError: value too long for type character varying(10)
your text Encountering "The specified object could not be found" error during Django migrations. Tried various solutions, including rolling back migrations, resetting the database, and checking foreign keys. Still seeking a resolution. -
How to set up webpack to compile multiple separate vue apps into separate js bundles
I'm trying to configure webpack to compile and bundle small standalone Vue apps (each in their own separate subdirectory) once, automatically from the top level, without having to set up web pack etc inside each of these directories and manually running an npm run build inside of each of them. How can I achieve this? Below is my directory structure (the Django subdirectories are not relevant so I've left them out): . ├── db.sqlite3 ├── front-end │ ├── App.vue │ ├── assets │ ├── components │ └── main.js ├── manage.py ├── node_modules/ ├── package-lock.json ├── package.json ├── django_project/ ├── django_app/ ├── static (where i want all the outputs to go) │ ├── d61e288f5de33456b33fb3c47275f16c.png │ └── index-bundle.js └── webpack.config.js (id like this top level config to be the only one required to bundle everything) My top level web pack config looks like the following, but currently is only for one Vue app (front-end), whereas I'd like to ideally have several apps under their own subdirs there instead: const path = require('path'); const {VueLoaderPlugin} = require('vue-loader') module.exports = { entry: './front-end/main.js', // path to our input file output: { filename: 'index-bundle.js', // output bundle file name path: path.resolve(__dirname, './static'), // path to … -
CS50W project 4 network getting started problem
I got a problem while starting project network it tells me : no such table:network_user although i followed the instructions of getting started section and ran commands pythons manage.py makemigrations network and python manage.py migrate. I noticed when i ran the command for migrating i was rendered an error :File "C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line 310, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency network.0001_initial on database 'default'. and when i run the server and try to register it tells me no such table network_user -
Passing data from Django to React
Im trying learn django and react and im doing so by trying to create a web app using spotify api to display top tracks and top artists for users. I have successfully connected to the api and created a view to extract the data I need and have created a template navigating through different time frames etc but i was wondering how i would now use React to build the frontend and how to pass the data to react. this is my current view to retrieve the users top tracks data: def top_track(request): code = request.session.get('spotify_code') time_frame = request.GET.get('time_frame', 'short_term') # Retrieve timeframe parameter from URL, Default to 'short_term' limit_frame = request.GET.get('limit_frame', 20) if code: request.session['spotify_code'] = code spotify_auth = SpotifyOAuth( client_id=settings.SPOTIPY_CLIENT_ID, client_secret=settings.SPOTIPY_CLIENT_SECRET, redirect_uri=settings.SPOTIPY_REDIRECT_URI, ) token_info = spotify_auth.get_access_token(code) access_token = token_info['access_token'] sp = spotipy.Spotify(auth=access_token) # Fetch data using the token and the selected time frame top_tracks = sp.current_user_top_tracks(limit=limit_frame, time_range=time_frame) # Track info dictionary track_info = [] for track in top_tracks['items']: track_id = track['id'] album = sp.track(track_id)['album'] album_cover = album['images'][0]['url'] artist_name = track['artists'][0]['name'] track_info.append({ 'track': track, 'album_cover': album_cover, 'artist_name' : artist_name, }) timeframe = " " if time_frame == "short_term": timeframe = "1 Month" elif time_frame == "medium_term": timeframe = "6 … -
How can we pass the data pages into to layouts partials file in Django
Layouts.html <div class="ispl-header js-ismHeader"> {% include './partials/_breadcrumbs.html' %} </div> Child Pages `{% extends 'layouts.html'%} {% endblock %} {% block breadcrumb %} <li>Test1</li> <li>Test12</li> <li>Test3</li> {% endblock %} ` partials/_breadcrumbs.html <ol class="breadcrumb ispl-admBreadcumb_listing"> {% block breadcrumb %}{% endblock %} </ol> breadcrumb not printing child page data Trying to print data into partial file -
Add second row of model data below Django select menu choice
I have all of my choices rendering in the dropdown menu but I was wondering if it was possible to add a second row of descriptive subtext below each choice that shows in the menu. class FootballLineup(forms.ModelForm): class Meta: model = FootballContestEntry fields = ['qb'] qb = forms.ModelChoiceField(label='', queryset=NFLPlayer.objects.filter(active=True, position='QB'), empty_label="Select Quarterback", required=True) qb.widget.attrs.update({'class': 'text-center lineup-select marker'}) -
PermissionError: [WinError 5] Access is denied whenever I run anything in python manage.py
Im relatively new to django and I got this error two days ago and tried everything to fix it. I tried to run as administrator and it did not work, and i tried re installing python and it didn't work as well. Also, I reintsalled the virtual environment and it didn't work as well. I read a couple of articles including https://sebhastian.com/environmenterror-winerror-5-access-is-denied/ https://gameofthrones-croatia.com/permissionerror-winerror-5-access-is-denied/ And i still couldn't figure it out. Traceback (most recent call last): File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File … -
I'm getting an error while installing 'mysqlclient' for a Django project on Ubuntu. Can anyone please help me fix this error?
Installing mysqlclient... Resolving mysqlclient... Adding mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Resolving dependencies... ✘ Locking Failed! ⠴ Locking... ERROR:pip.subprocessor:[present-rich] Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 704, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 662, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 642, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 1167, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 948, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 690, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run $ pipenv graph to inspect the versions actually installed in the virtualenv. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Getting requirements to build wheel exited with 1 I've used this command "sudo apt-get install python3-dev default-libmysqlclient-dev build-essential" and tried to install mysqlclient. But I get the same error. -
Django Crontab Job Not Executing Within Docker Container
I am facing an issue with running Django crontab jobs within a Docker container. The crontab jobs work perfectly in my local development environment, but when I dockerize my Django app and attempt to run it within a container, the crontab jobs do not seem to execute as expected. Here's a breakdown of the setup and the problem I'm encountering: Local Development (Working): In my local development setup, I have added the following configuration to my Django settings: THIRD_PARTY_APPS = [ "django_crontab", ] CRONJOBS = [ ("* * * * *", "apps.{path}.jobs.deactivate_expired_enrollments"), ] This configuration sets up a crontab job that deactivates expired course enrollments. The crontab job works perfectly in this environment. Docker Setup: To dockerize my Django app, I've created a Dockerfile and a start.sh script as part of my Docker Compose configuration: Dockerfile: # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # Installing cron cron \ RUN touch /var/log/cron.log RUN (crontab -l ; echo "* * * * * echo 'Hello world' >> /var/log/cron.log") | crontab # Run the command on container startup CMD cron && tail -f /var/log/cron.log start.sh: #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py …