Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF and React Login, JWT authentication header missing in request
I'm currently making a Login System in a Django/React and the SimpleJWT RestFramework and so far everything related to JWT and protected (API)Views, works except in the Django Frontend. The Login Frontend is in React, which posts the login credentials and gets the JWT-Token from the api and saves them to localstorage and sets it as header for axios: const handleSubmit = (e) => { e.preventDefault(); axiosInstance .post(`token/`, { email: formData.email, password: formData.password, }) .then((res) => { localStorage.setItem('access_token', res.data.access); localStorage.setItem('refresh_token', res.data.refresh); axiosInstance.defaults.headers['Authorization'] = 'JWT ' + localStorage.getItem('access_token'); history.push(""); location.reload(); }).catch(err => console.log(err)); }; api urls.py: path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), Every API call i make with axios works and only returns after logging in... as it should be... BUT the problem is in the second Frontend, which is in Django. It is a partly static frontend that consists mainly out of simple html-templates for the Homepage, but with a Navbar which requires User information. @api_view(['GET']) def home(request): print(request.header) context = { 'posts': posts } return render(request, 'SmartGM_MainApp/home.html', context) I noticed that the Authentication Header are simply missing: When i try to print the user-data after logging in : request.user, output is AnonymousUser After making the template view protected by … -
Getting Error While Saving Recovery Model In Django
I am getting "django.db.utils.IntegrityError: UNIQUE constraint failed: app_recovery.id" Error while saving my Recovery Model: I sended POST request on PostMen with data {'party': 1, 'party_order': '2', 'sale_officer': 1, 'payment_method': 'Clearing', 'bank': '', 'amount': '500000', 'description': 'Group Recovery'} Its raised UNIQUE constraint but saved Data. My Model : class Recovery(models.Model): date = models.DateField(default=timezone.now, blank=True) party = models.ForeignKey(Party,on_delete=models.CASCADE) status = models.CharField(max_length=50, choices=[('Pending', 'Pending'), ('Approved','Approved')], default='Pending') party_order = models.ForeignKey(PartyOrder,on_delete=models.CASCADE,null=True,blank=True) sale_officer = models.ForeignKey(SalesOfficer,on_delete=models.CASCADE) payment_method = models.CharField(max_length=20,choices=(('Cash','Cash'),('Bank','Bank'),('Clearing','Clearing'))) bank = models.ForeignKey(Bank,on_delete=models.CASCADE,null=True,blank=True) amount = models.FloatField() description = models.CharField(max_length=50) pl = models.ForeignKey(PartyLedger,on_delete=models.CASCADE,null=True,blank=True) bl = models.ForeignKey(BankLedger,on_delete=models.CASCADE,null=True,blank=True) cl = models.ForeignKey(CashLedger,on_delete=models.CASCADE,null=True,blank=True) cll = models.ForeignKey(ClearingLedger,on_delete=models.CASCADE,null=True,blank=True) def _str_(self): return str(self.id) + ':' + self.sale_officer.name def save(self, *args, **kwargs): if self.id == None: super(Recovery, self).save(*args, **kwargs) if self.party_order: order = PartyOrder.objects.get(id=self.party_order.id) order.pandding_amount -= self.amount order.save() else: if self.status == 'Approved': if self.party_order: pl = PartyLedger(party=self.party,sales_officer=self.sale_officer, freight = self.party_order.freight,transaction_type='Credit', description=self.description, total_amount=self.amount) pl.save() else: pl = PartyLedger(party=self.party,sales_officer=self.sale_officer, transaction_type='Credit', description=self.description, total_amount=self.amount) pl.save() self.pl = pl if self.payment_method == 'Bank': bl = BankLedger(bank=self.bank,transaction_type='Debit', description=self.description, total_amount=(self.amount)) bl.save() self.bl = bl elif self.payment_method == 'Cash': cl = CashLedger(transaction_type='Debit', description=self.description, total_amount=(self.amount)) cl.save() self.cl = cl elif self.payment_method == 'Clearing': ccl = ClearingLedger(transaction_type='Debit', description=self.description, total_amount=(self.amount)) ccl.save() self.cll = ccl super(Recovery, self).save(*args, **kwargs) serializer: class RecoverySerializer(serializers.ModelSerializer): class Meta: model = m.Recovery fields = … -
DRF Create object with nested object parameters
I have this two classes in my Django Rest Framework project class Call(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) client = models.ForeignKey('client.Client', on_delete=models.CASCADE, db_column='id_client') class Client(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=250, unique=True) Then I have my view that simply extend "CreateApiView" without any additional code and then the serializer: class CallSerializer(serializers.ModelSerializer): client = ClientSerializer() What I simply need to do is to create a Call object after a POST, sending as parameters my client object. The problem is that if I do so, django returns me this error: A client with that name already exists. So I tried to edit the serializer this way ClientSerializer(read_only=True) but this time it creates the Call object with Client set to null. How can I fix this? I know I can simply remove the nested ClientSerializer and then send the ID instead of the whole Client object, but is there a way to do it with the nested serializer? -
Django server not displaying the database information in the html template
I am trying to do an ecommerce and when creating the database it does not update in the checkout.html. page. Below the code. views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer = customer, complete = False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {} return render(request, 'store/checkout.html', context) checkout.html {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price|floatformat:2}}</p></div> <div style="flex:1"><p>x{{item.quantity}}</p></div> </div> {% endfor %} it works for cart.html but it does not work for checkout.html and there is no errors shown to look for. Any help will be appreciated. -
How to only create .pot files with django manage.py makemessages
Weblate has an add-on called "Update PO files to match POT (msgmerge)". I want to delegate the creation of .po files to Weblate and only use manage.py makemessages to create the .pot file(s). manage.py makemessages has a --keep-pot option, which adds .pot files to the output. Unfortunately there is no option to only keep the .pot files. -
How to configure tabwidth in djhtml?
I've Djhtml installed and working correctly and I want Djhtml (https://github.com/rtts/djhtml) to configure the tabwidth from 4 (default) to 2 of the django template. But due to lack of documentation I'm unable to do. This line in readme.md of the djhtml -t / --tabwidth: set tabwidth (default is 4) give a general of how to do it, but I can't get it to work. I've tried these commands but was unable to change the tabwidth: djhtml -t/2 detail.html; djhtml -t/tabwidth=2 detail.html Thanks! -
How do I solve a traceback when runing manage.py commands?
I am pretty new to Django and I was just following along witht the tutorial. I was making a project from https://github.com/justdjango/getting-started-with-django, and after I added users and a superuser, I started to get a Traceback like this: Traceback (most recent call last): File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\auth\__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\apps\registry.py", line 204, in get_model app_label, model_name = app_label.split('.') ValueError: not enough values to unpack (expected 2, got 1) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Dell\Desktop\prog\manage.py", line 22, in <module> main() File "C:\Users\Dell\Desktop\prog\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Dell\Desktop\prog\programa\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File … -
Django - how to retrieve object by foreign key only?
I have a model PredictorSetterItem, which has a foreign key pointing to PredictorSetter model: class PredictorSetterItem(models.Model): predictor_setter = models.ForeignKey(PredictorSetter, null=False, on_delete=CASCADE, related_name="predictors") When PredictorSetterItem is created, it's assigned a PredictorSetter model in the following way: pdi = PredictorSetterItem() pdi.predictor_setter = predictor_setter so, as I understand, predictor_setter inside PredictorSetterItem, while being a ForeignKey, points to one and only one PredictorSetter object, so one PredictorSetter can be pointed by multiple PredictorSetterItems, but each PredictorSetterItem has one and only one associated PredictorSetter. My question is - how do I retrieve PredictorSetter object back? I can't directly get it's attributes via predictor_setter.attribute statements from inside PredictorSetterItem object. So I need to formulate a QuerySet and get the model, but I have no idea how to do that. I don't know primary key or any another attribute of PredictorSetter to filter, but this should be unnecessary, since PredictorSetterItem is associated with one and only one PredictorSetter object. -
Django annotate with model values
The Django docs on aggregation give the following example for annotations: for store in Store.objects.all(): store.min_price # Error! min_price not defined! for store in Store.objects.annotate(min_price=Min('books__price')): store.min_price # Fine However, we only annotated a single field. We only know what the price of the cheapest book is, but not exactly which is the cheapest book. What if I wanted the result of the annotation be precisely that book, not just its price? (I'll call this function or class AggregateRelation) for store in Store.objects.annotate( cheapest_book=AggregateRelation('books__price', Min) ): store.cheapest_book.price store.cheapest_book.title Is there a way to do this? I checked up FilteredRelation but that's only useful for filtering. It does not truly retrieve the instances. -
pycharm Invalid id reference {%for%} {%endfor%}
The for tag of the form is not recognized <form action="{url 'regieter1'}" method="POST"> {% for item in form %} <div> <label for="{{item.id_for_label}}">{{item.label}}</label> </div> {% endfor %} </form> -
Django Keeping the same filter in pagination
I looked into the previous questions about this but did not find exactly the answer to my problem as I am not using django-filters. I am applying filters to a Search Page and I am using pagination. Of course when you move to the next page all filters are reset. I want to be able to include the same filters when we move from page to page. Here is my code: views.py: def recherche(request): filters = { 'intermediaire__name__icontains': request.POST.get('kw_intemediaire'), 'assurance__name__icontains': request.POST.get('kw_assurance'), 'matricule__icontains': request.POST.get('kw_matricule'), 'numero__icontains' : request.POST.get('kw_numero'), 'created_by__name__icontains' : request.POST.get('kw_created_by'), 'date_posted__icontains' : request.POST.get('kw_date_posted'), } filters = {k: v for k, v in filters.items() if v} dossiers = Dossier.objects.filter(**filters) print(filters) p = Paginator(dossiers, 10) page_num = request.GET.get('page', 1) try: dossiers = p.page(page_num) except EmptyPage: dossiers = p.page(1) context = { 'dossiers': dossiers, 'intermediaires': Intermediaire.objects.all(), 'assurances': Assurance.objects.all(), } return render(request, "dashboard/recherche.html", context) Template: <div class="pagination"> {% if dossiers.has_previous %} <a href="?page=1">Première page</a> <a href="?page={{ dossiers.previous_page_number }}">&laquo;</a> {% endif %} <p class="active">Page {{ dossiers.number }} sur {{ dossiers.paginator.num_pages }}</p> {% if dossiers.has_next %} <a href="?page={{ dossiers.next_page_number }}">&raquo;</a> <a href="?page={{ dossiers.paginator.num_pages }}">Dernière page</a> {% endif %} </div> I want to do this: I did add a print(filters) to the view to see how the filters … -
first select which filters the second without ajax
how can i create a filter that as soon as you choose the element of the first select filters the second select (see photo) i would try to do it without using ajax because i am not practical view def creazione(request, nome): scheda = get_object_or_404(Schede, nome_scheda = nome) eserciziFormSet = formset_factory(EserciziForm, extra = 0) if request.method == "POST": gruppo_form = GruppiForm(request.POST, prefix = 'gruppo') if gruppo_form.is_valid(): gruppo = gruppo_form.save(commit = False) gruppo.gruppi_scheda = scheda gruppoName = gruppo_form.cleaned_data['dati_gruppo'] gruppo.save() esercizi_formset = eserciziFormSet(request.POST, prefix='esercizi') for esercizi in esercizi_formset: esercizi_instance = esercizi.save(commit = False) esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName) esercizi_instance.save() return HttpResponseRedirect(request.path_info) else: gruppi_db = Gruppi.objects.all() group_to_add = Gruppi.objects.exclude(dati_gruppo__gruppi_scheda = scheda) GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add) gruppo_form = GruppiForm(prefix = 'gruppo') esercizi_formset = eserciziFormSet(prefix='esercizi') context = {'scheda' : scheda, 'gruppo_form' : gruppo_form, 'esercizi_formset': esercizi_formset, 'gruppi_db': gruppi_db} return render(request, 'crea/passo2.html', context) form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] #fields = '__all__' class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] -
Django 1.4: Tests are very slow
I am working on a old code base which still uses Django 1.4 This means the nice flag --keepdb is not available. Running a single test like this takes 50 seconds: time manage.py test myapp.tests.test_foo.FooTestCase.test_something My test_something method is fast. It is the creation of the test-DB which takes so long. 50 seconds is too long for a productive edit-test-cycle. What can I do (except faster hardware)? -
django setup error: django.db.utils.OperationalError
I'm setting up django with postgres, but when I type python manage.py migrate error shows up: Traceback (most recent call last): File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\demo\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1290, in check *cls._check_indexes(databases), File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1682, in _check_indexes connection.features.supports_covering_indexes or File "C:\Users\颚美\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
Django unable to find scripts in static folder
This might seem like a duplicate question but I dont whats going on but I have gone through stackoverflow and tried all the solutions but cant find the answer that I need. Here Django finds the style.css but cannot find the App.js and script.js literally located in the same folder as style.css. I cant seem to figure out the problem, I have wasted around 2 hrs trying to figure it out. Relevant HTML {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <title>Reyanna</title> <link rel="icon" href="https://img.icons8.com/nolan/96/bot.png" type="image/icon type"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="script" href="{% static 'App.js' %}"> <link rel="script" href="{% static 'script.js' %}"> </head> Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "home/static", ] Folders Home(Django App) |-> static |-> App.js |-> script.js |-> style.css |-> templates |-> index.html -
I am trying to make django app but this script error keeps coming
from django.contrib import admin from django.urls import path from buttonpython2 import views app_name = "buttonpython2" urlpatterns = [ path('admin/', admin.site.urls), path('', views.button) path('', views.output, name="script") ] this is my url.py this image shows the error enter image description here -
Django WizardForm save model using multiple forms
I have a model Customer: class Customer(models.Model): name = models.CharField( verbose_name='Bedrijfsnaam', max_length=100, unique=True ) street = models.CharField( verbose_name='Bezoek straat', null=True, max_length=150 ) house_number = models.IntegerField( verbose_name='Huisnummer', null=True ) zipcode = models.CharField( verbose_name='Postcode', max_length=6 ) city = models.CharField( verbose_name='Plaats', max_length=100 ) phone = models.CharField( verbose_name='Telefoon', max_length=100 ) mobile_phone = models.CharField( verbose_name='Mobiel Telefoon', max_length=100 ) fax = models.CharField( verbose_name='Fax', max_length=100, null=True, blank=True ) email = models.EmailField( verbose_name='E-mail' ) website = models.CharField( verbose_name='Website', max_length=100, null=True, blank=True ) kvk = models.CharField( verbose_name='KvK-nummer', max_length=20, help_text='s.v.p. uittreksel toevoegen, niet ouder dan 6 maanden' ) kvk_file = models.FileField( verbose_name='Uittreksel', max_length=2000, upload_to=kvk_directory_path, null=True, ) activities = models.TextField( verbose_name='Hoofdactiviteiten', null=True, blank=True ) total_employees = models.IntegerField( verbose_name='Aantal medewerkers', null=True, blank=True ) yearly_transactions = models.IntegerField( verbose_name='Verwachte jaarafname', null=True, blank=True ) order_confirmation = models.BooleanField( verbose_name='Opdrachtbevestiging altijd per email?', default=False ) confirmation_email = models.EmailField( verbose_name='E-mail opdrachtbevestigingen', null=True ) delivery_address = models.CharField( verbose_name='Afleveradres', max_length=100 ) delivery_zip = models.CharField( verbose_name='Postcode', max_length=6 ) delivery_city = models.CharField( verbose_name='Plaats', max_length=100 ) delivery_instructions = models.TextField( verbose_name='Instructies', null=True ) mail_address = models.CharField( verbose_name='Postadres', max_length=100, null=True, blank=True ) mail_zip = models.CharField( verbose_name='Postcode', max_length=6, null=True, blank=True ) mail_city = models.CharField( verbose_name='Plaats', max_length=100, null=True, blank=True ) iban = models.CharField( verbose_name='IBAN-nummer', max_length=36 ) btw = models.CharField( verbose_name='BTW-nummer', max_length=50 ) cash_pin = models.BooleanField( verbose_name='Contant/Pin', help_text='(alleen … -
How do you add a link in an f string?
I am trying to add a link in the f string below: d += f'<li> {event.time} {event.teacher} {event.student} {event.status} </li>' Basically, I want it to look something like below: f'<li> <a href="{% url 'somewhere' event.pk %}"> {event.time} {event.teacher} {event.student} {event.status} </a> </li>' However, I get the following error when I do this: SyntaxError: f-string: expecting '}' Do you guys know how to input a link in an f string? Please ask me any questions you have. -
query that must exclude me from the whole list
hi i have a problem with this filter. group_to_add takes some values which should filter out the problem that I don't want those values but I want the others without those. I would like to find a way to take those values and subtract them from others. group_to_add = DatiGruppi.objects.filter(gruppi_scheda = scheda.id) GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add) I asked a similar question I leave the link select filtering and removal if they are already present in the db -
Return Empty Page if There's No Filtering Provided in DRF and Django Filters
I have a ViewSet as below: class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = EntryFilterSet ordering_fields = ["created_at", "last_update"] ordering = "created_at" ...and a FilterSet defining several fields that I can filter against: class EntryFilterSet(django_filters.FilterSet): class Meta: model = models.Entry fields = [ "content", # and other fields ] I have connected my EntryViewSet to /api/entries/ with DefaultRouter of DRF, list view is automatically named as api:entry-list. So, /api/entries/ returns: { "count": 100, "next": "http://localhost:8000/api/entries/?format=json&p=2", "previous": null, "results": [ { "pk": "6Kqpyak", "created_at": "2021-10-13T13:28:17.410883Z", "last_update": "2021-10-13T13:28:17.410898Z", "content": "Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.", "content_html": "<p>Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.</p>", "author": 1, "title": { "pk": "6Kqpyak", "created_at": "2021-10-13T13:28:17.408026Z", "label": "republican attack computer recently though guy.", "redirects_to": null, "recent_count": 0, "last_update": "2021-10-13T13:28:17.416822Z" } }, { "pk": "1ozyMzx", "created_at": "2021-10-13T13:28:17.532635Z", "last_update": "2021-10-13T13:28:17.532649Z", "content": "School establish partner. Establish possible who let. Impact health exactly particular note.", "content_html": "<p>School establish partner. Establish possible who let. Impact health exactly particular note.</p>", "author": 2, "title": { "pk": "1ozyMzx", "created_at": "2021-10-13T13:28:17.531007Z", "label": "produce six while act.", "redirects_to": null, "recent_count": 0, "last_update": "2021-10-13T13:28:17.535188Z" } … -
django-puppeteer-pdf creates empty pdf
I'm trying to generate a pdf of Django class based detail view by using django-puppeteer-pdf. PDF file gets generated but when I open it, it contains only a word None and the rest of the page is blank. Here's the code: View I want to turn into pdf class CalculationDetailView(UserPassesTestMixin, LoginRequiredMixin, generic.DetailView): model = Calculation def test_func(self): return self.request.user.is_authenticated def get_queryset(self): qs = super().get_queryset() if not self.request.user.is_staff: qs = qs.filter(userid=self.request.user.pk) return qs View that generates pdf set up by following django-puppeteer-pdf docs class GenerateCalcDetailPdf(PDFTemplateView): filename = 'details.pdf' template_name = 'cycle\calculation_detail.html' header_template = 'base_generic.html' cmd_options = { 'margin-top': 3, } urls.py url(r'generate-pdf/$', views.GenerateCalcDetailPdf.as_view(), name='generate-pdf') The template content is dynamically rendered from the database and styled with Bootstrap. It contains static files and here are the static settings: PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(os.path.join(PROJECT_ROOT, 'orc2')) STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = 'static/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] Any advice or help is welcome since, according to docs I'm doing everything properly but for some reason it doesn't work properly. -
'QuerySet' object has no attribute 'META' 500(internal server erro)
I'm trying to practice ajax in django but I got this error 'QuerySet' object has no attribute 'META'. But it's showing the data in the traceback but not in the template because of the error.How to fix this? models.py from django.db import models # Create your models here. class Profile(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) bio = models.CharField(max_length=100) def __str__(self): return self.name I think it has something to do with the views but I cant figure it out. views.py from django.shortcuts import render from .models import Profile from django.http import JsonResponse # Create your views here. def list(request): return render(request, 'livedata/list.html') def getProfiles(request): profiles = Profile.objects.all() # print(JsonResponse({"profiles": list(profiles.values())})) return JsonResponse({"profiles": list(profiles.values())}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.list, name='list'), path('getProfiles', views.getProfiles, name='getProfiles') ] index.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% comment %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endcomment %} <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'js/main.js' %}" defer></script> <title>Hello, world!</title> </head> <body> {% block contents %}{% endblock contents %} {% block scripts %}{% endblock scripts %} <!-- … -
How to display error message with Django forms?
I would like to customize the Django login authentication form. The original form looks like this and it works perfectly: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 ">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> </div> </div> {% endblock content %} My goal is to modify the form style so that I can place the objects wherever I want. I was able to achieve this for the username and password fields, however I cannot display the error message just like in the original format. This is what I tried: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 ">Log In</legend> {% if formset.non_form_errors %} <div class="alert alert-block alert-danger"> {% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %} <ul class="m-0"> {{ formset.non_form_errors|unordered_list }} </ul> </div> {% endif %} <div class="row"> <div class="col-md-4 col-sm-12 register-field"> {{ form.username|as_crispy_field }} </div> <div class="col-sm-12 register-field"> {{ form.password|as_crispy_field }} </div> </div> … -
Djagno start server, scan Network and write data to DB
My idea Store network devices data threw a Django Model (Device Model) to my Database. Host configuration needs to be setup by User inside a View (Host Model) When the Host configuration is finished the Network should be scanned for devices (Device Model) The Data should be stored inside the DB The fuction create_devices() gets called before a host was setup, with migrate and makemigrations. How can i fix this? Is it even right to store this data via View to my Database? Bestcase would be storing data to the DB Async to my Application, is there a way? Thank you very much for your help!!! Host Model: class Host(models.Model): hostname = models.CharField(default="noads", max_length=6) ipv4_address = models.GenericIPAddressField('IPv4') ipv4_subnet = models.GenericIPAddressField('IPv4') gateway = models.GenericIPAddressField('IPv4') Device Model: class Device(models.Model): hostname = models.CharField(max_length=64) mac_address = models.CharField(max_length=64) ipv4_address = models.GenericIPAddressField('IPv4') My View: def get_arp_table_linux(): """ Parse the host ARP table on a Linux machine :return: Machine readable ARP table :rtype: dict {'ip_address': 'mac_address'} """ with open('/proc/net/arp') as proc_net_arp: arp_data_raw = proc_net_arp.read(-1).split("\n")[1:-1] parsed_arp_table = (dict(zip(('ip_address', 'type', 'flags', 'hw_address', 'mask', 'device'), v)) for v in (re.split('\s+', i) for i in arp_data_raw)) return {d['ip_address']: d['hw_address'] for d in parsed_arp_table} def get_devices_in_list(): """ Gets every device inside the … -
Can I use two urls for the same view in django?
So basically, can I have two urls(or paths) for the same view in django? I searched online for this question, but somehow I couldn't find a clear answer(in other word, please don't downvote me because it is a seemingly easy question). Thank you, and please let me know if you have any questions.