Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When using django-simple-history and DRF, how can I create an extra action to access the history of an object?
I'm new to Python, Django and DRF but I've gone through all the tutorials needed to set up a basic REST server and for this example, we'll pretend that it only serves one thing: a list of customers. Additionally, I have installed django-simple-history and registered my Customer model with it. This is the code that I've written so far and everything seems to work just fine. api/urls.py from django.urls import path, include from rest_framework import routers import api.views as views router = routers.DefaultRouter(trailing_slash=False) router.register('customers', views.CustomerView) router.register('customerhistory', views.CustomerHistoryView) urlpatterns = [ path('', include(router.urls)), ] api/views.py from rest_framework import viewsets from retail.models.customers import Customer class CustomerView(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer filterset_fields = '__all__' search_fields = ['name'] class CustomerHistoryView(viewsets.ModelViewSet): queryset = Customer.history.all() serializer_class = CustomerHistorySerializer filterset_fields = '__all__' api/serializers.py from rest_framework import serializers from retail.models.customers import Customer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' class CustomerHistorySerializer(serializers.ModelSerializer): class Meta: model = Customer.history.model fields = '__all__' As it is, when I go to api/customerhistory/1, it gives me a lovely list of all the history for customer 1. Question What I'd like to do is access the same list by going to api/customer/1/history. My Attempt So Far... To do this, I'm … -
passing django views into a separate highcharts js script file
I have a template that visualizes data from a django view using Highcharts js (as shown below) and it works IF the Content Security Policy is disabled. However, I don't want the CSP disabled and after some reading I come to the conclusion that the best way is to host the highcharts script into another (external) file which then would be allowed by the CSP 'self' directive (please correct me if I wrong). <script> document.addEventListener('DOMContentLoaded', function () { const chart = Highcharts.chart('container', { chart: { backgroundColor: '#eaeaea', type: 'bar' }, title: { text: 'Rezultatet sipas lëndëve' }, xAxis: { categories: [{% for cat, value in cat_scores.items %} '{{ cat }}' {% if not forloop.last %}, {% endif %}{% endfor %}] }, yAxis: { title: { text: 'Suksesi' } }, series: [{ name: 'Saktë', data: [{% for cat, value in cat_scores.items %} {{ value.2 }} {% if not forloop.last %}, {% endif %}{% endfor %}] }, { name: 'Pasaktë', data: [{% for cat, value in cat_scores.items %} {{ value.1 }} {% if not forloop.last %}, {% endif %}{% endfor %}] }, { name: 'Perqindje', data: [{% for cat, value in cat_scores.items %} {{ value.0 }} {% if not forloop.last %}, {% … -
Ajax and django routes with search form as-you-type
Im working on a search as-you-type with ajax form on a django web app (django oscar package), the problem is that the results only show on 1 specific route, and i need that in all apps, because is in the navbar, somebody saave meee smallville song working whit this tutorial https://openfolder.sh/django-tutorial-as-you-type-search-with-ajax apps/search/apps.py from django.urls import path from django.utils.translation import gettext_lazy as _ from oscar.core.application import OscarConfig from oscar.core.loading import get_class from django.urls import re_path class SearchConfig(OscarConfig): label = 'search' name = 'oscar.apps.search' verbose_name = _('Search') namespace = 'search' def ready(self): self.search_view = get_class('search.views', 'FacetedSearchView') self.productos_view = get_class('search.views', 'productos_view') self.search_form = get_class('search.forms', 'SearchForm') def get_urls(self): from haystack.views import search_view_factory # The form class has to be passed to the __init__ method as that is how # Haystack works. It's slightly different to normal CBVs. urlpatterns = [ path('', search_view_factory( view_class=self.search_view, form_class=self.search_form, searchqueryset=self.get_sqs()), name='search'), path('productos', self.productos_view, name="productos"), ] return self.post_process_urls(urlpatterns) def get_sqs(self): """ Return the SQS required by a the Haystack search view """ from oscar.apps.search import facets return facets.base_sqs() apps/search/views.py from haystack import views from oscar.apps.search.signals import user_search from oscar.core.loading import get_class, get_model Product = get_model('catalogue', 'Product') FacetMunger = get_class('search.facets', 'FacetMunger') from django.template.loader import render_to_string from django.http import JsonResponse from django.shortcuts … -
how to display user data in django?
here am looking for the particular data of logged in user to display in their profile i don't know how to do that. this is the error i get "'User' object is not iterable" please help me . views.py def users_homepage(request): merchant=Merchant.objects.filter(request.user) models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) shop_name=models.CharField(max_length=100) phone_number=models.IntegerField(null=True) dashboard.html {%for merchan in merchant%} <h1>{{merchan.shop_name}}</h1> {%endfor%} thanks in advance -
how to check the charfield choice instance
i need to check the charfield choice instance, representing a role for permissions, however i cannot obtain that here's models.py: class User(AbstractUser): ROLE_CHOICES = ( ('ADMIN', 'admin'), ('USER', 'user'), ('MODERATOR', 'moderator'), ) role = models.CharField(choices=ROLE_CHOICES, default=ROLE_CHOICES[1], max_length=500) bio = models.CharField(max_length=500, blank=True, null=True) password = models.CharField(max_length=128, blank=True, null=True) username = models.CharField(max_length=50, blank=True, null=True, unique=True) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role'] view permission func: def get_permissions(self): print(self.request.user.role) print(self.request.user.role) print(self.request.user.role) print(self.request.user.role) print('vvvvvvvvvvvvvvvvvk') if self.request.user.role == 'user': print(self.request.user.role) if self.request.user.role == 'USER': print(self.request.user.role) if self.request.user.role == ('USER', 'user'): print(self.request.user.role) if self.request.user.role in ['USER', 'user']: print(self.request.user.role) print('aaaaaaaaaaaaaa') if self.action == 'create' or self.action == 'perform_create': permission_classes = [] elif self.action == 'list' or self.action == 'retrieve': permission_classes = [permissions.IsAuthenticated] # elif self.action == 'list': # permission_classes = [IsAboveUser] elif self.action == 'destroy' or self.action == 'update' or self.action == 'partial_update': permission_classes = [permissions.IsAuthenticated] else: permission_classes = [IsAdmin] return [permission() for permission in permission_classes] out: ('USER', 'user') ('USER', 'user') ('USER', 'user') ('USER', 'user') vvvvvvvvvvvvvvvvvk so noting passes the check -
How should I handle uploaded resumes in django
I have a form where users can upload their resumes as word or pdf. Where should I store these files during production? I also thought about directly emailing the uploaded resume to my email without storing it, and it works but I dont know the cons of using such a way in production so any help would be really appreciated. Thanks -
Variable changes its value for no reason
In this function variable called "assembly_required_quantity" should change its value in line 16 (if function definition is line 1. And it changes. For example, it changed the value from 3 to 2 (-1). I have some print statements to track its value and I see that until print([8]) (including) line it doesn't change its value and still have 2 but at print([9]) value changes to 3. Can somebody explain to me why is this happening, please? def create_production_list_func(nomenclature, sets_number, step=0): product = ProductStructureProduct.objects.filter(nomenclature=nomenclature).first() assembly_required_quantity = product.quantity * sets_number available_warehouse_quantity = None if step != 0: available_warehouse_products = filter( lambda p: p.locator.warehouse.id not in [2, 3], nomenclature.warehouse_product.all(), ) available_warehouse_quantity = 0 for product_ in available_warehouse_products: available_warehouse_quantity += product_.quantity if assembly_required_quantity <= available_warehouse_quantity: return else: assembly_required_quantity -= available_warehouse_quantity print(f'[1]{product=},{assembly_required_quantity=}', flush=True) print(f'[2]{product=},{assembly_required_quantity=}', flush=True) production_list = ProductionList.objects.create( code=nomenclature.code, name=nomenclature.name, sets_number=sets_number ) print(f'[3]{product=},{assembly_required_quantity=}', flush=True) if not product: raise NotExistentProduct if not nomenclature.type == Nomenclature.Type.ASSEMBLY: raise NotAssemblyProduct print(f'[4]{product=},{assembly_required_quantity=}', flush=True) products_from_structure = product.get_children().select_related("nomenclature") print(f'[5]{product=},{assembly_required_quantity=}', flush=True) products_to_be_created = list() print(f'[6]{product=},{assembly_required_quantity=}', flush=True) if step == 0: required_quantity = product.quantity else: required_quantity = sets_number print(f'[7]{product=},{assembly_required_quantity=}', flush=True) products_to_be_created.append( ProductionListProduct( list=production_list, nomenclature=product.nomenclature, required_quantity=required_quantity, ) ) print(f'[8]{product=},{assembly_required_quantity=}', flush=True) for _product in products_from_structure: if available_warehouse_quantity: if assembly_required_quantity <= available_warehouse_quantity: return else: assembly_required_quantity -= available_warehouse_quantity … -
How to decide whether to have one or many apps in Django project
What are the design decisions one should make when choosing to have just one large app versus several smaller apps in a Django project? I read 2 Scoops of Djangowhich strongly asserts that latter- that it should always be several small apps. However, others assert the opposite, that building production-level projects at scale are a nightmare if broken up into several apps. My project currently has 2 apps: animals and store where animals stores animal related data and store stores online shop related data. I was thinking about breaking store up into a cart app, a vendor app, and product app but have been advised that I should have it all in one app and that store should also be in the animal app, as there is a few FK rel between animal and store, so that I will just have one app. This is my first project and Ive already rebuilt it once and want to make the right design decisions now so that it is optimally functional and wont be a nightmare when moving it to production. I appreciate any advice about how to make these decisions from those who have more experience building production level Django apps. … -
What's the most convenient full softare stack to incorporate video chats among about 5-10 clients at the same time?
I'm thinking of building a website where a small group of people can video chat while playing simple games together on their computers (not mobile). (If such website already exists, please let me know, because I failed to find one after lots of search). I have never programmed video chats into a website before, is there a specific software web stack that is very convenient to incorporate video chats with? Many years ago I used Django on the backend and Angular.js was very popular at that time. I just found out Angular.js is no longer going to be maintained. So if there are specific software I should or should not use, please let me know, since web development changes rapidly and I might be missing something obvious, and Google searches would yield a lot of outdated resources. I plan to host it for free on github pages. -
How to add relation in a model instantiation before save/create the instance in database?
I had a problem adding bulk with m2m, so I created a script a little different from the examples I found. Post here This seems to work, until the part of adding the instance arrives. This does not work in the examples: - Add using ModelName(related_m2m_field=related_instance) not works, django says to use something like: ModelName(id=1).related_m2m_field=related_instance. - So, try using this way, but not works, I get the error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed because the instance hasn't been created yet, I THINK, so I can't add a relation to an instance that hasn't been created, the problem is that I can't just create it, since I'm using bulk_create, everything should be ready before executing the bulk. You can see the complete code in the linked post. But here is the code that raise the error: # other imports.... from olympic.models import Game, Athlete # ... some code athlete_objs = [] game_objs = [] athlete_instance = Athlete( id=pk, name=name, sex=sex, age=age, height=height, weight=weight, team=team, noc=noc, ) athlete_objs.append(athlete_instance) game_objs.append( Game( id=register_row_number, name=game_name, year=year, season=season, city=city, sport=sport, event=event, medal=medal, ).athlete.add(athlete_instance) # I can't do this before save/creation!!!? ) # bulk code out of the instance scope Athlete.objects.bulk_create(athlete_objs, ignore_conflicts=True) Game.objects.bulk_create(game_objs, ignore_conflicts=True) -
TypeError: Field 'id' expected a number but got OrderedDict
I want to post request django rest but this error.I have two Serializer.I want to post a request for full data not via id Exception Value: Field 'id' expected a number but got OrderedDict([('title', 'id:2 Смартфон Samsung Galaxy Note 20 Ultra 256GB Black'), ('price', 2019)]). class ShopSerializer(serializers.ModelSerializer): img1 = serializers.SerializerMethodField('get_image_url') img2 = serializers.SerializerMethodField('get_image_url') img3 = serializers.SerializerMethodField('get_image_url') img4 = serializers.SerializerMethodField('get_image_url') img5 = serializers.SerializerMethodField('get_image_url') img6 = serializers.SerializerMethodField('get_image_url') class Meta: model = smartphone fields = ("id", "img1", "img2", "img3", "img4", "img5", "img6","title","price","slug") def get_image_url(self, obj): return obj.image.url class OrderCreateSerializer(serializers.ModelSerializer): smartphone=ShopSerializer(many=True) class Meta: model = order fields = '__all__' def create(self, validated_data): smartphone = validated_data.pop('smartphone') question = order.objects.create(**validated_data) question.smartphone.set(smartphone) return question how to solve this problem how to solve this problem how to solve this problem how to solve this problem -
Django model object as parameter for celery task raises EncodeError - 'object of type someModelName is not JSON serializable'
Im working with a django project(im pretty new to django) and running into an issue passing a model object between my view and a celery task. I am taking input from a form which contains several ModelChoiceField fields and using the selected object in a celery task. When I queue the task(from the post method in the view) using someTask.delay(x, y, z) where x, y and z are various objects from the form ModelChoiceFields I get the error object of type <someModelName> is not JSON serializable. That said, if I create a simple test function and pass any of the same objects from the form into the function I get the expected behavior and the name of the object selected in the form is logged. def test(object): logger.debug(object.name) I have done some poking based on the above error and found django serializers which allows for a workaround by serializing the object using serializers.serialize('json', [template]), in the view before passing it to the celery task. I can then access the object in the celery task by using template = json.loads(template)[0].get('fields') to access its required bits as a dictionary -- while this works, it does seem a bit inelegant and I wanted … -
Media files in Django
I think I'm doing everything correctly but the images won't show on the website although they get added successfully in the media folder... media/product_images inside media is the placeholder image + product_images folder Model Field image = models.ImageField(upload_to='product_images/', default='placeholder.png') Settings STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' Urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
chained drop down using django html jquery
in below code in need to chained dropdown using jquery. if i select county i need to get list of the states in state dropdown. county sate is working if i select state then related city need to be listed i dont know how to do ? please help using django i am passing country sate city info to the html page. in select1 value field county_id has been passed from country table in select2 value field county_id(fk) has been passed from state table. here i need to get state_id using that i need ger city list I dont know how to do ? in select3 value field, state_id(fk) has been passed from city table. this should refer select2 state_id I don't know how to do this one? <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { var $select1=$('#select1'), $select2=$('#select2'), $options=$select2.find('option'); $select1.on('change',function() { $select2.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); } ); </script> <title>Page Title</title> </head> <body> <tr> <td><label for="appt">Work County1:</label></td> <td><select id="select1"> <option selected disabled="true" value="">------</option> <option value="1">INDIA </option> <option value="2">USA </option> </select><br></td> <td><label for="appt">Work State1:</label></td> <td><select id="select2"> <option selected disabled="true" value="">------</option> <option value=1>CHN</option> <option value=1>tn</option> <option value=2>TX</option> </select><br></td> <td><label for="appt">Work city 1:</label></td> <td><select id="select3"> <option selected disabled="true" value="">------</option> <option value=1>CHN</option> <option value=1>CHN1</option> <option … -
How to not escape characters in Django Rest Framework
I have a blog model. I have text field where I want to write in HTML, for example including an a tag. The permission class used on unsafe methods is isAdminUser. I don't necessarily have to escape the characters. Is there way where I could not escape the characters. -
How to implement a conditional formset with multiple updates in one and the same sessionwizard step (Django 2.2)
I'm using a formwizard, SessionWizard, and I want to be able do to multiple choices in one step before proceeding to the next wizard step. In the below image there's a MultipleChoiceField 'choices' where the content should change, or update based on the selected features + feature 1-3 with Boolean buttons. The 'submit features' button is meant for updating the MultipleChoiceField 'choices' based on the choices of features and the Next button is meant for proceeding to the next wizard step. I've read some documentation and followed some tutorials on formsets but it doesn't work in the form wizard. In the first wizard step in get_form_kwargs(), step 0, in the view a dynamic list is filtered by the chosen features 1-3 and used for the MultipleChoiceField. Both the form Form1 and the step 0 in get_form_kwargs() should be updated, or reiterated as long as there are more filtered options in the list dynamic_ls in the MultipleChoiceField prior to proceeding to the next wizard step. How can I do this ? I found a django-multipleformwizard on Pypi that seems to be an extension for doing this type of task but I'm not sure how to use it or if it can … -
Display all of a single user's content on a profile page in django
I want to create a public-facing user profile page that displays these three things: 1-the user's Profile (model-singular-) data (image, name, email, etc..) 2-The Blog (model -list of posts-) posts the user has published. 3-The Art (model -list of art pieces-) pieces the user has published. All three of these models have fields that tie them to their User. So far I have been able to display all of these models on one page, but I cannot figure out how to sort them down to only display the content of the user who's profile page is being visited. I am trying to display all of this data on a ListView view, not sure if that is the correct move. I have been searching around for hours trying to find how to adjust the get_queryset and get_context_data but I can't figure out how to grab the <pk> from the url (i.e. artist/44). I also tried putting <username> in the url but I wasn't able to grab that either. The two views below are the views I have been working on. One uses (username) and the other uses (id) in the url: views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name … -
Extra alias thumbnail generated
I am using easy-thumbnails the image-cropping app and aliases in this model (simplified): from image_cropping import ImageRatioField from easy_thumbnails.fields import ThumbnailerImageField class Image(SlugMixin, models.Model): slug_from_field = 'title' slug_length = 110 image = ThumbnailerImageField('path', upload_to=get_file_name, resize_source=dict( size=(1600, 0), quality=95), width_field='width', height_field='height', blank=True, null=True) crop_thumb = ImageRatioField( 'image', '120x90', help_text='Drag the handles and crop area to crop the image thumbnail.', verbose_name="crop thumbnail") .... The alias definition in settings.py: THUMBNAIL_ALIASES = { '': { 'small': { 'size': (120, 90), 'detail': True, 'crop': True, 'upscale': True, 'ALIAS': 'small', 'ratio_field': 'crop_thumb', }, 'medium': { 'size': (240, 180), 'detail': True, 'crop': True, 'upscale': True, 'ALIAS': 'medium', 'ratio_field': 'crop_thumb', }, 'large': { 'size': (0, 400), 'quality': 90, 'detail': True, 'upscale': True, 'ALIAS': 'large', 'ratio_field': 'crop_image', }, }, } THUMBNAIL_NAMER = 'easy_thumbnails.namers.alias' I am expecting to get 3 thumbnails per image uploaded, but I am getting 4. The 3 expected are named my_image.jpg.small.jpg + medium and large and the additional one is my_image.jpg..jpg and is 300px wide. It is like it generates an extra thumbnail for an empty alias, but I cannot find anything in my code that would do this. Any idea? -
Postgresql unable to alter role to superuser
I am failing at postgresql 101... I simply want to change my current user catmaid to have superuser privileges. (catmaid) [catmaid@sonic ~]$ psql postgres psql (10.10) Type "help" for help. postgres=> \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------------------+----------- catmaid | | {} postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {} postgres=> alter role catmaid superuser; ERROR: must be superuser to alter superusers I want to do this because I'm otherwise unable to do django migrations (catmaid) [catmaid@sonic django]$ ./projects/manage.py migrate INFO 2021-02-11 18:12:40,155 CATMAID version 2018.11.09-1660-gce1dee4 WARNING 2021-02-11 18:12:40,806 NeuroML module could not be loaded. WARNING 2021-02-11 18:12:41,068 CATMAID was unable to load the Rpy2 library, which is an optional dependency. Nblast support is therefore disabled. WARNING 2021-02-11 18:12:41,068 CATMAID was unable to load the Pandas lirary, which is an optional dependency. Nblast support is therefore disabled. INFO 2021-02-11 18:12:41,125 Spatial update events disabled INFO 2021-02-11 18:12:41,271 History tracking enabled System check identified some issues: WARNINGS: ?: Couldn't check spatial update notification setup, missing database functions HINT: Migrate CATMAID ?: The output folder is not writable HINT: Make sure the user running CATMAID can write to the output directory or change … -
Download a dynamic html page as pdf on button click
I want to download pdf where the source is a url or a div. I have a database of quizzes based on different categories. These quizzes have MCQ and images. I am able to render the quiz in an HTML however I want to give users a chance to download the quiz on each topic as pdf using "click here to download" On clicking a pdf with the questions and images will be downloaded. I tried using pdfMake using the following code $("#download_quiz").click(function(){ // create the window before the callback // pass the "win" argument var docDefinition={ content:[ "hello world" ] } pdfMake.createPdf(docDefinition).download(); }); however, my content is dynamic. How do I achieve it ? Is there another way to do this. I am using Django as my webdev. -
How do I loop a Django Queryset in Javascript
How can I loop a Django model queryset in javascript. I have a music player that uses javascript and the 'trackUrl' variable inside the javascript lists the track paths, I need to be able to loop through each users uploaded tracks and load them into the player for each user. I basically need to get the track out from the Music model, for each user. Hopefully this makes sense , here's some of the code i have now. models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio') title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', blank=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title music.js <script> $(function() { var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, albumName = $('#album-name'), trackName = $('#track-name'), albumArt = $('#album-art'), sArea = $('#s-area'), seekBar = $('#seek-bar'), trackTime = $('#track-time'), insTime = $('#ins-time'), sHover = $('#s-hover'), playPauseButton = $("#play-pause-button"), i = playPauseButton.find('i'), tProgress = $('#current-time'), tTime = $('#track-length'), seekT, seekLoc, seekBarPos, cM, ctMinutes, ctSeconds, curMinutes, curSeconds, durMinutes, durSeconds, playProgress, bTime, nTime = 0, buffInterval = null, tFlag = false, albums = ['Dawn','Me & You','Electro Boy','Home','Proxy (Original Mix)'], trackNames = ['Skylike - Dawn','Alex Skrindo - Me & You','Kaaze - Electro Boy','Jordan Schor - Home','Martin Garrix - Proxy'], albumArtworks = ['_1','_2','_3','_4','_5'], trackUrl = … -
Create a Django fixture file that leaves some fields unchanged when loaded into DB
Is it possible to create a fixture that is written to the DB using loaddata, and overwrites some fields of an existing record, but not all of them? For example, suppose I have a table in my DB called app_foo: id bar baz 1 "a" "b" 2 "c" "d" The corresponding YAML fixture file for this would look like: - model: app.foo pk: 1 fields: bar: "a" baz: "b" - model: app.foo pk: 2 fields: bar: "c" baz: "d" How would I modify this fixture such that: Records 1 and 2 have an empty baz field when loading the fixture into a fresh empty database. When the fixture is loaded into a database already containing records 1 and 2 that have values for baz, they aren't overwritten with NULL. I thought that I could do something like this: - model: app.foo pk: 1 fields: bar: "a" - model: app.foo pk: 2 fields: bar: "c" or this: - model: app.foo pk: 1 fields: bar: "a" baz: - model: app.foo pk: 2 fields: bar: "c" baz: But both attempts overwrote the baz field for DB records 1 and 2 with NULL. This isn't specified in the documentation for fixtures, but is an … -
Django form validation clean methods not working
This is my form class class Feedback(forms.Form): name = forms.CharField(validators=[name_validate]) rollno = forms.IntegerField() email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) This is clean method def clean_name(self): data = self.cleaned_data['name'] print(len(data)) if len(data)<4: raise forms.ValidationError('Exception') return data The control is entering to if condition but not raising error -
Why does django libraries documentation dive straight into how to implement rather than starting with what it is about?
I was checking out the celery documentation: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html which of course I found by googling django celery. I read in an article that I can use the asynchronous tools that it provides which serves my purpose. My question is what is the best way to read the celery documentation since it immediately starts with how to use it. Wouldn't it be rather nice from the readers point of view if the documentation started with an overview of what it is about and the major functions it provides. I would like to hear your opinion about it. Thank you in advance! -
Django does not import local site packages on apache
I've pulled my django project onto an apache server and installed all dependecies with requirements.txt. All of the packages have downloaded to a local folder on the server and django appears to be pointing to it (as seen in the picture below) but none of them can actually be imported when running with apache (works fine with the django server). I can definitely see all packages in the /home/bitnami/.local/lib/python3.8/site-packages folder so I'm not sure what could possibly be wrong. I've set up the deployment following djangos but I assume there's some sort of import I'm missing. Any ideas? server .conf file WSGIScriptAlias / /opt/bitnami/projects/my_website/core/wsgi.py WSGIPythonPath /opt/bitnami/projects/my_website <Directory /opt/bitnami/projects/my_website/core> <Files wsgi.py> Require all granted </Files> </Directory> tweepy failed import pic - text below Exception Value: No module named 'tweepy' Exception Location: /opt/bitnami/projects/my_website/twitterapp/controllers/twitter_controller_rename.py, line 2, in <module> Python Executable: /opt/bitnami/python/bin/python3 Python Version: 3.8.5 Python Path: ['/opt/bitnami/projects/my_website', '/opt/bitnami/projects/my_website', '/opt/bitnami/python/lib/python38.zip', '/opt/bitnami/python/lib/python3.8', '/opt/bitnami/python/lib/python3.8/lib-dynload', '/opt/bitnami/python/lib/python3.8/site-packages', '/opt/bitnami/python/lib/python3.8/site-packages/setuptools-46.4.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/pip-20.2.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/virtualenv-20.0.30-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/six-1.15.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/filelock-3.0.12-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/distlib-0.3.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/appdirs-1.4.4-py3.8.egg', (THIS FOLDER) '/home/bitnami/.local/lib/python3.8/site-packages']