Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying LONGBLOB images in django template
I already inserted image as LONGBLOB datatype into the database and now trying to display the image by converting LONGBLOB to image in django template, How to do it? using MySQL Database views.py items=Products.objects.all() return render(request, 'display.html',{'itemLists':items}) display.html {% for item in itemLists %} <div class="box product-img"> <img src="data:image/jpg;charset=utf8;base64,{{item.image}}" alt="{{item.name}}"> <h3>{{item.name}}</h3> </div> {% endfor %} Got stucked in this code, How to do it? Any idea about How to decode the image in template itself ? -
NET::ERR_CERT_COMMON_NAME_INVALID error on GCP hosted Django site on email reset request using SendGrid. Namecheap domain
I've built a Django site which is hosted on GCP App Engine with SendGrid as email host. When resetting the password and clicking on the link in the following email, the subsequent error is thrown: Your connection is not private NET::ERR_CERT_COMMON_NAME_INVALID I've looked into several potential causes (linked at the end) but haven't been able to find a solution. password_reset_email.html (only displaying the reset_link block) {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} settings.py ALLOWED_HOSTS = ['*'] # Also tried with #ALLOWED_HOSTS = ['*', 'website.com', 'www.website.com'] # HTTPS settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Email backend settings (SendGrid) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'some@email.com' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have authenticated the domain and branded the link on SendGrid which have been verified over the DNS records on Namecheap. When I look at the certificate in the browser it still refers to *.sendgrid.net though. Perhaps this might be causing it? I thought authentication and link branding would solve that. I've … -
Django 3.2.7 - NoReverseMatch at /blog/ Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name
While following a tutorial from "Coding For Everybody - Learn wagtail", i ran into a problem while messing with the Routable Pages video, which i copypasted the code found at his GitHub into my Blog and now the following error appears: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/blog/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for ' latest_posts' not found. ' latest_posts' is not a valid view function or pattern name. Exception Location: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\pedro.garcia\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['C:\\Users\\pedro.garcia\\website\\mysite', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\pedro.garcia\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 15 Oct 2021 13:28:15 +0000 My latest_posts.html: {% extends "base.html" %} {% load wagtailimages_tags %} {% block content %} <div class="container"> <h1>Latest Posts</h1> {% for post in posts %} <div class="row mt-5 mb-5"> <div class="col-sm-3"> {% image post.blog_image fill-250x250 as blog_img %} <a href="{{ post.url }}"> <img src="{{ blog_img.url }}" alt="{{ blog_img.alt }}"> </a> </div> <div class="col-sm-9"> <a href="{{ post.url }}"> <h2>{{ post.custom_title }}</h2> {# @todo add a summary field to BlogDetailPage; make it a RichTextField with only Bold and Italic enabled. #} <a href="{{ post.url }}" … -
Cache Django related field in running Python process
class Publisher(models.Model): name = models.CharField(max_length=200) class Book(models.Model): publisher = models.ForeignKey(Publisher, on_delete=models.PROTECT) name = models.CharField(max_length=255) There is a DRF serializer that returns the books and publisher associated with the book. There are thousands of books whereas only a hundred publishers. The data distribution is 1:1000 and hence it makes sense to store publisher objects in Python app cache after the first load till the next app restart. How can I cache the publisher using lru_cache in Python? Constraints and other info I'm already using Django cache with redis backend for other purposes and I don't think redis would give a significant boost(same network call + lookup). Adding custom manager to the Publisher model with get, filter, all doesn't help. all method gets called while related field lookup happens but there is no id in the instance to find the lookup. The object lookup happens in the related description get. Is there a way to change the behavior without writing custom Field? -
Is using django-rest-framwork secure? [closed]
I want to use django rest framework to build an API which allows a website I'm making to access a database. How do I make it so that only that website can access the api(or that I at least know who is accessing it). -
How to run custom function when object deleted in StackedInline?
I have 2 models: User and Photo, Photo is StackedInline into User in admin panel. I want to run my custom function when any photo of a user is deleted. I have overridden method save_model in admin.py. def save_model(self, request, obj, form, change): photoset = request.FILES.getlist('photo') if len(photoset) == 0: obj.save() else: obj.save() for file in photoset: user_image = UserImage(user=obj) user_image.photo.save(file.name, file) user_image.save() my_custom_function() I know that when I delete a photo I get into if block, but now if block works only when User doesn't upload any image when registring. I know about signals but I'm sure it's my case. Is it possible to achieve this result in save_model method? Thanks in advance! -
Add Product immediately in Order (shop without cart) [django]
I make a store, without a cart, that is, an order is immediately created and saved to the database as order, but it looks like a cart. My models: STATUSES = ( ('NEW', 'New'), ('PROGRESS', 'Progress'), ('DONE', 'Done), ) class Order(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() phone = models.CharField(max_length=20) delivery_time = models.DateTimeField() address = models.CharField(max_length=200) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_paid = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null-True) status = models.CharFiels(max_lenght=20, choises=STATUS class Meta: ordering = ['-created_at'] def __str__(self): return f'Order: {self.id} on name {self.first_name} {self.last_name}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return f'{self.id}' def get_cost(self): return self.product.price * self.quantity class Product(models.Model): title = models.CharField(max_length=100, db_index=True, unique=True) slug = models.SlugField(max_length=150, db_index=True) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=7, decimal_places=2') in_stock = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['title', '-created_at'] index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:detail', args=[self.pk, self.slug]) I need a views, for add product in Order. Any help needed. Who could do that. Or who has seen something similar somewhere. … -
filter a select with the data of another select all in a modal
form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] views def creazione(request, nome): scheda = get_object_or_404(Schede, nome_scheda = nome) eserciziFormSet = formset_factory(EserciziForm, extra = 0) if request.method == "POST": #gruppi 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 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: #filtro esclusione gruppi già aggiunti 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) I have to filter the second select having using the first one. this code is inside a modal and the blue box (see photo) are form sets. how can i do to filter the data? From what I understand it is necessary to use AJAX I accept all the solutions but the answers without its use are more welcome as it is not very practical. -
is using multiples databases in django help performance?
Hi i have created a web app.inside my project have 3 more apps(Profile,Post,Comment) and for all of them i use one database in mysql.My question is:is using three databases(Profile_db,Post_db,Comment_db) will make some differences instead of using one database ?.I mean in the performance side. -
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