Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static root files
Hello i am currently working on a Django project where iam using CKEditor. Its working but if iam trying to customize CKEditor through STATIC ROOT where are all file for them is located, Django not reloading these files. I can even delete whole folder and CKEditor will still work, even i i tryed to delete browser caches atd.. settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
Why do I need to run the second loop to get the sigle value in django?
The project was to create a filter page where users can filter the model data based on their chosen criteria. The whole thing is working but a specific part is not clear and not making sense. Here is my model- class Author(models.Model): name=models.CharField(max_length=30) def __str__(self): return self.name class Kategory(models.Model): name=models.CharField(max_length=20) def __str__(self): return self.name class Data(models.Model): title=models.CharField(max_length=120) author=models.ForeignKey(Author, on_delete=models.CASCADE) categories=models.ManyToManyField(Kategory) publish_date=models.DateTimeField() views=models.IntegerField(default=0) reviewed=models.BooleanField(default=False) def __str__(self): return self.title Data is the main model while Author was added as ForeignKey and Kategory as many to many fields. My main issue is around this categories field in Data model which has many to many relationship with Kategory model. Here is my views.py file- # This view is for the filter page def is_valid_queryparam(param): return param !='' and param is not None def filter(request): qs=Data.objects.all() kategory=Kategory.objects.all() title_contains_query=request.GET.get('title_contains') id_exact_query=request.GET.get('id_exact') title_or_author_query=request.GET.get('title_or_author') view_count_min=request.GET.get('view_count_min') view_count_max=request.GET.get('view_count_max') date_min=request.GET.get('date_min') date_max=request.GET.get('date_max') category=request.GET.get('category') if is_valid_queryparam(title_contains_query): qs=qs.filter(title__icontains=title_contains_query) if is_valid_queryparam(id_exact_query): qs=qs.filter(id=id_exact_query) if is_valid_queryparam(title_or_author_query): qs=qs.filter(Q(title__icontains=title_or_author_query) | Q(author__name__icontains=title_or_author_query)) if is_valid_queryparam(view_count_min): qs=qs.filter(views__gte=view_count_min) if is_valid_queryparam(view_count_max): qs=qs.filter(views__lte=view_count_max) if is_valid_queryparam(date_min): qs=qs.filter(publish_date__gte=date_min) if is_valid_queryparam(date_max): qs=qs.filter(publish_date__lte=date_max) if is_valid_queryparam(category): qs=qs.filter(categories=category) test=Data.objects.only('author') context={'queryset':qs, 'kategory':kategory, 'test':test} return render(request, 'myapp/filter.html', context) As you can see in the views.py that I have 2 variables holding all of Data and Kategory model data. I have worked with this type … -
How to autoincrement values checkbox with jinja2 (Django) with reset
I need to autoincrement value in my checkbox and reset value when I generated new massive of checkbox forloop.count dont reset {% for ans in Answ %} {% if ans.question_id_id == Questions.id %} <input type="hidden" value="{{ Questions.id }}" name="id"> <div class="form-check" ><label><input type="checkbox" value="{{ ans.id }}" name="answer"> {{ ans.answer }} </label></div> {% endif %} {% endfor %} -
Run and follow remote Python script execution from Django website
I am running a Django website where user can perform some light calculation. This website is hosted in a Docker container on one of our server. I would like now to add the ability for the users to run some more complicated simulations from the same website. These simulations will have to run on a dedicated calculation machine (they will run in parallel for a several hours/days) under Ubuntu server in the same network. What will be the best way to achieve this? Send the calculation to the calculation serverand send them back automatically to Django? How can I follow the status of the calculation (waiting, calculating, finished) from the Django instance? Should I use a job scheduler on the calculation server? This is close to this question that was asked in 2014, so there might be more actual solutions. -
Django form is never valid and hence doesnt save to database
I am creating a registration model which has date,time(charfield with choices),customer and restaurant .I need some help on why my instance is not saved even when I fill out my model form models.py class reservation(models.Model): TIMESLOTS = [ ('11:00-1:00', '11:00-1:00'), ('01:00-3:00', '01:00-03:00'), ('03:00-05:00', '03:00-05:00'), ('05:00-07:00', '05:00-07:00'), ('07:00-09:00', '07:00-09:00') ] date=models.DateField(null=True) time=models.CharField(null=True,max_length=200,choices=TIMESLOTS) customer=models.OneToOneField(User,null=True,on_delete=models.CASCADE) restaurant=models.OneToOneField(Restaurantdetails,on_delete=models.CASCADE,null=True) def __str__(self): return self.restaurant.name forms.py class Reservationform(ModelForm): class Meta: model=reservation fields=['date','time','restaurant'] views.py def reservationcreator(request): form=Reservationform() if form.is_valid(): form = Reservationform(request.POST) res=form.save() res.customer=request.user res.save() messages.success(request, 'reservation created') return redirect('menu') else: print('BS') context = {'form': form} return render(request,'userrestaurant/reservation.html',context) -
Find all objects of a certain class who do not have any active links with other objects
I have a class A which is used as a Foreign Key in many other classes. class A(): pass class B(): a: A = ForeignKey(A) class C(): other_name: A = ForeignKey(A) Now I have a database with a huge table of A objects and many classes like B and C who reference A (say potentially dozens). In this table, there are many objects (100k+) and I want to clean up all objects that are not actively referenced by other objects with a Foreign Key. For example, object 1 of class A is not referenced by class B and C. How would I do this? I already came up with the following code: a_list: list = list() classes: list[tuple] = [(B, "a"), (C, "other_name")] for cl, field in classes: field_object: Field = cl._meta.get_field(field) for obj in cl.objects.all(): a: A = field_object.value_from_object(obj) a_list.append(a) to_remove: list[A] = [a for a in A.objects.all() if a not in a_list] for a in to_remove(): a.remove() This leaves me with a few questions: What if I don't know the full list of classes and fields (the case since it is a large group)? Is this the most efficient way to do this for a large table with … -
Edit form AuthAll Django
I'm new using Django and i'm using AuthAll to login/logout, the problem comes when i try to edit the template of the original form. I've created a the templates but i want to change the form with the inputs, originally there are no inputs just "{{form}}" line 38 . Is there a way to access to that inputs and change the style? Thanks!! I actually dont want to create views, i really want to use AuthAll and just change the style of the 2 inputs. I tried searching where its created the form but i think its automatic. -
How to get papypal client side info to django?
I am using PayPal standard IPN payment solution in client side in my Django web app. <body> <!-- Set up a container element for the button --> <div id="paypal-button-container"></div> <!-- Include the PayPal JavaScript SDK --> <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '88.44' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { // Successful capture! For demo purposes: console.log('Capture result', orderData, JSON.stringify(orderData, null, 2)); }); } }).render('#paypal-button-container'); </script> </body> everything works fine and I can access all the data through the details variable in the js code. Now, i need to insert the details into django db, how can it be done? No api, simple model. Tried many things, none worked. Thanks for the help! -
Best place to start to develop a website for someone who knows python
The small healthcare company I work for is looking to update the website that other employees enter data into that then gets sent to our database. The current website was coded by someone that isn't there anymore and no one really knows how to maintain it efficiently. Even though I am a data analyst my team has been tasked with this to do. Since I use python every day I was wondering if there was a good way to make all of this relying on python for most of it, or where would you guys point someone like me to start learning this? Thank you! I have heard of flask and Django but just wanted to see what people's opinions are for doing this kind of project. The website really just needs some basic interactivity like going to different pages and entering stuff into a field (and restricting what they can't enter) that then gets sent to a database. -
Mark specific Django migrations as fake migrations during test DB setup
I have some database migrations, some are structural migrations some are data migrations eg. 0001_initial.py 0002_move_data.py 0003_add_field.py 0004_move_more_data.py I would like to skip those data migrations (0002 and 0004) as I don't want to spend the effort to fake the source for those data migrations but still run 0001 and 0003 when running python manage.py test Is it possible? -
How to get foreign key attribute (or many to many attribute) of a model instance in Django in asynchronous queries?
In asynchronous queries, I want to get foreign key and many to many attributes of a model instance. In my case, I want to get university and courses of the model Student. models.py: from django.db import models class University(models.Model): name = models.CharField(max_length=64) class Course(models.Model): name = models.CharField(max_length=64) class Student(models.Model): name = models.CharField(max_length=64) university = models.ForeignKey(to=University, on_delete=models.CASCADE) courses = models.ManyToManyField(to=Course) when I use this code (in django 4.1): async for student in Student.objects.all(): print(student.university) print(student.courses) I get the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How can I fix this error? -
Will Django model instance always be populated when calling save()?
I have a model where I am overriding the save() function to add SearchVector's. I need to preprocess one of the instance's fields so I am overriding the save function: class Student(models.Model): first_name = models.CharField(max_length=255, default="") last_name = models.CharField(max_length=255, default="") search_vector = SearchVectorField(null=True) def save(self, *args, **kwargs): sv = SearchVector(Value(self.first_name)) + SearchVector(Value(self.last_name)) if len(self.last_name) > 3: sv += SearchVector(Value(self.last_name[0:3])) self.search_vector = sv super().save(*args, **kwargs) Can I expect that all fields (first_name & last_name) of the instance are always populated inside the save() function? I noticed that the instance loading function from_db seems to suggest that model instances can be created with a partial set of fields. Does this mean that first_name could be None on the save() call? -
How to make an ajax function to execute only in in a certain case?
I have an ajax function that updates every second some value on page, I want to update it only when the script is working, because to not request a value that is the same. The script is updating this value, and ajax is refreshing it on website, but when script is not working, my ajax is requesting the value. How to make it work only when the script is working? var interval = 1000; function update() { $.ajax({ type: 'GET', url: 'http://localhost:8000/api/updating', headers : {'Authorization': "Token "+ token,}, data: $(this).serialize(), dataType: 'json', success: function (data) { $('#points_a').html(data)// first set the value }, complete: function (data) { // Schedule the next setTimeout(update, interval); } }); } setTimeout(update, interval); This is script in python view, Django: def task(userid, seconds_for_thirtydays=0): if(seconds_for_thirtydays < 2592000): p_a = Wallet.objects.filter(name__id=userid).values("points").first()['points'] add = p_a + 1 result = Wallet.objects.filter(name__id=userid).update(points=add) seconds_for_thirtydays = seconds_for_thirtydays + 1 time.sleep(1) task(userid) else: return The thing that I want to make is: When the value is not changing(the script is not working), then this ajax won't work and won't make requests, is it possible? -
Django/Wagtail Media Files not showing up in the admin portal on a fresh install
I am working on a site in dev that contains a media folder. When I do a fresh setup of the site (empty db) and do all the migrations and steps to get the site up and running I noticed in the admin portal none of the images and assets in the media folder dont show up even though they exist. I have to re-import an image and then it shows up in the admin portal as expected. I have looked all over and cannot find an answer. To put it simply why isnt the admin portal importing existing files in the media folder on a fresh setup? django==3.2 wagtail==3.0 base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'media/' urls.py from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls from wagtail.contrib.sitemaps.views import sitemap from search import views as search_views urlpatterns = [ ... ] if settings.DEBUG: from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # Serve static and media files from development server urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If anyone has any idea? -
JS static files not working for Django Project
I am following this online countdown-tutorial https://www.youtube.com/watch?v=ZpujnQqcvAA to implement into my website. I feel I am missing something simple. base.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"> <!-- favicon --> <link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- custom js--> {% block scripts %} {% endblock scripts %} <title>countdown to events</title> </head> <body> <div class="container mt-3"> {% block content %} {% endblock content %} </div> </body> </html> main.html {% extends 'base.html' %} {% block content %} {% for obj in object_list %} <div> <a href={{obj.get_absolute_url}}>{{obj.name}}</a> </div> {% endfor %} {% endblock %} countdown.html {% extends 'base.html' %} {% load static %} {% block scripts %} <script scr={% static 'main.js' %} defer></script> {% endblock scripts %} {% block content %} <div class ="row"> <div class = "col-5"> <div>{{object.names}} will take place:</div> </div> <div class = "col-7"> <div id="event-box">{{object.when|date:"M d, Y H:m:s"}}</div> </div> </div> <div>Time left:</div> <div id ="count-down-box" class="text-center mt-3 h1"> <div class ="spinner-border" role = "status"></div> </div> {% endblock content %} main.js console.log('hello world') const eventBox = document.getElementById('event-box') const countdownBox = … -
How can I reduce the marker making time of Mapbox js
I don't understand why this page takes minutes to render, it takes so long that I get a gunicorn timeout... Anyway I could fix it ? I try to generate a marker for every address passed with django, the current address list has around 300 addresses Each marker also has a popup do display informations about the user or the event associated with it // Create a marker for each address {% for address in addresses %} {% if address.user.count|add:address.time_filtered_events.count >= 2 %} var el=document.createElement("div"); el.className="marker"; el.style.backgroundImage = `url(https://ssb.wiki.gallery/images/3/30/SandbagHeadSSBM.png)`; el.style.width = `20px`; el.style.height = `20px`; el.style.backgroundSize = '100%'; new mapboxgl.Marker(el) .setPopup(new mapboxgl.Popup().setHTML(...) .setLngLat([{{address.longitude}}, {{address.latitude}}]) .addTo(map); {% else %} {% for user in address.user.all %} var el=document.createElement("div"); el.className="marker"; el.style.backgroundImage = `url({{user.main.image}})`; el.style.width = `20px`; el.style.height = `20px`; el.style.backgroundSize = '100%'; // Add markers to the map. new mapboxgl.Marker(el) .setPopup(new mapboxgl.Popup().setHTML(...) .setLngLat([{{address.longitude}}, {{address.latitude}}]) .addTo(map); {% endfor %} {% for event in address.time_filtered_events %} var el=document.createElement("div"); el.className="marker"; {% if event in address.current_events %} el.style.backgroundImage = `url(https://i.ibb.co/bX2yVm5/green-smash-ball.png)`; {% else %} el.style.backgroundImage = `url(https://ssb.wiki.gallery/images/7/7a/FightingWireFramesHeadSSBM.png)`; {% endif %} el.style.width = `15px`; el.style.height = `15px`; el.style.backgroundSize = '100%'; {% endfor %} {% for event in address.time_filtered_events %} var el=document.createElement("div"); el.className="marker"; {% if event in address.current_events %} el.style.backgroundImage … -
Python Authlib: ResourceProtecter decorator for class based views
I am trying to secure a Django-DRF based API using Auth0. The Authlib resource protector works fine using a function-based views however when I try to apply the ResourceProtector decorator from Authlib to a class-based view it keeps returning an error 'ViewSet' object has no attribute 'build_absolute_uri'. It appears the decorator function is using the self argument instead of the request argument to get the url when it is applied to a class-based view causing the error. Is there any other way to use Authlib resource protector decorator to a class-based view? Views.py from api.permissions import auth0_validator from authlib.integrations.django_oauth2 import ResourceProtector from django.http import JsonResponse require_oauth = ResourceProtector() validator = auth0_validator.Auth0JWTBearerTokenValidator( os.environ['AUTH0_DOMAIN'], os.environ['AUTH0_IDENTIFIER'] ) require_oauth.register_token_validator(validator) #Resource protector decorator works here @require_oauth() def index(request): return Response('Access granted') class Users(ModelViewSet): #Resource protector decorator does not work and invokes error below @require_oauth() def list(self, request): return Response('access granted') stack trace Internal Server Error: /v2/statistics Traceback (most recent call last): File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line 68, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/td/Desktop/test-api/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in … -
How to automatically delete a Django Many-to-Many model entity once it no longer has any relations?
I have two models, Record and Tag. They have a Many-to-Many relationship. Tags also has a Many-to-Many relationship with a third model, Set. I'm using Django Rest Framework and the model serializer for Tag looks like this: class TagSerializer(serializers.ModelSerializer): usage_count = serializers.IntegerField( source="record_set.count", read_only=True) class Meta: model = Tag fields = ("name", "usage_count") What I want to achieve now is that once usage_count is 0, i.e. a Tag is no longer related to any Record, it is automatically deleted. The only reliable approach I could come up with is a cronjob that checks for Tags with such criteria and deletes them, as neither casecades nor any sort of delete "hooks" seem to do the trick. Is there a way to achieve this with an approach that is more elegant than a cronjob? -
How to use profile fields in comment form?
I to make my comment form login required and for that i had to use the fields in another models.py how can i use fields without foreignkey? models.py in blog app: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments', blank=True, null=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) class Meta: ordering = ('created',) def __str__(self): return f'نظر توسط {self.user} در {self.post}' models.py in account app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعهدهنده'), ('designer', 'طراح پروژه'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True) def __str__(self): return f'profile for user {self.user.username}' i want to use user full name and picture in comment template and with foreignkey I could not template: <div id="post_comments"> <h4>نظرات</h4> <div class="comment"> {% for comment in comments %} <div class="row"> <figure class="col-sm-2 col-md-2"> <img width="90" height="90" class="img-circle" src="{{ comment.user.photo }}" alt="عکس کاربر"> </figure> <div class="col-sm-10 col-md-10"> <div class="comment_name">{{ comment.user.user.get_full_name }}<a class="reply" href="#">&nbsp;</a> </div> <div class="comment_date"><i class="fa-time"></i>{{ comment.created }}</div> <div class="the_comment"> <p>{{ comment.body|linebreaks }}</p> </div> </div> </div> {% empty %} <h4>هیچ نظری وجود ندارد</h4> {% endfor %} </div> </div> is there any … -
How to reduce post method with two forms and two submit button?
I have two forms and two submbit buttons. Because I have a form submit for pdf and I have a submit for excel. So I distinguish in the views.py the forms like this: def post(self, request): filter_text = FilterText() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' content_excel= '' if request.POST.get('form_pdf') is not None: if submitted_form.is_valid() and request.POST: uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) if request.POST.get('form_excel') is not None: if submitted_form.is_valid() and request.POST: uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content_excel = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content_excel = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content_excel": content_excel }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) But as you can see this are almost identical code. Question: how can I reduce this? -
Assistance needed Django Rest Framework Serializer
I am new to the Django Rest Framework. I am attempting to get the navSidebarMaps object to serialize as follows: [ "navSidebarName": "mainSidebar", [ { "id": 1, "name": "item1", "order": 1, }, { "id": 2, "name": "item2", "order": 2, } ] ] What is the recommended approach for pulling the list of navSidebarItems through to the navSidebarMaps? The related_name argument seems to get me part way to the goal. However, I've missed something. Models: class navSidebars(models.Model): name = models.CharField(max_length=50, blank=False, null=False) description = models.CharField(max_length=150, blank=False, null=False) class navSidebarItems(models.Model): name = models.CharField(max_length=50, blank=False, null=False) description = models.CharField(max_length=150, blank=False, null=False) class navSidebarMaps(models.Model): fk_navsidebar = models.ForeignKey('core.navSidebars', related_name='sidebars', on_delete=models.CASCADE) fk_navsidebar_items = models.ForeignKey('core.navSidebarItems', related_name='sidebar_items', on_delete=models.CASCADE) order = models.IntegerField(default=0, blank=False, null=False) Serializers: class navSidebarSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebars fields = [ 'id', 'name', 'description', 'active', 'visible', 'enabled', 'can_delete', 'fk_navsidebar', 'created_by', 'created_when', 'modified_by', 'modified_when' ] class navSidebarItemsSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebarItems fields = [ 'id', 'name', 'description', 'position', 'active', 'visible', 'enabled', 'can_delete', 'created_by', 'created_when', 'modified_by', 'modified_when' ] class navSidebarMapsSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = navSidebarMaps fields = [ 'id', 'fk_navsidebar', 'fk_navsidebar_items', 'created_by', 'created_when', 'modified_by', 'modified_when' ] -
Django test to use Postgres extension without migration
I have an existing project that I want to start implementing test step. There are quite a few data migrations happened in the history and I don't want to spend the effort to make them run in test setup. So I have disabled 'migrations': DATABASES['default']['TEST'] = { 'MIGRATE': False, } However this Postgres DB makes use of some extensions class Meta: verbose_name = 'PriceBook Cache' verbose_name_plural = 'PriceBook Caches' indexes = [ GinIndex( name="pricebookcache_gin_trgm_idx", fields=['itemid', 'itemdescription', 'manufacturerpartnumber', 'vendor_id'], opclasses=['gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops', 'gin_trgm_ops'] ), ] Which resulted error when I run the test psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" I have had a look at here https://docs.djangoproject.com/en/4.1/ref/databases/#migration-operation-for-adding-extensions which specifically said done via migration but which I have disabled. An alternative is using template db but I don't really want to as this will be run automatically in gitlab using docker container and I don't want to maintain another fixture outside the project repo. So is there a way to initialise the database without running the migrations or is it possible to make it run completely different migration just for the test? -
The view main.views.view didn't return an HttpResponse object. It returned None instead
I have two forms on the same template. And that is why I check if one form has the name form_pdf: def post(self, request): extract_instance = ExtractingTextFromFile() filter_text = FilterText() extract_excel_instance = ExtractingTextFromExcel() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(request.POST, request.FILES) content = '' if 'form_pdf' in request.method == 'POST': if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/controle_punt140.html", { "form": submitted_form, }) and template: <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_pdf" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_pdf" class="btn btn-warning"> Upload! </button> </div> </form> <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data" id="form_excel" > <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" class="btn btn-warning"> Upload! </button> </div> </form> But if I run this I get this error: The view main.views.view didn't return an HttpResponse object. It returned None instead. But I googled that error of course. And the suggestion is that you have to return render. But I have that. So how to tackle this error? -
Why does my Django form data not appear in the database?
I try to develop a simple input form to save a deposit for a fishing vessel. The vessel and the net are tables in the database. There is no error when the form is submitted but there is nothing happening in the background. I use a PostgreSQL database with PgAdmin for insights.I am a little bit stuck since it's my first time working with Django. I tried adding the dep_id field into the form but it did not change anything. forms.py models.py views.py Maybe I have any kind of dependency wrong or is it a problem with a key? -
send file to django rest with ajax
In my project, I use ajax to send form data to back-end(django rest framework). but when I see the request.data, the image field is empty. but other fields are ok. js(img is file input): $.ajax({ method: 'POST', url: '/step5/send/', contentType: 'application/json', data: JSON.stringify({"date": date, "hour": time, "price": price, "document": img, "id": {{user.id}} }), success: function (res) { console.log(res); }, error: function (err) { console.log(err); } }); view: @api_view(["POST"]) def step5_get_pay(request): date = request.data.get("date") hour = request.data.get("hour") price = request.data.get("price") document = request.data.get('document') id_ = request.data.get("id") user = User.objects.get(id=id_) Step5.objects.create(date=date, hour=hour, price=price, document=document, user=user) data = { "data": request.data, } return Response(data=data, status=200) and data: {date: '1401-11-14', hour: '10:10:10', price: '500', document: {…}, id: 1} Document is in request.data but I think It's must in request.FILES and in model that's save {} (empty) enter image description here enter image description here send a form with file input with ajax and django rest