Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I input current date and time in Django?
So I'm a beginner in Django, and recently came up with a question, regarding datetime. So I'm trying to make a blog-like page. And among the input fields, including title and contents, I want a datetime field as well. However, there is an additional feature that I want to create, which is -- if the user clicks a checkbox right next to the datetime input field, the datetime will automatically change into the CURRENT date and time. So the input field is replaced with the current date and time. I have no idea on how to create the feature. I would very much appreciate your help :) -
Will the delete function be triggered if on_delete is set to models.PROTECT?
I am trying to implement a behavior where when I am trying to delete an instance, the instance will not be deleted but django will set an attribute called deleted to True. However, when I am trying to define a foreign key, I have to set on_delete because it is required. I set it to models.PROTECT. My question is: Will django trigger my overridden delete function while setting on_delete to models.PROTECT? Here is an example code: class BaseModel(models.Model): deleted = models.BooleanField(default=False) def delete(self): self.deleted = True self.save() class A(BaseModel): pass class B(BaseModel): a = models.ForeignKey('A', on_delete=models.PROTECT) -
Django Python Seat Selector User Interface
I'm trying to replicate something similar to this. I know a few websites that do this type of seat selection movie theatres, airlines, etc. How can I accomplish something like this? Are there any examples out there for accomplishing this is Django and Python? -
DRF: using partial update common case
I use the partial_updae method to update the instance. I understand the logic of how to change and save a specific field or fields. That's how it's done for vendor_name field serializer.py class VendorManagementUpdateSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) parent = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = Vendors fields = ('vendor_name', 'active', 'country', 'nda', 'parent', 'contacts',) def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.save() return instance views.py class VendorProfileUpdateView(generics.RetrieveUpdateAPIView): permission_classes = [permissions.AllowAny, ] serializer_class = VendorManagementUpdateSerializer lookup_field = 'vendorid' def get_queryset(self): vendorid = self.kwargs['vendorid'] return Vendors.objects.filter(vendorid=vendorid) def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) data { "vendor_name": "Tesddt7t2test" } That is, I get the value of the field I need from validate_data and manually replace it with instance in the def update() method. def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.save() But if I have, for example, 10 model fields and plus ForeignKey connections with other models, should I describe for all fields the same logic as for vendor_name and catch exceptions if the field was not passed to the request? def update(self, instance, validated_data): instance.vendor_name = validated_data.get('vendor_name', instance.vendor_name) instance.nda = validated_data.get('nda', instance.nda) ..... ..... instance.save() Or is there a way to write such functionality in a more … -
Basic question alert - Can script in Jupyter be called to use in Django/HTML
I have created some python script in a jupyter notebook that displays bushfires on mapbox, using a google sheet as a database - works great and takes an input for the user id to load user specific content. I want to take this online so users can login and interact. Presumed Django would be the best bet for this so created a project in pycharm. Is there a way to simply add the script in from the jupyter notebook. - This is a high level question (as i have a lack of 'systems' understanding being new to code), I just want to understand if I need to start from scratch and create an SQL database for Django, or if i can use what i have done in Jupyter so far. In my head, creating a compartment in HTML in pycharm for this bit of script and then being able to call it would be the (likely unrealistic) dream -
Objects not deleting
I have several ViewSets.They have one serializer and model. For example - ViewSet "Posts" and "Favorites". If I use DELETE request on Post object, he is deleted from "Posts", but in Favorites, I can see them. BUT, every object has a "URL" field. So, if some object from "Posts" will be deleted, then in "Favorites" I will see it and if I go to the link from the "URL" field, then I get "404 not found". Why does it happen? Model: class Post(models.Model): name = models.CharField(verbose_name='name', db_index=True, max_length=64) city = models.CharField(verbose_name='city', db_index=True, max_length=64) created = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(default=next_month, blank=True, editable=False) description = models.CharField(verbose_name='description', db_index=True, max_length=64) isFan = models.BooleanField(null=True) main_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) first_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) second_image = models.ImageField(upload_to=get_auth_dir_path, null=True, max_length=255) ViewSets: class PostViewSet(LikedMixin, viewsets.ModelViewSet): queryset = Post.objects.is_actual().order_by('-created') serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication, ) filter_backends = (DjangoFilterBackend, ) filterset_fields = (...) def perform_create(self, serializer): serializer.save(author=self.request.user) class ClosedPostViewSet(LikedMixin, viewsets.ModelViewSet): queryset = Post.objects.is_not_actual().order_by('-end_time') serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication,) filter_backends = (DjangoFilterBackend,) filterset_fields = (...) def perform_create(self, serializer): serializer.save(author=self.request.user) class SearchViewSet(LikedMixin, viewsets.ModelViewSet): pagination_class = None queryset = Post.objects.is_actual() serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication, ) filter_backends = (DjangoFilterBackend, ) filterset_fields = (...) def list(self, request, … -
3.5 hours in and still cannot install Django - my fortitude is waning
Hi and thank you for taking time out of your day to read this, and I very much appreciate any assistance. I'm trying to install Django for the first time - on a mac, python 3.7.7. However, the packages seem to be looking for 2.7 which is not the intended v3. I understand the best practice is to install this via a virtual environment. I am currently following this link. When I run mkvirtualenv my_django_environment I get this error: Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master return cls._build_from_requirements(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'zipp>=0.4' distribution was not found and is required by importlib-resources I've tried this mkvirtualenv -p /usr/local/bin/python3 my_django_environment Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set … -
customize user modification form django admin site
When you create/modify a user from the django admin site you have this interface : My project is quit simple because I have no group and every staff user could have superusers satus. That is why I want not to show the superuser status option, neither groups and user permissions. How to mask this sections of this form and assert that all staff users also superusers are. Any help would be very appreciated. Thanks in advance ! -
raise ValidationError doesn't work. Dgango
Anyone who can explain me, why my ValidationError in my form doesn't work? I can see "TEXT" in my terminal, but the ValidationError doesn't show. Forms.py def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') new_name = cleaned_data.get('name') if Student.objects.filter(room=new_room).count() > 3: if not Student.objects.filter(room=new_room, name__icontains=new_name): print('TEXT') raise ValidationError('The room is full') It’s also worth noting that a similar def clean_room(self): function works fine in my code. In this function, raise ValidationError works correctly. def clean_room(self): new_room = self.cleaned_data['room'] if new_room == '': raise ValidationError('This field cannot be empty') return new_room Full length code: class CheckInForm(forms.ModelForm): class Meta: model = Student fields = ['room', 'name', 'faculty', 'place_status', 'form_studies', 'group', 'sex', 'mobile_number', 'fluorography', 'pediculosis', 'contract_number', 'agreement_date', 'registration', 'citizenship', 'date_of_birthday', 'place_of_birthday', 'document_number', 'authority', 'date_of_issue', 'notation' ] widgets = {'room': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'faculty': forms.TextInput(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super(CheckInForm, self).clean() new_room = cleaned_data.get('room') new_name = cleaned_data.get('name') if Student.objects.filter(room=new_room).count() > 3: if not Student.objects.filter(room=new_room, name__icontains=new_name): print('TEXT') raise ValidationError('The room is full') def clean_room(self): new_room = self.cleaned_data['room'] if new_room == '': raise ValidationError('This field cannot be empty!') return new_room -
Django loop by groups
I am having trouble on looping in django template, loop by its particular group This is my html {% for behavior in behaviors %} <tr> <td rowspan="2" colspan="4" class="tblcoretitle">{{behavior.Grading_Behavior.Grading_Behavior.Name}}</td> <td colspan="4" class="tblcore">{{behavior.Grading_Behavior.Grading_Behavior.Description}}</td> <td class="tblcore">{{behavior.Marking}}</td> </tr> {% endfor %} this is my views.py Students = StudentPeriodSummary.objects.filter(Teacher = teacher) studentbehaviors = StudentsBehaviorGrades.objects.filter(Teacher = teacher)\ .filter(Students_Enrollment_Records__in=Students.values_list('id')).distinct('Grading_Period').values('Grading_Period').order_by('Grading_Period') behaviors = StudentsBehaviorGrades.objects.filter(Teacher=teacher) \ .filter(Students_Enrollment_Records__in=Students.values_list('id')) This is my table in Django admin StudentsBehaviorGrades This is my current result this is I want result -
Pip install matplotlib gives Microsoft Visual Studio error when visual studio already installed
I am making a django application. Recently i have had problems with using pip. It can no longer install librarys whithout errors about Microsoft Visual Studio C++ build tools... The first time it was because i hadnt installed it, so the i did just that with the link pycharm suggested: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ After installing the C++ build tools, i still get a related error. This is what i get after running "pip install matplotlib": C:\Users\augbi\PycharmProjects\untitled1>pip install matplotlib Collecting matplotlib Using cached https://files.pythonhosted.org/packages/4a/30/eb8e7dd8e3609f05c6920fa82f189302c832e5a0f6667aa96f952056bc0c/matplotlib-3.2.1.tar.gz Requirement already satisfied: cycler>=0.10 in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from matplotlib) (0.10.0) Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from matplotlib) (1.1.0) Requirement already satisfied: numpy>=1.11 in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from matplotlib) (1.18.2) Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from matplotlib) (2.4.6) Requirement already satisfied: python-dateutil>=2.1 in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from matplotlib) (2.8.1) Requirement already satisfied: six in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from cycler>=0.10->matplotlib) (1.14.0) Requirement already satisfied: setuptools in c:\users\augbi\pycharmprojects\untitled1\venv\lib\site-packages (from kiwisolver>=1.0.1->matplotlib) (46.0.0) Installing collected packages: matplotlib Running setup.py install for matplotlib ... error Complete output from command C:\Users\augbi\PycharmProjects\untitled1\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\augbi\\AppData\\Local\\Temp\\pip-install-pp8ywr9g\\matpl otlib\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\augbi\AppData\Local\Temp\pip-record-ri 8_ja0m\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\augbi\PycharmProjects\untitled1\venv\include\site\python3.8\matplotlib: Edit setup.cfg to change the build options; … -
Using pool.map in an api call, calls the api again
I am using pool.map in a function which parallely calls a function on different chunks of dataframe. I am using this in Django API. From my API call, a call is made to parallelize_df function which creates pool and pool.map. But I have observed that whenever pool.map is called , the API is called again. This is not an issue when dataframe size is small. Can anyone please help Code: def parallelize_df(df, function_name): dataframe_split = np.array_split(df, DssConfig.num_partitions) pool = Pool(multiprocessing.cpu_count()) df = pd.concat(pool.map(function_name, dataframe_split)) pool.close() pool.join() return df def calculate(df_input): # do some calculation return df -
Django Channels cancel coroutine messages
hi i'm developing application with django.I readed all documentation offical Django Channels documentation and couldn't find. When User connected to consumer i am adding user to group . And when changed model instance i send signal in consumer to every client instance in group but I send the signal all the time so my problem starts here I want the previous messages cancel when I send the signal. I just want the last messages I sent to the group to go. I couldn't find a way to solve it from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from channels.exceptions import DenyConnection from main.consumers import AsyncWebsocketConsumer from auctions.models import Auction, Lot, AuctionBid, AuctionReport, AuctionSaloon, LandLot, HouseLot, Deposit, UserFlag, Participant from liveauction.serializers import ROAuctionBidSerializer, ROAuctionSerializer, ROHouseLotSerializer, ROLandLotSerializer, ROLotSerializer, ROParticipantSerializer, ROFlagCoverageRangeSerializer, RONormalAuctionSerializer from django.core.exceptions import ObjectDoesNotExist import json import asyncio class AuctionConsumer(AsyncWebsocketConsumer): active_auction = None active_lot = None permissions = [] channel_groups = [] flag_coverage_ranges = [] async def connect(self): if self.scope['user']: user = self.scope['user'] print(self.scope['user']) if user.is_anonymous: await self.close() else: self.active_auction = await self._get_active_auction() print(self.active_auction) if self.active_auction is not None: print(self.active_auction.get_channel_name()) self.channel_groups.append(self.channel_layer.group_add( self.active_auction.get_channel_name(), self.channel_name)) asyncio.gather(*self.channel_groups) self.permissions = await self._get_user_permission(self.scope['user']) self.flag_coverage_ranges = self.active_auction.flag_coverage_ranges.all() await self.accept() else: await self.close() async def disconnect(self, code): asyncio.gather(*self.channel_groups) … -
'str' object has no attribute 'key' django drf
i have this model city and trying to get foreign table data geeting models.py: class City(BaseModel): name = models.CharField(_("City Name"), max_length=80, null=False, blank=False) state_name = models.ForeignKey(State, to_field="uid", on_delete=models.DO_NOTHING, max_length=55, null=False, blank=False) city_type = models.ForeignKey(TypeOfCity, to_field="key", on_delete=models.DO_NOTHING, max_length=15, null=False, blank=False) city_tier = models.ForeignKey(CityTier, to_field="key", on_delete=models.DO_NOTHING, max_length=10, null=False, blank=False) status = models.SmallIntegerField(_("Status: 1 for Active; 0:Inactive"), default=1) class TypeOfCity(models.Model): key = models.CharField(verbose_name=_("key"), max_length=15, unique=True) value = models.CharField(verbose_name=_("value"), unique=True, max_length=15) status = models.SmallIntegerField(_("status:1 for Active; 0: Inactive"), default=1) views.py: @api_view(['POST']) def cityFetch(request): try: data =decode_data(request.data.copy()) try: queryset = City.objects.filter(uid=data['uid']).values('name','city_type','city_type__value','status') serializer_obj = CitySerializer(queryset,many=True) return CustomeResponse(request=request, comment="Get Single City", message="Get Single City", data=json.dumps(serializer_obj.data, cls=UUIDEncoder), status=status.HTTP_200_OK) except City.DoesNotExist: return CustomeResponse(request=request, comment="City Not Found", message="City Not Found",data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) except Exception as e: print(e) error_str = UID_KEY_IS_MISSING if type(e) is KeyError else UID_IS_NOT_VALID return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), comment=error_str, message=error_str, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) I am getting this queryset: <QuerySet [{'name': 'test', 'city_type': 'normal_city', 'city_type_id__value': 'Normal City', 'status': 1}]> but maybe its trying to find key and i am getting this error: 'str' object has no attribute 'key' -
Django dynamic categories Using Models
Im trying to make dynamic category using foreign key in django but not able to save drop down category this is my view.py @login_required(login_url='login') @admin_only def add_product(request): name = request.POST.get('name') description = request.POST.get('description') price = request.POST.get('price') select = request.POST.get('dropdown') b = Product.objects.all() categories = Category.objects.all() if request.method == 'POST': b = Product.objects.create(name=name, description=description, price=price, category=select) return render(request, 'product.html', {'b': b, 'category': categories }) this is models.py class Category(models.Model): categoryname = models.CharField(max_length=255, null=True) def __str__(self): return self.categoryname class Product(models.Model): name = models.CharField(max_length=255, blank=False, null=True) description = models.CharField(max_length=255, blank=False, null=True) price = models.CharField(max_length=50, blank=False, null=True) date = models.DateTimeField(auto_now_add=True, null=True) category = models.ForeignKey(Category, on_delete= models.CASCADE, null=True) def __str__(self): return self.name this is html for add product {% block content %} <div class="container"> <div class="row"> <form class="center-align" action="{% url 'addproduct' %} " method="POST"> {% csrf_token %} <div class="input-field col s12"> <input value="" id="name" name="name" type="text" class="validate"> <label class="active" for="name">ProductName</label> </div> <div class="input-field col s12"> <input value="" id="des" name="description" type="text" class="validate"> <label class="active" for="des">Description</label> </div> <div class="input-field col s12"> <input value="" id="price" name="price" type="text" class="validate" required> <label class="active" for="price">Price</label> </div> <div class="input-field col s12"> <select name="dropdown" class="browser-default"> <option value="" disabled selected>Choose your option</option> {% for item in category %} <option value="{{ item.categoryname }}">{{ item.categoryname }}</option> … -
Django Models: Set Staticfile as ImageField
I have a Django project with a model that uses an ImageField. I need to set this ImageField to an image I've stored in my staticfiles, or alternatively somewhere in my project files. In short: I have a staticfile or image file located somewhere in my Django project path. I have an ImageField I need to set this ImageField as the staticfile or locally stored file. I am fine with redundancy, such as this staticfile then being uploaded to my media_root. How can I set an ImageField to an image stored in my Django project? -
Ranking organizations based on their ratings in django
I am building an app which lists different products based on their average user ratings. I have two questions, how to calculate the average ratings on basis of ratings given by the user and second, how to display them in a ranked list based upon their ratings. I would greatly appreciate if someone could point me in the right direction. -
How do i allow only my friends to see my post
I'm a Django beginner, how do I allow only my friends, people who follow me (from_user) and people I follow (to_user) to see my post. I tried this but I'm not getting any results. def home(request): friends_posts=[] if request.user.is_authenticated: posts=Image.object.exclude(imageuploader_profile=request.user) for p in posts: if p.imageuploader_profile in request.user.friends.all(): friends_posts.append(p) context={'friends_posts':friends_post} return render(request, 'home.html', context) Models.py class Profile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL) friends=models.ManyToManyField('Profile' related_name='my_friends') class FriendRequest(models.Model): to_user=models.ForeignKey(settings.AUTH_USER_MODEL) from_user=models.ForeignKey(settings.AUTH_USER_MODEL) class Image(models.Model): imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL) upload_image=models.ImageField() -
Chunk wise deleting data from database in django
just say i fetched data in chunks from a table with 20 million entries and i need to process the whole data and need to delete whole data only once everything is processed (my condition is i cant delete inside the loop where it is getting fetched) chunk = 10000 id_gte = 1 id_lt = 20000000 delete_query = MyModel.objects.none() for i in range(id_gte, id_lt, chunk): data = MyModel.objects.filter(id__gte=i, id__lt=i+chunk) print(data) delete_query |= data now if i want to delete the data...that i fetched in the loop, so i can do delete_query.delete() So my doubts are. Does the time to delete the data that is deleted depends on that how much data i am deleting at once? Like above i am trying to delete the whole 20000000 rows at once. Will it be better to delete the data in chunks? Say in delete_query, i use a loop to get the cached chunks of queryset of size 10000 and delete them? So overall it will take maybe the same time, but it will lock the db for smaller times? Does any evaluation done to delete the data from database? if yes, then is the query re-evaluated to delete the data. I mean … -
how do i set radio button as checked based on database values in django template?
here is my html code <input type="radio" name="cast" id="open" style="margin-left:10px;text-align:left;" value="Open" {% if data.cast %}checked{% endif %} required>Open <input type="radio" name="cast" id="sebc" style="margin-left:10px;text-align:left;" value="SEBC" {% if data.cast %}checked{% endif %} required>SEBC <input type="radio" name="cast" id="sc/st" style="margin-left:10px;text-align:left;" value="SC/ST" {% if data.cast %}checked{% endif %} required>SC / ST <input type="radio" name="cast" id="other" style="margin-left:10px;text-align:left;" value="Other" {% if data.cast %}checked{% endif %} required>Other I did this but it didn't work for me. the data.cast is variable having database value. -
Django Rest-framework: Migration No changes detected
I'm new to python and django, I'm creating a simple shopping app. I have followed all the steps to create django rest-framework project, run the server and it works. What I did is created a new folder called Models (deleted the pre-defined models.py) and created inside it many model classes in addition of an __init__.py file as I red and imported all the classes inside it. When running python manage.py makemigrations it return ''No changes detected''. Here is the structure: quickstart/ . . `Models/ __init__.py model1.py model2.py . . . tutorial/ manage.py -
how to render django model permission in my own templates in tabular format
I want to render django model permission in my own template. I tried this one called django-tabular-permission package. But it only works for django admin. I didn't know either it works for custom template or not. My requirements is somethings like django tabular permission but in my own templates. Any suggestion would be appreciated. I'm new to django and i love django model permission concept. -
Django Models: Set ImageField Default
I'm working on a Django project and using S3 as storage. I have a model that has a photo ImageField, however I'd like to specify a default as something from my staticfiles. The user can change this later, but initially I would like to supply one of a few specific random images from my own static files. Something like: class StoreObject(models.Model): ... photo = models.ImageField(upload_to='media', default='what/goes/here?') ... How can I do this? I found a few relevant answers here, but none are exactly what I need. Programmatically saving image to Django ImageField -
How can I run a project in a local server using Pycharm?
when I try to run a project in a local server using Pycharm, I can't do that with these errors. So would you mind telling me how should I solve this problem? Thank you in advance. Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 10, in main from django.core.management import execute_from_command_line File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 11, in <module> from django.conf import settings File "/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 17, in <module> from django.conf import global_settings ImportError: cannot import name 'global_settings' from 'django.conf' (/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages/django/conf/__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 21, in <module> main() File "/Users/apple/GoogleDrive/project_django/project/manage.py", line 16, in main ) from exc 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? Python Console import sys; ... ...print(sys.path) ['/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/third_party/thriftpy', '/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/apple/GoogleDrive/project_django/venv/lib/python3.7/site-packages', '/Users/apple/GoogleDrive/project_django'] Development environment Mac: mojave 10.14.6 Python: 3.7.5 Django: 2.2.2 Pycharm: 2019.3.1 (community edition) -
Design patten to access internal python api server on local and production
I have django project which has restful api framework, and some commands. For now, I can accesing api like, python manage.py mycommand url = "http://localhost/api/tasks" r_get = requests.get(url) If only development on localhost. But sometimes port need to be changed on production. Even more my production environment is clustering. API server and Commandline server will be separate on docker-swarm How should I write the python code?? What is the good practice for this purpose??