Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a char field behave like URLField in django
I am using Django and I want a field for URLs I know there is a URLField in Django but I want that field to be a charfield and I don't want users to submit anything other than URL in that charfield take a look at my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=500, blank=True, null=True) social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) Please answer how can I make a char field behave like a URL field -
Add more than 1 folder (network path) to static files with Django on IIS
I have a django website deployed on an IIS Server. in it, I have 2 different network paths I need to access via static STATICFILES_DIRS = [ "//server1/Shared1/folder/", "//Server2/folder2/", ] Now, currently my IIS has a static virtual directory that is set to "server1" this allows me to work with all the files I have in that shared network drive and opertate properly. The issue comes when I try to work with any files in the "server2" I don't know how to add it. I understand that exists something called "static root" but for that I need to do a "collect static" in this case, I can't do a collect static since both servers have over 60gb of data that I need to access. Is there a way I'm not seeing for adding this second server to be able to be used via IIS? -
How to apply multiple filters in a Django query without knowing if some filters are null or not
Let's say we have the following filters: filter1 = request.GET.get("blabla") filter2 = request.GET.get("blabla") filter3 = request.GET.get("blabla") filter4 = request.GET.get("blabla") filter5 = request.GET.get("blabla") filter6 = request.GET.get("blabla") Let's say we have the following query: user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3, element4=filter4, element5=filter5, element6=filter6).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") Some of the filters might be of type None (depends on the request) I would like to create a dynamic query that based on whether the filter exists or not, executes the query only with the non-null filters. Let's say for example filters 1, 2, and 3 have values, but filters 4, 5, and 6 are empty/null/None. Expected query: user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") What I've tried: if filter1 is None or filter1.strip() == "": filter1 = "" elif is_valid_queryparam(filter1): user_projects = Project.objects.filter(element1=filter1).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") And it works, but only for one filter, if I want that for 6 or N filters, it's extremely inefficient to execute multiple queries. Is it possible to achieve the desired result with a simple query? -
objects instances returning none using django bulk_create()
I am trying to bulk insert data into the database but upon appending these instances i find they are none model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' my view for skill_nme, skill_lvl in zip(skill_name, skill_level): skill_set = Skillset.objects.get(skill_name=skill_nme) seeker_skll.append(Seekerskillset( skill_set=skill_set, skill_level=skill_lvl, seeker=user)) print(seeker_skll) seeker_bulk = Seekerskillset.objects.bulk_create(seeker_skll) print('after insertion',seeker_bulk) return redirect('/users/dashboard') trace <class 'seekerbuilder.models.SeekerProfile'> [<Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>] after insertion [<Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>] [19/Jul/2021 14:27:12] "POST /users/app_det/ HTTP/1.1" 302 0 [19/Jul/2021 14:27:12] "GET /users/dashboard HTTP/1.1" 301 0 -
How to create and update user and User and custom model together in Django
Main Thing I want to register new user with User model and Custom user model data together. Problem Hello I'm a beginner it might be not a big deal at all and I may be overlooking it but I don't have any idea how can I do it. I'm using react in the fronted. can you please help me. Here is my code. Custom User Model class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="users", blank=True) birthday = models.DateField(blank=True) gender = models.CharField(max_length=100, choices=Gender_Choices, blank=True) User Serializer class UserSerializer(serializers.ModelSerializer): user_profile = ProfileSerializer(source='profile') class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'user_profile') Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) Frontend // Register User export const register = ({ username, password, email }) => dispatch => { // Headers const config = { headers: { 'Content-Type': 'application/json' } } // Request Body const body = JSON.stringify({username, email, password}) … -
ImportError: no module named typing on Mac OS X
Traceback (most recent call last): File "/usr/local/bin/pip", line 11, in load_entry_point('pip==21.1.3', 'console_scripts', 'pip')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2843, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2434, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2440, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "/Library/Python/2.7/site-packages/pip-21.1.3-py2.7.egg/pip/init.py", line 1, in from typing import List, Optional ImportError: No module named typing -
GeoDjango: How to create a geometry object from a bounding box?
I am intercepting a query parameter of bounding box ex. ?bbox=160.6,-55.95,-170,-25.89 in my GeoDjango application to filter my queryset of entries that intersects with the bbox. I want to know if how can I create an geometry object from the bbox or a list of the bbox object [160.6,-55.95,-170,-25.89]. bbox = GEOSGeometry('BBOX [160.6,-55.95,-170,-25.89]') -
Django CBV form submission returned JSON is displayed as a new page
I am using Django 3.2 I am creating a simple newsletter subscription form. The form submission returns JSON to the frontend, which should then be used to update parts of the page - however, when I post the form, the JSON string is displayed as text on a new page. Here is my class based view: class BlogsubscriberCreateView(CreateView): model = BlogPostSubscriber form_class = BlogSubscriptionForm http_method_names = ['post'] def post(self, request, *args, **kwargs): form = self.form_class(request.POST) content_type = "application/json" if not form.is_valid(): return JsonResponse({'ok': 0, 'msg': form.errors.get('email')[0]}, content_type=content_type, status=200) else: email = form.cleaned_data.get("email") subscriber = BlogPostSubscriber(email= email) subscriber.save() # send email to confirm opt-in email_message='Please confirm your subscription' message = f"A confirmation email has been sent to {email}. Please confirm within 7 days" return JsonResponse({'ok': 1, 'msg': message}, content_type=content_type, status=200) Here is a snippet of the HTML containing the form: <div class="col-lg-8 content"> <form id="blog-subscription"> {% csrf_token %} <br /> <h3>Some title</h3> <br /> <p>Lorem ipsum ...</p> <br /> <h4 id='submit-response-h4'>SUBSCRIBE TO OUR BLOG</h4> <div id="submit-response" class="input-group"> <span id="email-error"></span> <input type="email" id="blog-subscription-email" name="email" class="form-control" placeholder="Enter your email" required="true"> <span class="input-group-btn"> <button id="subscribe-btn" class="btn" type="submit">Subscribe Now</button> </span> </div> </form> Here is the Javascript that is responsible for updating the page: $().ready(function() { … -
How do i set and use the id field in django model and template
I need to be able to access a self incrementing integer field for my model and use it in my template. Is there a way to do that? My code accepts complaints from users so for each complaint I need the id to increment from 0,1,2,3,4, and so on and then I need to access these in the template to be able to use it accordingly models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter … -
Why are django-q scheduled tasks delayed randomly?
I'm finding that django-q is not executing tasks I schedule on time. There can be delays of several seconds to almost a minute. I schedule a task like so: from django.utils import timezone from django_q.models import Schedule def schedule_auction_deadlines(self): now = timezone.now() if self.deadline: name = "end_phase_%d" % self.id Schedule.objects.filter(name=name).delete() if now < self.deadline: Schedule.objects.create(name=name, func="myapp.views.end_phase", args=str(self.id), next_run=self.deadline, schedule_type=Schedule.ONCE) And here is my configuration in the settings.py file: Q_CLUSTER = { 'name': 'myproj', 'label': 'Django Q', 'timeout': 30, 'catch_up': True, 'guard_cycle': 1, 'redis': os.environ.get('REDIS_URL', 'redis://localhost:6379'), } From the docs it seemed like guard_cycle might be relevant, but I've got it set at the minimum setting. What could be causing these delays? -
Why is Django Easy Thubnails maintaining image extension?
I think I'm doing something foolish to cause this issue but django-easy-thumbnails seems to be maintaining the loaded image's file format, so I'm not getting best advantage of compression. I have the following within settings.py THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_QUALITY = 50 THUMBNAIL_DEFAULT_OPTIONS = { 'crop': True, 'upscale': True, 'progressive': True, } #THUMBNAIL_EXTENSION = 'jpg' #THUMBNAIL_PRESERVE_EXTENSIONS = None THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters' ) THUMBNAIL_ALIASES = { '': { 'full_width_image': {'size': (2220, 0), 'upscale': False}, 'hero': {'size': (2220, 0), 'upscale': False}, 'content_width_image': {'size': (1520, 0), 'upscale': False}, 'awards_image': {'size': (50, 50)}, 'carousel_slide': {'size': (1600, 900)}, 'modal_carousel_slide': {'size': (1500, 700)}, 'tablet_modal_carousel_slide': {'size': (700, 325)}, 'mobile_modal_carousel_slide': {'size': (310, 142)}, 'testimonial_avatar': {'size': (160, 160)}, 'core_service_icon': {'size': (64, 64)}, 'cta_carousel': {'size': (688, 0)}, 'image_carousel': {'size': (524, 524)}, 'search_result': {'size': (340, 340)}, 'news_article': {'size': (700, 470)}, 'carousel_main': {'size': (1090, 720)}, 'carousel_thumbnail': {'size': (240, 160)}, 'dropzone_thumbnail': {'size': (240, 240)}, 'manager_thumbnail': {'size': (510, 510)}, 'staff_thumbnail': {'size': (510, 510)}, 'brand_icon' : {'size' : (120, 120)}, 'mobile_brand_icon' : {'size' : (240, 240)}, 'native_logo' : {'size' : (180, 90)}, 'monaco_pdf': {'size' : (340, 200), 'extension':'png'}, 'monaco_brand' :{'size': (50, 50), 'extension':'png'}, 'monaco_half_size': {'size' : (163, 95), 'extension':'png'}, 'your_services_card' : {'size': (78, 78)}, 'my_shortlist_card' : {'size': (500, 300)}, 'extra_service_icon' : {'size': … -
Offline Cache Web Application with Django
I have faced some problems with offline web application which used VueJS(frontend) and Django(Backend) with postgres database. Currently postgres database are installed on cloud while frontend and backend are on local computer, in order to avoid retrieve or update data every time from cloud, I have used cache in Django to store data temporary. But when internet connection is disconnected, cache suddenly stop working and show error on database disconnected. Are there any solution to add some offline service worker to avoid database connection error and allow cache to work both offline and online ? Thank you -
Creating separate Date/Time Field in Models.py when clicked on calender and if try to select a date it does select the value the field remain empty
The issue is that when open django admin panel It shows the calender and time options but when I select any options it does not fill up the field and also for the time field it shows invalid time. Here is my models.py class Appointment(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) phone_number=models.CharField(max_length=12,null=False) date=models.DateField(null=True,blank=True) time=models.TimeField(blank=True) here is my js and css linking in base.html <head> <link rel="stylesheet" href="{% static 'static\css\jquery-ui.css' %}"> <link rel="stylesheet" href="{% static 'css\jquery-ui-timepicker-addon.css' %}"> <link href="{% static 'css\jquery-ui.min.css' %}" rel="stylesheet"> <link href="{% static 'css\jquery-ui.structure.min.css' %}" rel="stylesheet"> <link href="{% static 'css\jquery-ui.theme.min.css' %}" rel="stylesheet"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css"> </head> <script src="{% static 'js\jquery-ui.js' %}" ></script> <script src="{% static 'static\js\jquery-ui-timepicker-addon.js' %}"></script> <script src="{% static 'js\jquery-3.6.0.min.js' %}"></script> <script src="{% static 'js\jquery-ui.js' %}"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <script> <script> $(document).ready(function(){ $("#id_date").datepicker({changeYear: true,changeMonth: true, dateFormat: 'yy-mm-dd'}); }) $(document).ready(function(){ $('#id_time').timepicker({scrollbar: true,maxTime: '4:00pm'}); }); </script> </script> Here is admin.py from django.contrib import admin from .models import Appointment admin.site.register(Appointment) forms.py <form class="appoinment-form" method="POST" action="#" > {{ form.as_p }} <a class="btn btn-main btn-round-full" href="appoinment.html" >Make Appoinment <i class="icofont-simple-right ml-2 "></i></a> </form> Here is the screenshot of calender but date not getting selected Need to find out the reason and solve it Help will be appreciated. -
How do I authenticate with tokens from the remote database?
I am building a REST API that uses 2 postgresql databases: db1 (default) and db2 (remote, read_only). I want to get users from db2 and create a profile for them to store in db1. The custom User and MyToken models are in the db2. Is it possible to do such that Users authenticate using their token from the db2? When I use ObtainAuthToken in my view, it creates new model named Token in db1. -
I'm merging multiple forms, and geting ValueError/ at Registration form in django while interlinking to another form database
I'm getting a ValueError at /Register. The view Capp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. I'm merging various html forms. Even checked for the variables, its the same everywhere. enter image description here [ITS ss of models.py for the same code][1] -
How to avoid sending error from a specific Python library to sentry?
I'm using django and logging errors to sentry via sentry_sdk. However, I do not want to log errors from specific library. For example, libraries such as elastic apm generate various errors(Like TransportException, ..., etc) depending on the state. import sentry_sdk from elasticapm.transport.exceptions import TransportException sentry_dsk.init( dsn='SENTRY_DSN', ignore_errors=[ TransportException() ] ) The example above is how to write down a specific error and ignore it. Is there a way to ignore errors that occur in a specific library other than this way? -
ajax selecting specific part of a HTML
I am trying to AJAX load a chained dropdown list using django, where the dropdown choices are based on the choice of another field... I have more than one element which needs to be chained, So I tried to chain multiple Ajax requests one after the other which I wasnt able to ... Now I am trying to to bring in the ajax response of different choice fields in single html and render the ajax response based on the id of the div's... Can you please let me know if I can explicitly specify the part of the data(div) that can be replaced... Thanks! AJAX PART store_dropdown_list_options.html: <div id="div1"> <option value="">---------</option> {% for store in stores %} <option value="{{ store.id }}">{{ store.StoreNM }}</option> {% endfor %} </div> views: def load_store(request): ReadingAreaNo_id = request.GET.get('ReadingArea') print('value is ', ReadingAreaNo_id) stores = StoreMaster.objects.filter(ReadingAreaNo_id=ReadingAreaNo_id).order_by('StoreNO') print('stores are ', stores) return render(request, 'rateshare/store_dropdown_list_options.html', {'stores': stores}) URLS: path('ajax/load-stores/', views.load_store, name='ajax_load_stores'), script: <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_ReadingAreaNo").change(function () { var url = $("#personForm").attr("data-cities-url"); var ReadingAreaNo = $(this).val(); $.ajax({ url: url, data: { 'ReadingArea': ReadingAreaNo }, success: function (data) { $("#id_StoreNO").html(data); } }); }); </script> There will be different div's rendered in the ajax html and so I am looking … -
How to use 2 engines with the same database in Django?
Note: This question is NOT about using 2 databases. So I have been using timescaledb with my django project and my DATABASE portion in my settings.py file is something like this: DATABASES = { 'default': { 'ENGINE': 'timescale.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER' : os.getenv('DB_USER'), 'PASSWORD' : os.getenv('DB_PASSWORD'), 'HOST' : os.getenv('DB_HOST'), 'PORT' : os.getenv('DB_PORT'), }, } Now, I want to use postigs with the same database. Under the hood, i can just install the postgis extension to postgres but how should i configure the settings in django? All the documentation of using postgis suggests to use different settings for the 'ENGINE' property, but i have to use timescale too. This article shows it is possible to use both with single DB. But I am just not sure how to do it with django? -
Return user object along side token using rest_framework_simplejwt
I am using django_rest_passwordreset for my authentication on Django rest framework. I followed the tutorial on their official documentation and login, registration works well. Login returns the access and refresh token. What I want to do is also return the user object alongside the access and refresh token. I have a custom model # auth/models.py # Inherited from user class MUser(AbstractUser, models.Model): email = models.EmailField(unique=True) role = models.CharField(max_length=40, default="student") USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username', 'role'] Serializers # auth/serializers.py class TokenObtainPairSerializer(TokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data My view # auth/views.py class TokenObtainPairView(TokenViewBase): """ Takes a set of user credentials and returns access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer_class = serializers.TokenObtainPairSerializer So in summary, upon successful login, I receive { access: xxx, refresh: xxx, # I want to add this user: {username, first_name, last_name, email, ...} } -
Connect html form with models in dango to submit data
I wanted to know how to connect the below html form with a specific model. Also how can I connect multiple forms to multiple forms to multiple models ( or rather tables in the database) to submit data. html <form action='register' method="POST" > {% csrf_token %} <table> <tr> <td><label for="name">NAME :</label></td> <td><input type="text" id="first_name" name="name" maxlength="50" ></td> </tr> <tr> <td><label for="email">EMAIL :</label></td> <td><input type="email" id="email" name="email" placeholder="This will be your User ID"></td> </tr> <tr> <td><label for="phone">MOBILE NUMBER :</label></td> <td><input type="tel" id="phone" name="phone" maxlength="10" pattern="[0-9]{10}" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" ></td> </tr> <tr> <td><label for="join_as">JOIN AS :</label></td> <td><select id="join_as" name="join_as" > <option value="select" disabled selected hidden>Select...</option> <option value="individual" >INDIVIDUAL</option> <option value="firm" >FIRM</option> <option value="company" >COMPANY</option> <option value="consultancy">CONSULTANCY</option> <option value="students" >STUDENTS</option> <option value="others" >OTHERS</option> </td> </select> </tr> <tr> <td><label for="passpwrd">PASSWORD:</label></td> <td><input type="password" id="password" name="password" maxlength="10" placeholder="max 10 characters" ></td> </tr> <tr> <td><label for="con_passpwrd">CONFIRM PASSWORD :</label></td> <td><input type="password" id="con_password" name="con_password" maxlength="10" ></td> </tr> </table> </form> model.py class Regd3(models.Model): name= models.CharField(max_length=100) username= models.EmailField(max_length=254, primary_key= True) #email mobile_number= models.CharField(max_length=10) category = models.CharField(max_length=10) password= models.CharField(max_length=10) agreed= models.BooleanField(default=False) what shall i write in views.py or how to submit data exactly? -
Django static file not loaded with gunicorn
When I run my Django project with python mange.py runserver it runs fine without broke and CSS or javascript file but when I try with gunicorn it's not able to load any static file CSS or js file shows 404. Here are my Django settings.py PROJECT_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__))) LOCALE_PATHS = (os.path.join(PROJECT_DIR, "../locale"),) RESOURCES_DIR = os.path.join(PROJECT_DIR, "../resources") FIXTURE_DIRS = (os.path.join(PROJECT_DIR, "../fixtures"),) TESTFILES_DIR = os.path.join(PROJECT_DIR, "../testfiles") STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, "../static"), os.path.join(PROJECT_DIR, "../media"), os.path.join(PROJECT_DIR, "../node_modules"), os.path.join(PROJECT_DIR, "../node_modules/react/umd"), os.path.join(PROJECT_DIR, "../node_modules/react-dom/umd"), ) STATIC_ROOT = os.path.join(PROJECT_DIR, "../sitestatic") STATIC_URL = "/sitestatic/" COMPRESS_ROOT = os.path.join(PROJECT_DIR, "../sitestatic") MEDIA_ROOT = os.path.join(PROJECT_DIR, "../media") MEDIA_URL = "/media/" I configure my Nginx in a lot of different ways but it's doesn't work with gunicorn. 1. server { listen 80 default_server; server_name 52.3.225.81; location = /favicon.ico { access_log off; log_not_found off; } location /static { autoindex on; alias /home/ubuntu/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject.sock; } } location /static/ { root /home/ubuntu/myproject; } location /myproject/static/ { root /home/ubuntu; } location /myproject/static/ { alias /home/ubuntu; } I am not understanding why this is happening. My static folder in myproject/static. any idea why I getting 404? -
django fileuploader chunk method not working as expected
the Django chunks method on the fileuploader handler accepts chunk_size with this desc in the source code "" Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``). """ so i have this view function, def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] print(sys.getsizeof(file)) chunk_size = 0 dd = list(file.chunks(chunk_size=20000)) print(len(dd[0])) // this gives me some figures like the size of the image print('...') for chunk in list(file.chunks(chunk_size=10000)): chunk_size += sys.getsizeof(chunk) print(chunk_size) return redirect('index') return render(request, 'upload.html') generally, my expectation is that if the image is 50000bytes and i choose a chunk_size of 10000 the length of the generator should be 5. i dont know if i am missing something. -
How do i provide a default image for a django project
In my project, I want users to be able to create a post without an image and if they create it, the default dummy image would be there rather than it Beign blank In my models.py related_image = models.ImageField(default='defaultimg.jpg', upload_to='images/’, null=True) Now if I create a post in the admin section, it would put the default image but if I create it from the users point of view(the form), it does not upload or use the default image forms.py class BlogPostForm(forms.ModelForm): related_image = forms.ImageField(label='', required=False) views.py def uploadPost(request): form = BlogPostForm() if request.method == 'POST': form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') The problem is that when a user create a post, the related image would be empty but from the admin section, the default image would show. I want the default image when a user don't provide an image to be 'defaultimg.jpg' Thanks for your contribution -
Could not find a version that satisfies requirements aptural==0.5.2 in heroku
I trying to deploy heroku my django app and got a error like this I don’t know why the says that could not find version in apturl version in requirements.txt but there is apturl in there.And also I’m using a ubuntu os to deploy to deploy this app.I have found a previous question like this I tried that also and it didn’t work either. ERROR: Could not find a version that satisfies the requirement (from -r /tmp/build_750f707f/requirements.txt (line 1)) (from versions: none) And also in my requirements.txt file has apturl==0.5.2 in first line.Please help in advance thanks. -
How do I run previously set up environment in django?
I am very new to django I set up an environment and now later when I try open the environment it is not running. Please help. Sorry if this a noob question I am very new with django