Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to apply 2d list in jinja(format) using django
I have this 2d list in python "[['count1', 'product1', 'subtotal1',' 'unit1', 'total1'], ['count2', 'product2', 'subtotal2',' 'unit2', 'total2'], ['count3', 'product3', 'subtotal3',' 'unit3', 'total3']]" i expect this in jinja format please explain in brief thank you obj = '[['count1', 'product1', 'subtotal1',' 'unit1', 'total1'], ['count2', 'product2', 'subtotal2',' 'unit2', 'total2'], ['count3', 'product3', 'subtotal3',' 'unit3', 'total3']]' return obj {% for x in list % }} {{x.count}} {{x.product}} {{x.subtotal}} {{x.unit}} {{x.total}} {% endfor %} -
Python: getting all combinations from dictionary with list values (i.e permutation)
I used django-oscar and I need to auto-create product variants from one parent product, that has multiple color, size, textile options. I have the following ProductAttributeValues rows, which I use to populate the auto-created variants. [ OrderedDict([('value', <QuerySet [<AttributeOption: Black>, <AttributeOption: White>]>, <AttributeOption: Red>]>), ('attribute', <ProductAttribute: dress Color>), ('product_class', 'dress')]), OrderedDict([('value', <QuerySet [<AttributeOption: M>, <AttributeOption: S>]>), ('attribute', <ProductAttribute: dress Size>), ('product_class', 'dress')]), OrderedDict([('value', <QuerySet [<AttributeOption: Cotton>, <AttributeOption: Wool>, <AttributeOption: Silk>, <AttributeOption: Nylon>]>), ('attribute', <ProductAttribute: dress Textile>), ('product_class', 'dress')]), ] I need to get all combination of the product variants like the following: [ { <ProductAttribute: dress Color>: <AttributeOption: Black>}, <ProductAttribute: dress Size>: <AttributeOption: S>, <ProductAttribute: dress Textile>: <AttributeOption: Cotton>, }, { <ProductAttribute: dress Color>: <AttributeOption: Black>}, <ProductAttribute: dress Size>: <AttributeOption: S>, <ProductAttribute: dress Textile>: <AttributeOption: Wool>, }, .... # this list should include all 24 possible combinations 3*2*4 = 24 # ] I tried to use itertools.product to get the results I wanted, but found no luck. Help needed! Thanks. Additional question. Would the following results be a better design? [ [ { "attribute": <ProductAttribute: dress Color>, "value": <AttributeOption: Black> }, { "attribute": <ProductAttribute: dress Size>, "value": <AttributeOption: S> }, { "attribute": <ProductAttribute: dress Textile>, "value": <AttributeOption: Cotton> } ], … -
correct usage of limit_choices_to in django models
Please help me to limit model team choices based on the company. Right now I put test value "1" and it's working correctly (function _limit_function). But how to limit it dynamically based on the selected company? class CustomCompany(models.Model): name = models.CharField(max_length=30, default="None", unique=True ) class CustomTeam(models.Model): name = models.CharField( max_length=30, default="None" ) company = models.ForeignKey( CustomCompany, on_delete=models.CASCADE, ) class CustomUser(AbstractUser): def _limit_function(): return {"company__id":1} phone = models.CharField( max_length=20, blank=True ) company = models.ForeignKey( CustomCompany, on_delete=models.CASCADE, default=1 ) team = models.ForeignKey( CustomTeam, on_delete=models.CASCADE, default=1, limit_choices_to = _limit_function() ) So, I need to limit variants of team values, based on the selected company. Please help to understand how to do this. -
TypeError: __str__ returned non-string (type MagicMock)
I'm writing some tests for my Django code and I'm mocking file and file storage. I've found this guide https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html so my mocks look like this # mocks.py image_mock = mock.MagicMock(spec=File, name='FileMock') image_mock.name = 'dummy.jpg' storage_mock = mock.MagicMock(spec=Storage, name='StorageMock') storage_mock.url = mock.MagicMock(name='url') storage_mock.url.return_value = '/tmp/dummy.jpg' any my failing test looks like this: import factory import mock from imagekit.signals import source_saved from .mocks import storage_mock, image_mock from .models import Car @factory.django.mute_signals(source_saved) class CarFactory(factory.django.DjangoModelFactory): class Meta: model = Car image = image_mock def test_case_one(self): with mock.patch('django.core.files.storage.default_storage._wrapped', storage_mock): car = CarFactory.create() And it fails with the following error: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:564: in create return cls._generate(enums.CREATE_STRATEGY, kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:337: in wrapped_generate return generate_method(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:141: in _generate return super(DjangoModelFactory, cls)._generate(strategy, params) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:501: in _generate return step.build() /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/builder.py:279: in build kwargs=kwargs, /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/base.py:315: in instantiate return self.factory._create(model, *args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/factory/django.py:185: in _create return manager.create(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/manager.py:82: in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/query.py:422: in create obj.save(force_insert=True, using=self.db) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:741: in save force_update=force_update, update_fields=update_fields) /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:779: in save_base force_update, using, update_fields, /home/admin/.virtualenvs/car-project/lib/python3.7/site-packages/django/db/models/base.py:870: … -
showing json data in django template?
I have json files generated and saved in a model and I want to show it's content in a template. I tried this but it didn't work : def ResultDetails(request, pk=None): result = get_object_or_404(models.Processed,pk=pk) json_ = result.json_result.path with open(json_) as json_file: detail = json.load(json_file) context = { 'result' : result, 'json' : detail } template = "patients/results.html" return render(request,template,context) and this how I call it in the template : <tr> <th scope="row">{{ json.NumberOfCells }}</th> <td>{{ json.Cells_Density }}</td> <td>{{ json.Cells_Area }}</td> <td>{{ json.Cells_Perimeter }}</td> <td>{{ json.Cells_Polymegethism }}</td> <td>{{ json.Cells_Pleomorphism }}</td> </tr> the table headers appear but the content not btw the json file is just like this : I followed an answer here which was this approach is there a better one or should i take another one ? -
Select2 in Bootstrap with Dependent/Chained autocomplete List. Did not work
I'm trying to create Dependent/Chained Dropdown List (with auto-complete) with Bootstrap4 and Django. I'm trying to use this solution. Everything works fine if the forms are dropdown List. <select id="id_country" name="country" class="form-control" > <option value="" selected="selected">---------</option> <option value="1">Colombia</option> <option value="2">Rusia</option> </select> <select id="id_city" name="city" class="form-control"> <option value="" selected="selected">---------</option> <option value="1" class="1">Bogotá</option> <option value="2" class="2">Moscú</option> <option value="3" class="2">San Petersburgo</option> <option value="4" class="1">Valledupar</option> </select> But when I try to set the autocomplete to the first field, the second field stops working (stops responding). My code (after changes) looks like this: <select id="id_country" name="country" class="form-control" data-toggle="select" title="Country" data-live-search="true" data-live-search-placeholder="Country"> <option value="" selected="selected">---------</option> <option value="1">Colombia</option> <option value="2">Rusia</option> </select> <select id="id_city" name="city" class="form-control"> <option value="" selected="selected">---------</option> <option value="1" class="1">Bogotá</option> <option value="2" class="2">Moscú</option> <option value="3" class="2">San Petersburgo</option> <option value="4" class="1">Valledupar</option> </select> Why the solution stops working after adding additional parameters to the select field. Is it possible to add some simple javascript code in template that will run it again so that the second drop down field react properly again. Any help will be appreciated. -
Django return form with errors
I have created two functions, a edit and update. In the edit view, I return the form, on my template I have a form post to the update function. I am trying to return the form errors back to the page but how can I do that when it hits the update function? I know I could do all in one function and do a if request.method == 'POST but i'd figure to separate them. (Is my solution even the correct way to do in Django?) My goal is to do a return redirect with form, which then form would hold the errors. def locations_edit(request, id): location = Location.objects.filter(rand_id = id, user_id = request.user.id).first() if location is None: print('Error') return redirect('company-locations') context = { 'title': 'Edit Location - ' + location.name, 'pagetitle': 'Editing "' + location.name + '" Location ', 'tab_name': 'locations', 'new_location': 0, 'location': location } return render(request, 'company/locations/add_edit.html', context) def locations_update(request, id): location = Location.objects.filter(rand_id = id, user_id = request.user.id).first() if request.method == "POST" and location is not None: form = AddLocationForm(request.POST, instance=location) if form.is_valid(): form.save() messages.success(request, f'Location {location.name} updated') else: print(form.errors) return HttpResponse('Error') #return redirect('company-locations-edit', id=location.rand_id, *args={'form':form}) else: raise Http404 return redirect('company-locations-edit', id=location.rand_id) -
apache not servce media file django when debug =false
I use Linux VPS to run my application for android API and use apache web server when the debug is true my app work completely, but when debug is false I can't access my media file and get an error this is my apache conf : and this is my setting.py: and this is my media location: where is wrong and how to fix it debug false in my production and serve media file completely -
django queryset to output foreignkey objects to ModelChoiceField
class Location(models.Model): name = models.CharField() class Point(models.Model): name = models.CharField() location = models.ForeignKey('Location') I have a list of locations: Location A Location B Location C Every Point belongs to a location: Point 1 -> Location A Point 2 -> Location B I want to provide a queryset to a forms.ModelChoiceField so that it shows only Locations which have a Point associated in the database (in the example above it should only return Location A and Location B). In SQL language it would be: SELECT location.* FROM location JOIN point ON location.id = punto.location_id I've spent the last two hours reading the Django documentation, but I couldn't find any method to do what I need... any advice? -
Obtain mamytomanyfield value in anchor tag in template - Django
I am new to Django and trying to add program_code value to anchor tag. here are the codes: models.py class Program(models.Model): class Meta: verbose_name_plural = 'Program' program_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) program_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' program = models.ManyToManyField(Program, blank=False) course_code = models.CharField(max_length=10, default='', unique=True, validators=[MinLengthValidator(1)]) course_title = models.CharField(max_length=100, default='', validators=[MinLengthValidator(10)]) urls.py urlpatterns = [ path('',views.programs,name='programs'), path('<slug:program_code_no>/',views.courses,name='courses'), path('<slug:program_code_no>/<slug:course_code_no>',views.all_items,name='all_items'), ] views.py def programs(request): obj = Program.objects.all() paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/programs/index.html',context=all_details) def courses(request,program_code_no): obj = Courses.objects.filter(program=program_code_no) paginator = Paginator(obj,20) page = request.GET.get('p', 1) list = paginator.get_page(page) all_details={ 'lists': list, } return render(request,'courses/courses/index.html',context=all_details) def search(request): query = request.GET.get('q') if query: course_search = Courses.objects.filter( Q(course_code__icontains=query) ).distinct() else: return redirect('/') all_details = { 'courses': course_search, } return render(request,'index/search.html',context=all_details) However, I get this error when I try to get http://127.0.0.1:8000/search/?q=c ('c' is a course_code field) search.html {% if courses %} {% for i in courses %} <a href="{% url 'courses:all_items' **i.program.program_code** i.course_code %}{% endfor %} "> <span>{{ i.course_title|title }}</span> </a> {% endfor %} {% endif %} I have to get value of program_code in anchor tag and program_code is from Program model and program is from Courses … -
Get second item of queryset in html file (Django)
How can I get the second item of queryset in html file (Django)? I tried {{ posts[1] }} -
Nested Serializer in Django Rest Framework
I am trying to make a nested serializer but when I run the following code it gives me an empty list. I tried to replicate the solution of this question and my problem is exactly similar The only difference is in that answer serializer.Serializer is used but I am using Model Serializer class hhhSerializer(serializers.Modelserializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(read_only=True) class Meta: model = ItemBatch fields = ('id','name') class dispatchhistorySerializer(serializers.ModelSerializer): truck_name = ReadOnlyField(source='truck_name.name') truck_type = ReadOnlyField(source='truck_type.name') items = hhhSerializer(many=True) class Meta: model = DispatchPlan fields = "__all__" Output: "id": 35, "truck_name": "24 ft mxl 14 Ton", "truck_type": "Container", "items": [ {}, {}, {}, {}, {}, {}, {}, {}, {}, {} ], -
NameError name 'ApplicationcreateView' is not defined
I've created an app where by a user can create a job and the other user can apply to that specific job.My problem is that when another user tries to apply for the job, on submitting the application view i get a NameError at /*/*/ name 'ApplicationcreateView' is not defined this error is due to the form_valid method in the ApplicationcreateView in the last line of views.py may some one please help me out,here is what i've tried in my code . thanks in advance models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True, null=True) career_briefing = models.CharField(max_length=250, null=True) class Attachments(models.Model): application = models.ForeignKey(Application, related_name='attachments', on_delete=models.CASCADE) cv = models.CharField(max_length=150, null=True) forms.py class ApplicationForm(forms.ModelForm): cvs = forms.CharField(max_length=6000, widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('career_briefing', 'job',) views.py class ApplicationCreateView(LoginRequiredMixin, CreateView): model = Application form_class = ApplicationForm message = _("succesfuly applied") template_name = 'jobs/application_form.html' def form_valid(self, form): cvs = form.cleaned_data['cvs'] form.instance.user = self.request.user apply = form.save(commit=False) apply.user = self.request.user apply.save() doc = Attachments(cv=cvs) doc.application = apply doc.save() return super(ApplicationcreateView,self).form_valid(form) My expectations are that after a user fills a form he is directed back to the job details but i just end up … -
I want to know how to change html table block color through jinga and django views?
i want to change the color of every block of table according to fee status of student. i.e if fee is not submitted then it should be red, after submission it should be green. I have tried if loop in template but the problem is i am not getting method to compare each class fee with present class fee. <table class="table datatable-key-basic"> <thead> <tr> <th>Student ID</th> <th>Student Name</th> <th>Class</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> <th>January</th> <th>February</th> <th>March</th> <th>Save</th> </tr> </thead> <tbody> {% for info in fee_record %} <tr> {% csrf_token %} <td>{{info.auto_increment_id}} <br /><a href="{% url "updatefeerecord" id=info.auto_increment_id %}">Edit fee</a></td> <td>{{info.first_name}} {{info.last_name}}</td> <td>{{info.selectclass}}</td> <td><div >{{info.april}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.may}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.june}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.july}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.august}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.september}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.october}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; height:20px; padding:0;">Print reciept</button></td> <td><div >{{info.november}} </div><br><button class="btn btn-info" id="cancel-next" type="submit" style="width: 75px; … -
Problem converting from standard django form select to select2
I am trying to convert django form from using standard select to select2. I have followed instruction and installed django-select-forms, added select2 to INSTALLED_APPS, and include select2 links and scripts in the header block Here is my original code Model.py class Photographer(models.Model): author_id = models.CharField(max_length=50, primary_key=True) displayname = models.CharField(max_length=50) forms.py class UploadFileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.fields['author'].required = True self.fields['author'].queryset = Photographer.objects.all().order_by('displayname') Is ther anyway I can do this without changing my model? -
How to send alert or message from view.py to template?
I am uploading a .xls file from frontend template to Django. In views.py I'm validating the fields of the .xls file, if all is fine I save the file. If there is a problem I wish to send a message or alert back to the template with the alert message which specifies what went wrong. I would prefer if the error msg is shown below the file upload field, however, any js alert or any other way is fine too. Please help. Thanks Extra: If possible I would like to change a span element in my template. Is it possible to do it from views.py? (I'm uploading the file using AJAX request.) I tried using messages but nothing is happening. In views.py: if request.method == 'POST' and request.FILES: . --code to verify and save the file or generate error msg-- . if error != 'false': messages.info(request, 'The file you uploaded has the following problem: '+error+'. Please fix it and upload the file again') In template: {% block content %} --lot of html-- . --file upload field-- . {% if messages %} <ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} . … -
Django Management Command does not import correctly
I am trying the execute a management command in Django that doesn't quite correctly import the modules. My project structure is as follows: myproject/ |-- appname/ | |-- __init__.py | |-- management/ | | |-- commands/ | | | |-- __init__.py | | | |-- somefile.py | | |--__init__.py | |-- migrations/ | |-- admin.py | |-- apps.py | |-- views.py | |-- models.py | |-- urls.py |-- myproject/ | |-- __init__.py | |-- settings.py | |-- urls.py | |-- wsgi.py |-- manage.py ` myapp/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' myapp/init.py default_app_config = 'myapp.apps.MyAppConfig' myapp/management/commands/somefile.py from django.core.management import BaseCommand from django.utils.datetime_safe import datetime from myproject.myapp.models import Car class Command(BaseCommand): help = "Create initial data" def handle(self, *args, **options): cars = Car.objects.all() print(cars) self.stdout. write('Command successfully executed!') Traceback (most recent call last): File "myapp/management/commands/somefile.py", line 4, in from myproject.myapp.models import Car ModuleNotFoundError: No module named 'myproject' How do I configure the app to have the management command address the correct dir? -
command not found: django-admin when using django-admin startproject prj in mac
I'm trying to start a new project using django usign the command django-admin startproject prj1 in Mac, but it shows command not found:django-admin. -
'User' object has no attribute 'get' when trying to get user data in update profile form
im new in django. i'm trying to get user data in the update form. here is my code: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=1) image = models.ImageField(upload_to='profile_images', default='default.jpg') def __str__(self): return f'{self.user}' forms.py class UpdateUserForm(forms.ModelForm): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'uk-input', 'placeholder': 'Last Name'})) class Meta: model = User fields = ['first_name', 'last_name'] class UpdateProfileForm(forms.ModelForm): image = forms.ImageField(widget=forms.FileInput(attrs={'class': 'uk-button uk-button-default uk-button-medium uk-width-1-1', 'type': 'file'})) class Meta: model = Profile fields = ['image'] views.py @verified_email_required def profile_view(request): u_form = UpdateUserForm(request.user) p_form = UpdateProfileForm(request.user.profile) title = 'Profile Page' template_name = 'profile.html' context = { 'title': title, 'u_form': u_form, 'p_form': p_form } return render(request, template_name, context) and i get this error: 'User' object has no attribute 'get' -
How to modify data of auth_user column using django in postgresql
I want to modify column for auth_user through Django project. I have created an HTML page to allow the user to change their info in auth_user column. I have tried many things but none worked. Please help -
How to use ModelChoiceField with ModelForm and AbstractUser DJANGO
I want to create a dropdown button on an invoice page for the manager to select the appropriate customer to send to and save it. My current issue is to set up the forms.py and views.py correctly I believe. In regards to the forms.py I have tried using forms.Form without the class Meta and when i press 'SAVE' button on the HTML page ,the terminal return: 'UserDropDownForm' object has no attribute 'save' USERAPP - models.py User = settings.AUTH_USER_MODEL class User(AbstractUser): is_customer = models.BooleanField(default=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) phone_number = models.CharField(max_length=10) city = models.CharField(max_length=30) state = models.CharField(max_length=30) postal_code = models.CharField(max_length=30) active = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50) company_name = models.CharField(max_length=30) active = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username INVOICEAPP - models.py class Invoice(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_invoices') number = models.IntegerField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_paid = models.BooleanField(default=False) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Service, on_delete=models.CASCADE, related_name='invoice_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) INVOICEAPP - forms.py class UserDropDownForm(forms.ModelForm): user_form = forms.ModelChoiceField(queryset=User.objects.order_by('id').filter(is_customer='True')) # class Meta: (DO I NEED CLASS META????) # model … -
Django + tox: Apps aren't loaded yet
I'm migrating a Django project to use Tox and pytest. I'm getting the following when running tox. _________________________________________ ERROR collecting fixtureless/tests/test_django_project/test_app/tests/test_factory.py _________________________________________ fixtureless/tests/test_django_project/test_app/tests/test_factory.py:10: in <module> from test_app.models import ModelOne, ModelTwo fixtureless/tests/test_django_project/test_app/models.py:11: in <module> class ModelOne(models.Model): .tox/py36-django21/lib/python3.6/site-packages/django/db/models/base.py:87: in __new__ app_config = apps.get_containing_app_config(module) .tox/py36-django21/lib/python3.6/site-packages/django/apps/registry.py:249: in get_containing_app_config self.check_apps_ready() .tox/py36-django21/lib/python3.6/site-packages/django/apps/registry.py:132: in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Here is my tox file. [tox] skipsdist = true envlist = py{36,37}-django21, py{36,37}-django22, # Add environment to use the default python3 installation [testenv] setenv = PYTHONDONTWRITEBYTECODE=1 PYTHONPATH = {toxinidir}:{toxinidir}/fixtureless/tests/test_django_project DJANGO_SETTINGS_MODULE = settings.postgres deps = pillow psycopg2 pytest django21: Django>=2.1,<2.2 django22: Django>=2.2,<2.3 commands = pytest It's like django.setup() isn't being invoked or something. I'm fairly new to tox still. Any help would be greatly appreciated. This is an open source project (django-fixtureless) and I have been successfully running the Django test suite using the instructions outlined here. -
My css and images arent showing in django
I'm very new to using Django and am having issues with my css and images appearing in my home.html. I added a STATICFILES_DIR after looking it up, however it's still no appearing. I also tried adding path('', include('template/pesq.css')) to urlpatterns but that just caused some errors so I took it out. home.html <html> <head> <title>homepage</title> {% load static %} <link href="{% static 'pesq.css' %}" rel="stylesheet"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> ... urls.py from django.urls import path from . import views from django.conf.urls import url, include app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("", views.register, name='register'), path('tinymce/', include('tinymce.urls')), #path('', include('template/pesq.css')) ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Context, loader from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from .models import info # Create your views here. def homepage(request): return render(request=request, template_name="template/home.html", context={"info": info.objects.all})#context_instance=RequestContext(request), def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') login(request, user) return redirect("main:homepage") else: for msg in form.error_messages: print(form.error_messages[msg]) return render(request = request, template_name = "main/register.html", context={"form":form}) form = UserCreationForm return render(request = request, template_name = "main/register.html", context={"form":form}) setting.py ... DEBUG = True ... INSTALLED_APPS … -
How to validate a single field in a django form after an ajax request
I'm trying to validate a single field in a django form, after an ajax request - which I would prefer to validate on the backend rather than the frontend due to the detailed validation required. However using ajax means I can give earlier feedback to the user if the validation fails, before having to validate the full form. So instead of checking if form.is_valid() I could just check the field instead? def some_ajax_view(request): form = Form(request.POST): if form.is_valid(): .... -
how to correct binascii.Error: Incorrect padding?
i was writing a view in view.py and i tried to get the username (b2b_pan) that already loged in from the Header. then i figured out that i can get it by using request.META, but i got some problem and i don't know why here is the Code: class InventoryListView(generics.ListAPIView): permission_classes=[IsAuthenticated,] pan = "" b2b_pan = "" # def header_auth_view(request): def get (self,request, *args, **kwargs): the_serializer = InventorySerializer(data = request.data) auth_header = request.META['HTTP_AUTHORIZATION'] encoded_credentials = auth_header.split(' ')[1] #remove basic to isolate credentials (basic username:password) decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':') b2b_pan = decoded_credentials[0] if the_serializer.is_valid(): pan = request.data['pan'] the error is : File "/home/.venv/lib/python3.7/base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding