Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
STATIC_ROOT in Django not working correctly
Trying to get static root set properly, Went through the tango with Django tutorial and stuck on this part. Basically this is my setting files, and the static folder is linked below in the tree. C:. ββββmedia β ββββlocations β ββββ2018 β ββββ11 β ββββ11 β ββββ20 β ββββ18 ββββSpace β ββββ__pycache__ ββββSpaces β ββββmigrations β β ββββ__pycache__ β ββββ__pycache__ ββββstatic β ββββadmin β β ββββcss β β β ββββvendor β β β ββββselect2 β β ββββfonts β β ββββimg β β β ββββgis β β ββββjs β β ββββadmin β β ββββvendor β β ββββjquery β β ββββselect2 β β β ββββi18n β β ββββxregexp β ββββcss β ββββimages β ββββparralax β ββββhome ββββtemplates β ββββregistration β ββββSpaces ββββusers ββββmigrations β ββββ__pycache__ ββββ__pycache__ and below you can see the settings i'm using for this . """ Django settings for Space project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Quick-start development settings - β¦ -
Multiple Queries For Inline instances Django admin
I have created a custom Admin for one of my model. And added a Relational table as one of its inline. 1). Now the thing is that Inline has over a 100 rows. And the inline further has a foreign key object to some other model. 2).Whenever i load the model form it takes a whole lot of time to Load. 3).I debugged and checked the code and number of queries. No query was duplicated and the count was nominal. 4).I have overridden the query set for the inline instance to prefetch its foreign key instance. 5).I went on and raised a random validation error in the formset's clean. 6).What i found out that when the error was raised it had a different query for every inline instance. Say if it has a 100 rows then the query was duplicated 100 times for that inline. 7).Is there any way to prefetch or optimize this scenario as its causing way too lag in my application Please help -
How to create an inline formset with manytomany relation in Django
I want to create an inline formset between Preorder model and Product model. The scenario is that the user will be able to select one or more than one products when he decides to create a preorder. On the other hand a product might be found in one or more than one preorders. With that in mind i created a manytomany relationship. models.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'Client') invoice_date = models.DateField("Invoice date",null=True, blank=True, default=datetime.date.today) preorder_has_products = models.ManyToManyField(Product, blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) class Product(models.Model): name = models.CharField("Name",max_length=200) price = models.DecimalField("Price", max_digits=7, decimal_places=2, default=0) barcode = models.CharField(max_length=16, blank=True, default="") eopyy = models.CharField("Code eoppy",max_length=10, blank=True, default="") fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Fpa Scale') forms.py class PreorderForm(ModelForm): class Meta: model = Preorder exclude = ('client','preorder_has_products',) def __init__(self, *args, **kwargs): super(PreorderForm, self).__init__(*args,**kwargs) self.fields['invoice_date'].widget = MyDateInput(attrs={'class':'date'}) class ProductForm(ModelForm): #name = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete')) class Meta: model=Product fields = '__all__' def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['name'].label="Name" self.fields['price'].label="Price" and finally the inline formset: PreorderProductFormSet = inlineformset_factory(Preorder, Product, form=ProductForm, extra=1) After run I face up the issue:ValueError at / 'intranet.Product' has no ForeignKey to 'intranet.Preorder' Why this happening since I created a manytomany relation? One solution is to create a foreign key relationship between Preorder and β¦ -
how to make a list of posts titles in django
I am creating a blog web app with django where i want to make a list which contains only titles of the posts. i wanna make two lists namely Latest posts All posts In Latest posts , i wanna list out titles of the posts created recently.Means post created at last should be in first place of the list. simple In All Posts , i want to list out titles of all posts in ascending order. Here is my code goes..... views.py from django.shortcuts import render , redirect from django.views.generic import TemplateView , ListView , DetailView from .models import home_blog_model from .forms import create_post class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" def detail_view(request , pk): obj = home_blog_model.objects.get(id=pk) context = {"obj":obj} return render(request , "detail.html" , context) def create_post_view(request): if request.method == "POST": form = create_post(request.POST) if form.is_valid(): form.save() return redirect("/home/") else: form = create_post() return render(request , "create_post.html" , {"form":form}) home.html {% extends "base.html" %} {% load static %} {% block body %} <img src="{% static 'hori.jpg' %}" style="margin-top: 50px;margin-left: 250px;width: 60%"> <div class="row" style="margin-top: 40px;margin-left: 320px;margin-right: 20px"> {% for post in posts %} <div class="col-sm-6 mb-4"> <div class="container" style="width: 300px;box-shadow: 0 4px 8px 0 β¦ -
Elasticsearch in Django - sort alphabetically
I have a following doc: @brand.doc_type class BrandDocument(DocType): class Meta: model = Brand id = IntegerField() name = StringField( fields={ 'raw': { 'type': 'keyword', 'fielddata': True, } }, ) lookup_name = StringField( fields={ 'raw': { 'type': 'string', } }, ) and I try to make a lookup using this: BrandDocument.search().sort({ 'name.keyword': order, }) The problem is that I'm getting results sorted in a case sensitive way, which means that instead of 'a', 'A', 'ab', 'AB' I get 'A', 'AB', 'a', 'ab'. How can this be fixed? -
React + Django form input with images and text
I want to have a 'post' model in Django that contains both images and text in the body of the post, but I am not sure how I should go about it. On the frontend React side, I'd like to have a content input form (along with title, etc.) that would allow users to type the text they want, and then insert photos to upload at any spot they choose in the text. On the backend Django side, I'd like the images to go to s3, but that seems like an issue I can work out once the actual uploading POSTing to the db is functional. Can I use a JSON field for the content from from django.contrib.postgres.fields import JSONField Would the json field be able to handle text interrupted by image urls? What would my frontend axios post request look like? The only other option I saw was wagtail with their StreamField, but if possible I'd like to avoid using a content management system. I'm open to any ideas at this point! -
Check pdf is valid or not from Django InMemoryUploadedFile
I am uploading the pdf file to s3 storage. Before uploading it to s3 storage I need to check if pdf is valid or not. I searched a lot but haven't found any workaround. -
Django - login_required doesn't update URL
I'm currently facing issues using @login_required django decorator. Indeed, using @login_required correctly redirect to the page I want, but didn't update the URL. I've requested login to access 'http://127.0.0.1:8000/global_results/by_module/' @login_required def results_by_module(request): ... When I'm going to this page without logging in, the page I see is the correct one (login), but the URL is not updated (still http://127.0.0.1:8000/global_results/by_module/) whereas I see the correct redirection into django logs : [20/Nov/2018 11:41:08] "GET /global_results/by_module/ HTTP/1.1" 302 0 [20/Nov/2018 11:41:08] "GET /accounts/login/?next=/global_results/by_module/ HTTP/1.1" 200 2055 When I refresh the page, I can see the 'correct' url http://127.0.0.1:8000/accounts/login/?next=/global_results/by_module/ What am I doing wrong ? I tried to use def results_by_module(request): if not request.user.is_authenticated: return redirect('accounts/login/?next=%s' % request.path) or def results_by_module(request): if not request.user.is_authenticated: return HttpResponseRedirect('accounts/login/?next=%s' % request.path) with always the same behaviour. Thanks in advanced for your help. -
RestFul API endpoints with Django Rest Framework Class based views
I have the following 4 class based views in DRF to perform CRUD operation on a model called Trips. from rest_framework import generics class TripCreateView(CreateAPIView): #code that creates a Trip class TripListView(ListAPIView): #code that lists Trips class TripDetailView(RetrieveAPIView): #code that gives details of a Trip class TripUpdateView(UpdateAPIView): #code that updates a particular trip details class TripDeleteView(DestroyAPIView): #code that deletes an instance Now in-order to wire up the urls to each view, my urls.py looks like this: urlpatterns = [ url(r'^trip/$', TripCreateView.as_view()), url(r'^trip/list/$',TripListView.as_view()), url(r'^trip/(?P<pk>[0-9]+)/detail/$', TripDetailView.as_view()), url(r'^trip/(?P<pk>[0-9]+)/update/$', TripUpdateView.as_view()), url(r'^trip/(?P<pk>[0-9]+)/delete/$', TripDeleteView.as_view()) ] This works as expected.However, as is evident, those API endpoints are poorly designed since the URI has the http method as well in it. RESTFUL API endpoints don't have the HTTP method in the URI as look like this: Endpoint HTTP METHOD Result trips GET Gets all Trips trips/:id GET Gets details of a Trip trips POST Creates a Trip trips/:id PUT Updates a Trip trips:/id DELETE Deletes a Trip I know Viewsets can help achieve this but I can't use them because of certain other restrictions.Can this be achieved just by using class based views that I am using ? -
check pdf is valid or not breaks s3 bucket file upload
I am uploading pdf file to s3 bucket. Before uploading i am checking if pdf is valid or not. cv_file = request.FILES['cv'] request.FILES['cv_new'] = request.FILES['cv'] temp_file = request.FILES['cv_new'] try: sg = PyPDF2.PdfFileReader(BytesIO(temp_file.read()), 'rb') except: pass It's working but when file get's uploaded to s3 bucket it's size is 0kb and not valid. Upload to s3 bucket def upload_cv_on_s3(file, full_name): s3 = boto3.client('s3') s3_response = s3.put_object(Body=BytesIO(file.read()), Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key='carriculum_vitaes/' + full_name) return s3_response I am not sure what wrong I am doing. Somehow PdfFileReader is changing the file content or BytesIO issue may be. File is getting uploaded fine without below line sg = PyPDF2.PdfFileReader(BytesIO(temp_file.read()), 'rb') -
Graphene Django - Mutation with one to many relation foreign key
I would like to know how to properly create mutation for creating this django model: class Company(models.Model): class Meta: db_table = 'companies' app_label = 'core' default_permissions = () name = models.CharField(unique=True, max_length=50, null=False) email = models.EmailField(unique=True, null=False) phone_number = models.CharField(max_length=13, null=True) address = models.TextField(max_length=100, null=False) crn = models.CharField(max_length=20, null=False) tax = models.CharField(max_length=20, null=False) parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE) currency = models.ForeignKey(Currency, null=False, on_delete=models.CASCADE) country = models.ForeignKey(Country, null=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) As you see, there are three Foreign keys. For model Currency, Country and Parent(self). Company DjangoObjectType looks very simple like this: class CompanyType(DjangoObjectType): class Meta: model = Company And finally my mutation class CreateCompany have Currency, Country and Self(Parent) defined like graphene.Field(): class CompanyInput(graphene.InputObjectType): name = graphene.String(required=True) email = graphene.String(required=True) address = graphene.String(required=True) crn = graphene.String(required=True) tax = graphene.String(required=True) currency = graphene.Field(CurrencyType) country = graphene.Field(CountryType) parent = graphene.Field(CompanyType) phone_number = graphene.String() class CreateCompany(graphene.Mutation): company = graphene.Field(CompanyType) class Arguments: company_data = CompanyInput(required=True) @staticmethod def mutate(root, info, company_data): company = Company.objects.create(**company_data) return CreateCompany(company=company) When i want to start django server, Assertion error will be raised. AssertionError: CompanyInput.currency field type must be Input Type but got: CurrencyType. I was finding some good tutorial for one to many foreign key β¦ -
Background Image won't show with Django
<div class="full-screen force-full-screen" style="background: url('{% static 'images/parallax/home/9.jpg' %}') center center no-repeat; background-size: cover;"> Above code won't show the image I have as a background. Really unsure how to fix this issue. Please help :) Cheers! -
How do I prevent orders from being displayed repeatedly on the checkout screen when selecting multiple times
For my store, I basically have a quantity box with an add item option. When I select the quantity and click on the add item, the order gets added to my list of orders and it is displayed on checkout. However, Suppose I Select Order A for the first time and set quantity as 5. The second time, I selected Order A again and set quantity as 3, I want it to add to the previous order and display quantity as 8. However, in case of my code, it displays it as separate orders. How do I solve this issue? def addItem(request): selected_supply = Supply.objects.get(pk=request.POST['supplyID']) qty = request.POST['qty'] try: current_order = Order.objects.filter(owner=1).get(status="pre- place") except Order.DoesNotExist: current_order = Order.objects.create(owner=Manager.objects.get(pk=1), status="pre-place") order_detail = OrderDetail.objects.create(orderID=current_order, supplyID=selected_supply, quantity=qty) return HttpResponseRedirect(reverse('Store:browse')) -
Wagtail Custom Image Tag
Is there anyone knows how one can create a custom image tag that add a text to the rendition in Wagtail? I couldn't see anything on this in the document. tnx -
Django cassandra search engine
Anyone tried integrating any search engines such as elasticsearch or solr integrated with Cassandra using django haystack, please suggest if you tried any for your Django Cassandra project. -
How to pass more than two parameters in a queryset in Django?
I hope my question is understood For example, I have this model class Area(models.Model): area_id = models.IntegerField() name = models.CharField() last_name = models.CharField() short_name = models.CharField() I want to make a query with several parameters If I do not find the first one, look for it for the second and so with the third filter_areas = Area.objects.filter(area_id=3 | name='area_name' | short_name='are') Like to an or | -
Django ORM join many to many relation in one query
If we have 2 models A, B with a many to many relation. I want to obtain a sql query similar to this: SELECT * FROM a JOIN ab_relation ON ab_relation.a_id = a.id JOIN b ON ab_relation.b_id = b.id; So in django when I try: A.objects.prefetch_related('bees') I get 2 queries similar to: SELECT * FROM a; SELECT ab_relation.a_id AS prefetch_related_val_a_id, b.* FROM b JOIN ab_relation ON b.id = ab_relation.b_id WHERE ab_relation.a_id IN (123, 456... list of all a.id); Given that A and B have moderately big tables, I find the way django does it too slow for my needs. -
Execute a raw query to create object in Django
I have a Table which not defined as a Model in Django server. So I need to use raw query to create object in Database My Database: Table name: msg_rooms I want to create object { with_user: 5, room_name: 'abc', user_id: 2 } by using raw query in Django. Please help me! -
type object 'ContentType' has no attribute 'objects'
I am using djangae with some third party applications like all-auth, django-invitations and django rest framework. When I hit python manage.py migrate I get the following error. AttributeError: type object 'ContentType' has no attribute 'objects' The full trace is following Traceback (most recent call last): File "manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "/home/salman/Workspace/chaipani/lib/djangae/core/management/__init__.py", line 43, in execute_from_command_line return _execute_from_command_line(djangae_namespace.sandbox, argv, parser=djangae_parser, **overrides) File "/home/salman/Workspace/chaipani/lib/djangae/core/management/__init__.py", line 68, in _execute_from_command_line return django_management.execute_from_command_line(argv) File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/salman/Workspace/chaipani/lib-vendor/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/home/salman/Workspace/chaipani/lib-vendor/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/home/salman/Workspace/chaipani/lib-vendor/django/contrib/auth/management/__init__.py", line 63, in create_permissions ctype = ContentType.objects.db_manager(using).get_for_model(klass) AttributeError: type object 'ContentType' has no attribute 'objects' My installed apps: INSTALLED_APPS = [ 'djangae', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'djangae.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djangae.contrib.security', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'invitations', ] Any help anyone? -
django: 2 button has to take user to diff. URL but code in single html and the tab swap is not working.
I'm doing a project in Django. in my home page, I have a login and signup button. I have a login.html page where both login and signup codes are done. when I press the login button it takes me to the login page and the login tab. when I press sign up button, it takes me to the login page, login tab instead of signup tab. I have added a variable signup on the login page which acts as a boolean value. I can't find a way where signup button takes to signup tab. The code is below: this is the code in index.html <nav id="nav-menu-container"> <button class="btn button-login"><a href="{% url 'login' %}" style="color:#fff;">Login </a></button> <button class="btn button-login"><a href="{% url 'signup' %}" style="color:#fff;">Sign-Up</a></button> </nav> Login Sign-Up login page: <div class="logmod"> <div class="logmod__wrapper"> <span class="logmod__close">Close</span> <div class="logmod__container"> <ul class="logmod__tabs"> <li data-tabtar="lgm-2"><a href="#">Login</a></li> <li data-tabtar="lgm-1"><a href="#">Sign Up</a></li> </ul> <div class="logmod__tab-wrapper"> <div class="logmod__tab lgm-1"> <div class="logmod__heading"> <span class="logmod__heading-subtitle">Enter your personal details <strong>to create an acount</strong></span> </div> <!-- Signup --> <div class="logmod__form" id="Signup"> <form method="post" action="#" id="Register" class="simform"> <div class="sminputs"> <div class="input full"> <label class="string optional" >First Name*</label> {{ signupform.first_name }} </div> <div class="input full"> <label class="string optional" >Last-Name*</label> {{ signupform.last_name }} </div> <div β¦ -
Django REST API in XML & JSON
How could I produce Django REST API in XML & JSON at the same time from same model I have a model. I need to create 2 api from that model , one in xml and one in JSON. -
boto3 : Dont allow presigned_url to show in browser
So, i have a python/Django rest framework for backend and react for frontend. For now i construct a presigned url in the backend and give that to the front in order to a show a video that i want. However, if i put the same url in the browser it plays as well, that i don't want. How can i let only my backend and frontend to be able to get that object? I have already tried to use cors configuration in m aws bucket but it doesn't do anything. I have read about cloudfront but i don't want to implement a new infrastructure for that, any ideas? Thank you! -
Saving Django Model with OneToOne Relationship Field returns Object has no attribute 'id' error
I have defined OneToOne Relationship in model b with model a. When i try to save model b i get "Model B : Object has no attribute 'id' " error. How to resolve this issue? What am i missing here. Models: class ModelA: datefield = models.DateTimeField(blank=True) amount = models.DecimalField(max_digits=12, decimal_places=2) status = models.CharField(max_length=20, default='ACTIVE') class Meta: db_table = "modela" class ModelB: rel = models.OneToOneField(ModelA, on_delete=models.CASCADE, primary_key=True) field1 ... class Meta: db_table = "modelb" Method to insert data into models: @transaction.atomic def methodToInsertData(args): new_modela = ModelA( "datefield" = "2018-11-05", "amount" = 5000, "status" = "ACTIVE" ) new_modela.save() new_modelb = ModelB( rel = new_modela, ... ) new_modelb.save() #This statement throws "object has no attribute id" error ModelA will auto create id as primary key but model B will not have id as primary key instead rel field would be the primary key with OneToOne relationship to Model A. Any suggestions to resolve this issue would be highly appreciated. -
django authorization in class-based view
I'm trying to restrict access of CRUD pages to the owners, but I can't find the class-based view equivalent of "if request.user != post.author raise Http404". Thx for your time. models.py class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) views.py class ArticleUpdateView(LoginRequiredMixin, UpdateView): model = Article fields = ['title', 'body'] template_name = 'article_edit.html' login_url = 'login' I tried the following (and many other combination arround those lines), but it isn't working. def get(self, request, *args, **kwargs): if self.request.user == self.obj.author: raise Http404() -
How to print post request data in django
In PHP when I send post request data from template form to controller I can use print_r($data) to print form send data for debugging purpose but in Django how can I print post request form data in view.py