Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - rendering templates and passing them via AJAX
Ok, so this a more of a conceptual question. Basically i just found out i can do the following: Use ajax to start a function that returns a rendered HTML template, send that as a response to ajax, then apply that HTML code to a host div. This feel so much more versatile and powerfull than using include tags. I can render, and re-render forms (or any little snippet of HTML) in a flash with minimal JS, and, most importantly without refreshing the page. I understand that passing whole html blocks via AJAX might not be optimal, so i am avoiding abusing this. However this feels "hacky" to me, so my question is, Why should i NOT do this? if you want some example code: {% load crispy_forms_tags %} {% load static %} <div id="formdiv1"> </div> <script> function getform_rec() { $.ajax({ type: "GET", url: "/backoffice/ajax/rec_form/", success: function(data) { $("#formdiv1").html(data); } }); } getform_rec() </script> and my view def ajax_rec_form(request): if request.method == "GET": rec_id = request.GET.get("id", None) if not rec_id: form = Rec_form() else: form = Rec_form(instance=Rec.objects.get(id=rec_id)) return render(request, "rec-form.html", {"rec_id": rec_id, "form": form}) rec-form.html is just a html file with no extends or includes, and it just renders the … -
Is there a way i can join two tables and get the sum of duplicated field in Django
I have a model WarehouseTrade Account and WarehouseStorage Account it look like this:------- class WarehouseStorageAccount(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES) bags = models.IntegerField(default=0) gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) updated = models.DateTimeField(auto_now=True) class WarehouseTradeAccount(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES) bags = models.IntegerField(default=0) gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) updated = models.DateTimeField(auto_now=True) I am trying to get All the data in both accounts, but it should sum it up if there is a duplicate between the two. I have been able to achieve this with SQL using below code: SELECT data.warehouse_id AS Warehouse, data.item_id AS Item, data.grade AS Grade, SUM((data.net_weight)) AS Net_WEIGHT, SUM((data.gross_weight)) AS Gross_WEIGHT, SUM((data.bags)) AS Bags FROM (SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags FROM public.inventory_warehousestorageaccount UNION ALL SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags FROM public.inventory_warehousetradeaccount ) data GROUP BY data.warehouse_id, data.item_id, data.grade I tried using union to join the two tables, then get the aggregate the result, but I keep getting an error wt = WarehouseTradeAccount.objects.all() ws = WarehouseStorageAccount.objects.all() w=wt.union(ws) w.aggreate(new_net_weight=Sum('net_weight') How do I replicate this in Django? -
Write in database on exception
I have the following code, if the try catch statement executed successfully then I write in my database model success = True and if the code Excepts then I want to write success = False. In purpose I raise the exception in order to test my except statement. The code goes successfully in the except statement because I get the print, but it does not write in my database. try: ...do some work... models.SyncRun(success=True).save() raise Exception except Exception as e: print("in") models.SuncRun(success=False).save() raise Exception -
Django: access model instances
I have a model called OrderItems class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) and a model called Order class Order(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) Now in my views.py i have an OrderItem model order instance. And in my Order model i need to set its order instance to complete. Im trying something as follows. orderID=OrderItem.objects.values('order').filter(order_id=4) #lets say there are more than one order_id with the value of 4 for order in orderID: order = Order.objects.get(id=orderID) order.complete=True order.save() this code gives me ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. How to fix this? Thanks in advance -
Is it an antipattern to make queries from models?
Django says the Models should be used as an Active Record and include persistence and business logic. What to do when the business logic requires access to unrelated models? Is it an antipattern to make queries from model instances? I see the queries are made from views and it is assumed that all dependencies of a model are covered by its database fields. -
Django static files works when site is accessed vai `appname.heroku.com` but not found when site is accessed via custom domain (www.exmple.com)
here are important debug values on settings.py site is hosted on heroku.com and DNS from namecheap STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') STATIC_URL = '/static/' 'whitenoise.middleware.WhiteNoiseMiddleware', STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' -
Django + HTML: Why does my if condition in my template fail even thought I havent submitted interest?
Django + HTML: Why does my if condition in my template fail even thought I havent submitted interest? As you can see from my views.py i have already indicated that if you have submitted interest, you will get the message that you have submitted the interest, otherwise the button 'submit interest' will be shown. Why does it not work then? views.py def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['liked'] = liked context['blog_post'] = blog_post context['total_likes'] = total_likes account = Account.objects.all() context['account'] = account #when post does not belong to me if blog_post.author != request.user: submittedinterest = False if blog_post.author.interestsender.filter(id=request.user.id).exists(): submittedinterest = True context['submittedinterest'] = submittedinterest #when the post belongs to me else: pass return render(request, 'HomeFeed/detail_blog.html', context) template {% if submittedinterest %} <a href="{% url 'HomeFeed:submitinterest' blog_post.slug %}"><button type="button" class="btn btn-warning">Collaborate!</button></a> {% else %} <div class="alert alert-success" role="alert"> <p class="text-center">You have submitted your interest.</p> </div> {% endif %} models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class … -
how to display fields from other table that has onetoone relation using serializers in django
I have two models class Rule(models.Model): pmdruleid = models.BigIntegerField(primary_key=True) effectivedate = models.DateTimeField(blank=True, null=True) retireddate = models.DateTimeField(blank=True, null=True) createdby = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'rule' class Ruledefinitions(models.Model): ruleactivestatus = models.CharField(max_length=14) rulename = models.CharField(max_length=255, blank=True, null=True) pmdclinicalruleid = models.OneToOneField(Rule, models.DO_NOTHING, db_column='pmdclinicalruleid', primary_key=True) pmdclinicalvariableid = models.IntegerField() class Meta: managed = False db_table = 'ruledefinitions' unique_together = (('pmdclinicalruleid', 'pmdclinicalvariableid'),) Corresponding serializers for the above models class RuleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Rule fields = ['pmdruleid', 'effectivedate', 'retireddate', 'createdby'] class RuledefinitionsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Ruledefinitions fields = ['ruleactivestatus', 'rulename', 'pmdclinicalruleid', 'direction', 'pmdclinicalvariableid'] Views for Rules model class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Rule.objects.select_related('ruledefinitions').all() serializer_class = RuleSerializer When i call this view class, i am getting fields of only rule model in api response. I would also need to add the fields of ruledefinitions model fields (since both are connected by onetoone relationship) in the api response. Help me in snippet for displaying the ruledefinitions model fields in api response. I am new to django -
Django looking for wrong path on url() in css files
I am trying to set up a personal blog that uses Django and is hosted in Heroku. You can check it here: https://generic-blog.herokuapp.com/ All my static files were loading as intended on my local machine until I decided to store the static files on AWS S3. I configured my settings.py to use S3 and did python manage.py collectstatic to collect the static files to my s3 bucket. The static files are loading as intended, but on my css files there are url() with relative paths as this one: url("../fonts/blog.woff") format("woff") Which is not loading, as the path is incorrect. My browser's console gives me the following error: downloadable font: download failed (font-family: "blog" style:normal weight:400 stretch:100 src index:1): status=2147746065 source: https://personal-django-blogs.s3.amazonaws.com/fonts/blog.woff The path that Django tries to search for the font is wrong https://personal-django-blogs.s3.amazonaws.com/fonts/blog.woff would have to be https://personal-django-blogs.s3-sa-east-1.amazonaws.com/static_root/vendor/font-awesome/fonts/fontawesome-webfont.woff I could just replace each relative path with the absolute path of the file in s3 bucket, but this feels wrong. I think the problem lies in settings.py, but I couldn't manage to understand why when working on s3 the relative paths don't work anymore. Here's my settings.py relevant configurations: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] # … -
how to split a for loop in django
I want have a simple model for images. there is a option to upload unlimited images. but I want don't want them to be shown under each other. for instance just show the first 5 images then some text and then again another 5. right now my code is like this: {% for img in images %} <img src="{{ img.images.url }}" class="img-fluid" alt=""> {% endfor %} I want the Structure to be like this: for loop for img0 to 5, then everything elese, then another for loop for img6 to 10, Thanks for the solutions and apologies for my bad English -
Creating automatic datetime in django
I would like to create a field with a predefined datetime. Something like this: class MyExample(models.Model): expiration = timezone.now() + timedelta(days=1) expiration_date = models.DateTimeField(verbose_name="Expirate in", default=expiration) ... I don't know if it's the best way, because when there are new migrations there is an update of the table with the expiration. Does anyone have any tips? -
Get values in real time in Django
I have made a sketch of how my project should look like. The user can communiticate with a virtual assistant over the web browser. The backend is Django. How to get values from the database in real time in Django? I've heard about Rest API, but I am not sure if that is the right thing to do. It is possible to use queries like website.com/?variable=value, but that is NOT what I want, because that slows down the time to "update" the user's screen and speakers. The frontend and backend is Django. The user should be able to communicate with Morpheus (there are other characters as well) when the "conversate" button is clicked. -
How can I display all fields from a Many-to-Many Model in Django Admin
I have the following Models: class ModelA(models.Model): some_field_A = models.CharField() some_other_field_A = models.CharField() class ModelB(models.Model): some_field_B = models.CharField() many_to_many_relation = models.ManyToManyField(ModelA) In admin.py I am using filter_horizontal to edit the ManyToManyField: class ModelB(admin.ModelAdmin): model = ModelB filter_horizontal = ('many_to_many_relation',) but it shows only some_field_A and I want it to show both fields from ModelA, because the entries in ModelA are unique depending on both fields and as you can see from the picture there are multiple entries with the same value (i.e. some_field_A = EUV) but they have different values for some_other_field_A: -
Celery 5.0.4 with Django 3.1.4 - OperationalError: Error 101 connecting to localhost:6379. Network is unreachable
I am having an issue with Django and Celery integration whereby it seems the settings for the RESULT_BACKEND and BROKER_URL keys are not being honored. I am running Django and Celery successfully in Docker with django-celery-beat without issue. Scheuduled tasks are running as expected. The issue I am having is when calling a @task function through a Django Signal. When this runs (triggered from Django Rest Framework); I get the following error: OperationalError: Error 101 connecting to localhost:6379. Network is unreachable. This would be expected because I dont run redis locally but within another container. Any ideas on why the configuration is not being used? I have confirmed that the environment variables are being loaded correctly and seen by both celery and Django. Compose File app-redis-prod: image: redis:alpine app-worker-prod: environment: - PLATFORM=prod - CERT_DIR=/run/certificates - DB_SSL_MODE=require - BROKER_URL=redis://rocx-redis-prod:6379 - RESULT_BACKEND=redis://rocx-redis-prod:6379 settings.py CELERY_BROKER_URL = os.environ.get('BROKER_URL', 'redis://localhost:6379') CELERY_RESULT_BACKEND = os.environ.get('RESULT_BACKEND', 'redis://localhost:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True celery.py app = Celery('MYAPP') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f"Request {self.request!r}") Any ideas would be greatly appreciated! -
PyCharm complains template not found if template path is given in render function
PyCharm error inspection complains template not found error in django project if the template path is given as string in render function. It does not show error if the path is stored as variable before and that variable is passed in render. In any ways the site works correctly. Project Structure is configured correctly, TEMPLATE_DIRS, TEMPLATE_LOADERS in settings.py also configured. -
Why can't I clear or change field on inline formset, but I can only add, after clicking submit button?
I am new to Django and I am trying to create a view that uses a form with fields, another form with an image and file field, and a third inline formset form with two fields that uploads an image and video with the option to add more after submit, all in the same view. The problem I am currently experiencing is that I am able to add videos to my inline formset, but I am not able to clear or change those fields and I would like to know if it is my view that is causing it. Thanks! View: def edit(request, id): all_objects = get_object_or_404(Profile, id=id) ProfileFormset = inlineformset_factory(Profile, MultipleFileUpload, fields=('image', 'video',), extra=1) if request.method == 'POST': form1 = EditProfile(request.POST or None, instance=all_objects) form2 = ProfileUpdateForm(request.POST, request.FILES, instance=all_objects) formset = ProfileFormset(request.POST, request.FILES, instance=all_objects) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() formset.save() return HttpResponseRedirect(".") form1 = EditProfile(instance=all_objects) form2 = ProfileUpdateForm(instance=all_objects) formset = ProfileFormset(instance=all_objects) context = { 'form1': form1, 'form2': form2, 'formset': formset } return render(request, 'accounts/edit.html', context)``` -
why does Materialize not work on Django native server?
I made a materialize registration form and it works outside of the Django project but as soon as I run it on the Django web-server it does not work. Additional info - I am using bootstrap elsewhere in the project, I don't know if that interferes with thought would let you know. If you need any more details please let me know, and this is only my 2nd ever question so if I do anything wrong please correct me :) -
I cannot access the admin page
when I started the local server for django framework project and wanted to enter the admin page, I got this error: **TypeError at /admin/ Cannot mix str and non-str arguments Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: Cannot mix str and non-str arguments Exception Location: C:\Program Files\Python39\lib\urllib\parse.py, line 122, in _coerce_args Python Executable: C:\Program Files\Python39\python.exe Python Version: 3.9.1** -
Foreign Key value assigning in Django
I am working on a project in Django where two custom build user model is used. Industry Employee Here every Industry user will entry some of their Employee's data, and later on Employee will verify and finish to create his account. my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Inspector = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) is_Admin = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) class Employee(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user', blank=True) #industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry') industry = models.ForeignKey(Industry, on_delete=models.CASCADE) i_id = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail = models.EmailField(null=True, blank=False, unique=True) rank = models.CharField(max_length=20, blank=False, null=True) employee_varified = models.BooleanField(default=False, blank=True) Now I wrote the following code in views.py to create an Employee's entry by Industry user when the Industry user signed in from their account: @method_decorator(industry_required, name='dispatch') class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inserted_text'] = "inserted text from EmployeeDetails of views.py" return context def employeeRegister_byIndustry(request): employeeRegister_dict={ 'insert_me' : "hello … -
How to Integrate Django WEB Application with Microsoft Azure For Authentication
I have developed a web application based on Django Framework, but i want my application to get authenticated by Azure Single Sign on, Please suggest the method or tutorials to achieve this -
How is the correct way to send a json serializer
I am practicing with serializers and I find an error because I want to send json from my queryset and the error it generates is context must be a dict rather than JsonResponse, I read the documentation and it says that setting the safe parameter to false allows sending any object serializer: This is my view: class TypeTaskListView(ListView): template_name = 'tasks/type_task.html' queryset = TypeTask.objects.all().order_by('-pk') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) data = serializers.serialize('json', context['object_list']) return JsonResponse(data, safe=False) -
How to use multi-tenant functionality in django
Im trying to create a project that should have multi-tenancy ability but i want it a bit customized. So here is my whole schema I want an organization to signup whenever someone lands on my main site, they will be given a landing page (handled in view, no worries about this) eg: www.test.com (this will be my public url) Lets say company puts the name "abc" in form and signs up for my site. Now I want to create a tenant like abc.test.com (tenant url) and also database (postgres) should have an organization table in public schema and an abc table in private schema This is my main goal of the project. Now I have achieved most of it. DB schemas are handled and everything is done by using django-tenants package by tomturner. What I cant achieve is the functionality to differenciate automatically between my public and private urls. Like if someone hits "www.test.com" should land on my main site if someone hits "abc.test.com" should land on my private urls. I know I have to write a middleware for this (which is given in django-tenants) but still im not able to achieve it. By the way im following https://github.com/django-tenants/django-tenants/tree/master/examples/tenant_multi_types/tenant_multi_types_tutorial this … -
django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading Django
I've tried this solution but I am getting Segmentation fault: 11 when migrating in Django. When I remove PYTHON_CONFIGURE_OPTS when installing Python, I am getting this error. django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading -
Django-rest-auth urls Page not found
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # drf, rest_auth, allauth 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', # apps 'board_subject_restful', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } SITE_ID = 1 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', include('board_subject_restful.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] When attempting to connect to rest-auth/ url, the following error occurs. *api-auth/ rest-auth/registration/ The same error also occurred. enter image description here -
Handling JWT Authentication for Soft Deleted Users in Django Rest Framework
I'm trying to make a username available once a user deletes their account. By default the username is unique meaning the username won't be available even after the account is soft deleted. This is, by default, the setup that comes with django out of the box. class CustomUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_active is used here to mark a model as deleted. So that I can be able to take advantage of UniqueConstraint and add a condition, I have to drop the uniqueness of the username. class CustomUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=False, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[UnicodeUsernameValidator()], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) class Meta: constraints = [ models.UniqueConstraint( fields=['username'], name='active_username_constraint', condition=models.Q(is_active=True) ) ] This …