Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement multi-page forms with separate models using function based view in Django
I am trying to create a multi-page form where each form get saved to a different model. An example of what I have in mind is the stackoverflow survey. I have read different post on this but most are either with multiple forms in one template or formset. I was able to do it using the form-tool package. As a newbie, I was hoping there might be a way to achieve this using function-based-view. Below is my implementation of the fool-tool package. Views.py class FormWizardView(SessionWizardView): template_name = "new_rental.html" form_list = [NewRentalPropertyForm, NewContractForm] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'images')) def done(self, form_list, **kwargs): rentalproperty_instance = RentalProperty() contract_instance = Contract() for form in form_list: rentalproperty_instance = construct_instance(form, rentalproperty_instance) contract_instance = construct_instance(form, contract_instance) rentalproperty_instance.save() contract_instance.rentalproperty = rentalproperty_instance contract_instance.save() return redirect('rental:home') urls.py path('new_rental/<int:pk>', FormWizardView.as_view(forms), name='new_rental'), Html Templates {% load i18n %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ … -
django circular import on urls
I have a simple django project structure is examp- exam polls templates exam was the name of the project and polls is the name of the first app I have the following code in exam/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')), ] and the following code in polls/urls.py from django.urls import path from views.polls import index urlpatterns = [ path('', views.index, name='index'), ] and i am getting the following error when i try to runserver The included URLconf module 'polls.urls from '/home/grr/Documents/examp/polls/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Conflict in form save() method when inherit from other save() method in Django
I changed the save method in the Django form.Then I inherited another save method from this method and made some changes to the child method ,that conflicted. I can't figure out how to fix the conflict so that my other uses of the parent method stay healthy and don't get spoiled. Forms.py class BaseModelForm(forms.ModelForm): def save(self, commit=True, **kwargs): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, 'created' if self.instance._state.adding else 'changed', ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save(user=kwargs.pop('user')) self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance class ChildForm(BaseModelForm): def save(self, commit=True, **kwargs): new_instance = super(ChildForm, self).save(commit=True) # Some other codes goes here! return new_instance Models.py class BaseFieldsModel(models.Model): def save(self, *args, **kwargs): user = kwargs.pop('user', None) if user: if self.pk is None: self.created_by = user self.updated_by = user super(BaseFieldsModel, self).save(*args, … -
Custom filter for django rest framework
I have a pair of Model and Filter ,and already make the filter work correctly. class MyText(models.Model): my_text = models.TextField(null=True) my_json = JSONField() class MyTextFilter(filters.FilterSet): my_text = filters.CharFilter(lookup_expr='contains') Then now ,I want to add the custom filter,which parse the json and check. like this below(this code is not correct) text_id = CustomFilter() def filter_text_id(self,obj): obj['id'] > 100: return obj; How can I make this??? -
How can I avoid "Using selector: EpollSelector" log message in Django?
I upgrade to Django 3.0, and I have been seeing this message in the logs printed to console. How can I avoid it? Using selector: EpollSelector -
How to change annotated month int in a dictionary into a month name?
I am new to Django framework, I have used annotation to sum up all the Amounts paid in a specific month in a year. This is working fine but the problem is that am unable to convert the month int into a month name in the template views.py def income_report(request): context = {} if grab_data_passed == 'monthly': daily_data=Income.objects.values('date__year', 'date__month')\ .annotate(amount=Sum('amount')) context['daily_data']=daily_data return render(request, 'reports/incomes_report_details.html', context) template {% for fo in daily_data %} <tr> <td>{{ fo.month }}</td> <td>{{ fo.amount }}</td> </tr> {% endfor %} How can change this annotated month into a month name in the templates. I know I have to first convert date__month back to month name in views before I pass it to the templates but how? -
Unable to run Django+MS-SQL with Ubuntu and Python3
I am setting up my django application on a linux server with apache as webserver. The project has ms-sql as its backend. To connect I have installed following packages: django-pyodbc==1.1.3 django-pyodbc-azure==2.1.0.0 django-mssql==1.8 pyodbc==4.0.26 sql-server.pyodbc==1.0 Below is Database settings: DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "########", "USER": "########", "PASSWORD": "########", "HOST": "########", "PORT": "########", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server"}, } } I checked in my terminal and required driver is also installed root@5b4341ff02e3:/# python3 Python 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pyodbc as py >>> py.drivers() ['ODBC Driver 17 for SQL Server'] >>> exit() When I try to runserver I face below issue: File "/usr/local/lib/python3.6/dist-packages/sql_server/pyodbc/base.py", line 7 except ImportError, e: ^ SyntaxError: invalid syntax This is a syntax error because sql_server.pyodbc is written in python2. What is strange that it runs fine on my local machine. Have you guys faced this issue? Is there any workaround? -
Django admin css loads perfectly (status: 200) but the output shows pure html with no styles loaded
I am very new to Django and I have been following steps from a site I found. I have already tried doing the solutions I found on other questions but none of them worked on my situation. Django Admin - Webpage cmd output Django Admin - Output no CSS My static settings looks like this: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #STATIC_ROOT = os.path.join(BASE_DIR, 'static') and my installed apps settings looks like this: DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'boards', ] Thanks in advance! -
Is there any good implementation tutorial of Django-secretballot?
I am trying to implement Django-secretballot for anonymous upvote and downvote for my blog app. I cannot find any implementation tutorial on web. I am new to Django and cannot figure out from Django-secretballot documentation on GitHub. -
How to create custom user without using models from django.contrib?
I've tried to create custom user for authentication purpose. The problem is, django.contrib.auth.models are not flexible enough to be extended. I'm using legacy mysql database with quite different table compared with django.contrib models. And I was told not to touch it by my boss since it's quite critical for our business. To conclude, I want to know how to create custom user which should be mutually excluded from django.contrib models yet still functional enough for token authentication purposes. I'm a beginner at Django, at I've yet found useful advices from official documentations. -
How to run script on startup and keep it running?
I have 4 script files for start my django project. I want to run these scripts on background when system is up. I created 1 script that trigger others and i tried sudo crontab -e @reboot /that/one/script.sh. It is working on startup(i understand it because ports are open) but its not keep running in background. When i go to browser i can see nginx default page it is opening ports but my site doesnt keep working. script1: celery -A MyProject flower --loglevel=info script2: uswgi --socket mysite.sock --module MyProject.wsgi --chmod-socket=666 --http :9090 --chdir /home/ubuntu/Desktop/project script3: celery worker --app=MyProject --loglevel=info --pool=gevent --concurrency=1000 script4: celery beat -A MyProject -l DEBUG. Manually everything works good. So how can i run these scripts on startup and keep running on background without system login. -
Django: PostgreSQL Graph Search
Is there any simple way to use PostgreSQL's graph search functionality with Django's Querysets? -
Optimize postgress query for large set of data
A Postgress database table exists with around 4 million rows of product information. Available columns are product id, SKU, product barcodes (array field) & product description etc. Here, users will upload CSV files of product data. Each product may contain multiple barcodes. The data will be updated based on existing product barcodes from DB. If the barcode already exists, the product row from CSV file will be skipped, or the product will not be added from CSV. Otherwise, a new row will be added with product information. So I have to check every row before inserting data into the table and the query time is very high as there is a large number of data. The query I used to check if barcode exists: SELECT * FROM retail_retailinventory WHERE '*****’ = ANY(barcodes) Is there any way to optimize the query? Or any scope to apply Machine Learning in this case? My concern is if I apply ML, the machine needs to be trained every-time a new row is inserted into the database and it would not be a good solution. Any suggestions will be appreciated. Thanks. -
When i use pip install mysqlclient i got error
I am trying to install mysqlclient using pip but it keeps running into an error. I have seen suggestions telling me to make sure my python version in mysqlclient is up to date. I have already done that. After pushing to mysqlclient master, i ran the install command but it gives me the following errors. How can I fix this error? pip install mysqlclient Error: (base) brijesh:~ sierra$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /opt/anaconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/pm/gmghbq8960bgdq9hk_bx25qc0000gn/T/pip-install-8qoawh1_/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/pm/gmghbq8960bgdq9hk_bx25qc0000gn/T/pip-install-8qoawh1_/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/pm/gmghbq8960bgdq9hk_bx25qc0000gn/T/pip-wheel-yu73tf06 cwd: /private/var/folders/pm/gmghbq8960bgdq9hk_bx25qc0000gn/T/pip-install-8qoawh1_/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension … -
Delete multiple objects in django rest framework
I need to delete all objects in my table. Is possible to have a request " http://localhost:8000/api/products/delete_all/ " and when i do a get request i delete all objects. I saw this solution Delete multiple objects in django but i don't know if is possible to implement this in a moldeViewSet. Views.py class ProductModelViews(viewsets.ModelViewSet): permission_classes =(permissions.IsAuthenticated,) queryset = ProductModel.objects.all() serializer_class = TestProductModelSerializer -
Add and Accept friend request issue
I am working on a dating website with Django, i have followed tutorial online but there is an issue with my code on how i can accept a friend/follow request back from other users. For example, if John send a friend/follow request to Paul, when i log into Paul's account and click on John profile then i can see 'accept request/follow back' in John's profile. But what i have coded is the reverse, according to my code when John send a friend/follow request to Paul, when i log into Paul's account and click on John's profile i do not see the 'accept request/follow back', rather i see the 'accept request/follow back' on John profile instead of Paul's profile. How do i link the 'accept request/follow back' to the user profile i sent a friend/follow request to. Please let me know what i am missing in my code. class Follow(models.Model): users = models.ManyToManyField(User, blank=True) follower = models.ForeignKey(User,on_delete=models.CASCADE,related_name='owner',blank=True,null=True) date = models.DateTimeField(auto_now_add=True, null= True) @login_required def profile(request, username): follow, created = Follow.objects.get_or_create(follower=request.user) #request.user follows = follow.users.all() rec_friend_requests = Follow.objects.filter(users__username=username) context = { 'rec_friend_requests': rec_friend_requests, } return render(request,'profile.html', context) {% for hideeditbtn in profile_img %} {% for r_request in rec_friend_requests %} <p><a href="">{{ r_request.follower.username … -
Showing Image in django
I have a Django web app where I am uploading an image and showing some texts. But I am not able to show the image in the front end after uploading. views.py def index(request): if request.method == "GET": return render(request, 'index.html') elif request.method == "POST": input_file = request.FILES['file'] media_root = settings.MEDIA_ROOT fs = FileSystemStorage() filename = fs.save(input_file.name, input_file) uploaded_file_url = fs.url(filename) filepath = os.path.join(media_root, filename) images = segment_lines(filepath) extracted_text = extract() copy2(filepath, '/home/user/ocr/ocr/static/images/'+ filename) response = { "response" : extracted_text, "img": filename} return JsonResponse(response, safe=False) index.html <form action="" id="file-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-sm-10 col-md-10 col-lg-9"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01">Upload</span> </div> <div class="custom-file"> <input type="file" accept="image/*" name="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01"> <label class="custom-file-label" for="inputGroupFile01">Choose file</label> </div> </div> </div> </div> <div class="col-sm-2 col-md-2 col-lg-3"> <span class="upload-btn"> <button type="submit" id='upload-button' class="btn btn btn-outline-dark">Extract</button> </span> </div> </div> </form> <div class="row" style="border:none;"> <div class="col-xs-6 mx-auto" id="img_data"> </div> <div class="col-xs-6 mx-auto" id="content_data"> </div> </div> <script type="text/javascript"> var form = document.getElementById('file-form'); var fileSelect = document.getElementById('inputGroupFile01'); var uploadButton = document.getElementById('upload-button'); form.onsubmit = function(event) { event.preventDefault(); uploadButton.innerHTML = 'Processing ...'; var file = fileSelect.files[0]; var formData = new FormData(); formData.append('file', file, file.name); formData.append('csrfmiddlewaretoken', '{{ csrf_token }}'); var xhr = new … -
How to create database for multi-level menu, category and right-side content
I trying to rewrite the website (it is same as https://ketoansaovang.com.vn/en/news/accounting-news-1.html) by Django. I have problem with design database for main menu and other part of page. For example, "NEWS AND EVENT" item have subitem as "ACCOUNTING NEWS", "AUDIT NEWS", "TAX NEWS",... When I choose one sub-item, it is highlighted on left category and ringt show all news for this subitem. workflow when click on news sub-item I have designed menu model as below: class Menu(models.Model): menu_parent = models.ForeignKey('self', on_delete=models.CASCADE, default = None, blank=True, null=True) menu_title = models.CharField(max_length = 255, unique=True) menu_link = models.CharField(max_length=500) def __str__(self): return self.menu_title But I can not link it to news or services item. Please give idea for it. -
How to paginate a returned list from viewset in DRF?
In reference to the question asked earlier : Similar Question related to the pagination I am still not getting the Metadata(Count,previous and next) in the response. class LinkHeaderPagination(pagination.PageNumberPagination): page_size_query_param = 'page_size' def get_paginated_response(self, data): next_url = self.get_next_link() previous_url = self.get_previous_link() if next_url is not None and previous_url is not None: link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"' elif next_url is not None: link = '<{next_url}>; rel="next"' elif previous_url is not None: link = '<{previous_url}>; rel="prev"' else: link = '' link = link.format(next_url=next_url, previous_url=previous_url) headers = {'Link': link, 'Count': self.page.paginator.count} if link else {} return Response(data, headers=headers) def list(self, request, *args, **kwargs): queryset= User.objects.all().values_list('name','designation') queryset=[{'name':i[0],'designation':i[1]} for i in queryset] serializer=getuserserializer(queryset,many=True) paginator = LinkHeaderPagination() page = paginator.paginate_queryset(new_dict, request) if page is not None: return paginator.get_paginated_response(page) return Response(serializer.data) -
How to update foreign key fields using same serializer
I am facing one issue for updating foreign key field using same serializer Here is my model : class User(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(max_length=200, blank=True) contact_number = models.CharField(max_length=20, blank=True) team = models.CharField(max_length=200, blank=True) manager = models.CharField(max_length=200, blank=True) joining_date = models.DateField(default=datetime.now) I need to update the current user profile details But the user first name and last name are associated with table User and the rest of the informations associated with Userprofile table So I am confused how to create a working serializer for updating the Userprofile Here is my serializer class ProfileSerializer(ModelSerializer): class Meta: model = UserProfile exclude = ['deleted_at', 'created_date', 'modified_date'] extra_kwargs = {'user': {'required': False}} or am I need to edit it in views , this is the current view... class UserProfileUpdateView(UpdateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = UserProfile.objects.filter( user=self.request.user) return queryset_list serializer_class = ProfileSerializer -
Django, is_authenticated creates multiple requests
In base.html I use request.user.is_authenticated several times, which creates as many database queries as I called this check, is it possible to run the check once the user is authenticated, and then use the variable to check so that I don’t have to go every time to the database or is it not so critical -
Django: when to use the annonate and aggregate?
What is the difference or, advantage and disadvantage of using aggregate and annonate? I already read the documentation on how to use the aggregate and annonate, but i still dont know the difference between them, I need to know when to use the annonate and aggregate , please tell me, I know I'm not the only one confused about when to use annonate and aggregate. especially when you are a beginner in django, thanks -
Django haystack change query generated from SOLR admin to django haystack ORM query / syntax
I have query generated from SOLR Admin like this Raw Query select?bq=num_in_stock:[1%20TO%20*]^1000&debugQuery=on&defType=edismax&fq=baby&indent=on&q=*:*&sort=score%20desc,%20price%20desc&wt=json Response Header "responseHeader":{ "status":0, "QTime":99, "params":{ "q":"*:*", "defType":"edismax", "indent":"on", "fq":"baby", "sort":"score desc, price desc", "wt":"json", "debugQuery":"on", "_":"1583221250846", "bq":"num_in_stock:[1 TO *]^1000"}}, and it displays the right data for me. How to change to Django-haystack ORM syntax? I already use this syntax in Django haystack ORM, but still not display data like SOLR admin generated: from haystack.query import SearchQuerySet self.searchqueryset = SearchQuerySet() sqs = self.searchqueryset.auto_query(self.cleaned_data['q']) sqs = sqs.order_by('-score', '-price') sqs = sqs.filter_and(content=AltParser('edismax', self.cleaned_data.get('q'), bq='num_in_stock:[1 TO *]^1000')) Thanks for help and answer! -
Compute sum from another table in Django
I need to create model in Django for the following : Invoice table -> invoice_id, order_id, unit_price, num_units 1, 1, 10, 5 1, 2, 10, 5 2, 1, 10, 5 2, 2, 10, 5 3, 3, 10, 5 3, 1, 10, 5 3, 2, 10, 5 Invoice Summary table -> invoice_id, sum 1, 100 2, 100 3, 150 How should my Model look like for the above tables in Django? I tried: class Invoice(models.Model): inv_id = models.IntegerField() order_id = models.IntegerField() unit_price = models.IntegerField() num_units = models.IntegerField() class Summary(models.Model): How will my Summary Model look like such that I get correct result for a particular Invoice id? -
Condition in permissions of suit config django
In suit config, i am passing multiple permissions. Is it an AND or OR condition, if its an AND condition how can i change it to OR condition {'label': 'Upload Patients Details', 'url': '/admin/patients/upload_patients_data/', 'permissions': ('upload.access_patients_data', 'user.superuser', 'patients.patients')}, currently the user should be a superuser and he should have the group called patients too. so i think its an AND condition. How can i make it OR condition ? any help is appreciated