Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelForm Related To Specific Instance Django
So basically I am creating a jobs board using Django. I have a model such as: class Job(models.Model): title = models.CharField() description = models.CharField() reference = models.Charfield() etcetc I have a page that displays Job.objects.all() where users can go to a detail view that displays the detail of each instance, and on each detail view there's an Apply Now button, which takes the users to a form. The form has a field like: reference_code = forms.TextField() When a user clicks on the Apply Now button, I want the form to know which instance the user is applying for. I was thinking maybe prepopulating the form with the the 'reference' of the instance they have just came from may be the best way? (I.e. user on detailview > user clicks apply now > taken to apply page > form on page already knows which instance the user is applying for.) Any help is much appreciated. Thanks guys! -
Django search form with multiple search criteria
in my Django website I've got a simple search form. The User can look for a band name or an album name. But if the album and band name are the same I'd like the user to be redirected to a page where he can choose between looking for the band or the album. Hope someone could help me, I'm really stuck with this. Thanks a lot! this is the form in HTML: <form method="post" action="{% url 'searches' %}"> {%csrf_token%} <input type="text" name="srh" class= "form-control" placeholder=" Type Album or Band Name..."> <!-- <button type="submit" name="submit">Search</button> --> </form> views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr.exists() and sd.exists(): return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') The "searches" page where are listed the results: {% if sd %} {% for y in sd %} <div class="container"> <div class="album"> {%if y.cover%} <img src= "{{y.cover.url}}" width="100%"> {%endif%} </div> <div class="info"> <table class="talbum" style="height:400px"> <tr><th colspan="2"><h2>{{y.disco}}</h2></th></tr> <tr><td> Band: </td><td> {{y.band}} </td></tr> <tr><td> Anno: </td><td> {{y.anno}} … -
Why the pagination doesn't work in my Django website?
I followed the django documentation and I added the pagination and everything looks fine. Here is how it looks how the pagination looks like. I think the views.py, urls.py, and the template are okay and the problem is in the models.py, I don't know exactly. When I click to any page number in the pagination which will redirect me to the page with the url "example?page= " and the problem comes here, because my website doesn't work with the "?page=". Here is the error I got: IntegrityError at /new_search NOT NULL constraint failed: global_store_app_search.search Request Method: GET Request URL: http://127.0.0.1:8000/new_search?page=2 Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: global_store_app_search.search Exception Location: /home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/Desktop/TunisiaGlobalStoreDjango/global_store_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Thu, 2 Apr 2020 18:08:59 +0000 Here is the template: <div class="pagination"> {% if posts.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ posts.previous_page_number }}">Previous</a> {% endif %} {% for num in posts.paginator.page_range %} {% if posts.number == num %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > posts.number|add:"-3" and num < posts.number|add:"3" %} <a … -
django: avoid repeating strings spanning relationships?
I have lookup strings that span multiple relationships and want to select/filter on fields of a related table. I end up with something like MyTable.objects \ .filter(aaa__bbb__ccc_field1=5) \ .values('aaa__bbb__ccc_field2') \ .annotate(Sum('aaa__bbb__ccc_field3')) Is there any way to refer to the multiple fields of aaa__bbb__ccc without repeating the whole string (obviously, I'm not asking about string concatenation, but whether there's any django-specific support). -
Django storage app files are always uploaded to same folder
I want every user to have his own folder with files. No matter on what account I am logged in, files are always uploaded to first registered user's folder. For instance, when I am logged as user "tester" files should go to /media/files/tester. models.py from django.contrib.auth.models import User def user_directory_path(instance, filename): return '{0}/{1}'.format(instance.user.username, filename) class FileModel(models.Model): title = models.CharField(max_length=50, blank=True) file = models.FileField(upload_to=user_directory_path) uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.title views.py @login_required() def main_page(request): files = FileModel.objects.filter(user=request.user) return render(request, 'dropbox/main_page.html', {'files': files} ) @login_required() def upload_file(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main_page') else: form = FileForm() return render(request, 'dropbox/upload_file.html', {'form': form}) What to do to have files uploaded to proper folders depending on who is logged in? -
when I try to run python manage.py runserver , i am facing someproblem
enter image description here I'm neither getting an error nor getting a successful message -
how to insert my own form into ready Codepen template of search bar
Guys i have ready search input which i took from CodePen which looks great. <div class="input-group"> <input type="text" class="form-control" placeholder="Search this blog"> <div class="input-group-append"> <button class="btn btn-secondary" type="submit"> <i class="fa fa-search"></i> </button> </div> </div> I have the form which work good but is ugly : <form method="POST" > {% csrf_token %} {{ form}} <button lass="btn btn-secondary" type="submit"><i class="fa fa-search"></i></button></form> I want to combine my form into ready CodePen template instead of input. However when i tried the boxt of my form get into box of CodePen form and looks ugly. How to insert form into the first template which i took from the internet? I am not experienced with design so wanted your help make my form more beatiful and worksable. Thanks in advance -
Django - get objects that have a related objects with certain field only
Given the following models: class Person(models.Model): objects = PersonManager() ... class Job(models.Model): person = models.ForeignKey( to=Person, related_name='jobs' ) workplace = models.ForeignKey( to=Workplace, related_name='workers' ) position = models.CharField(db_index=True, max_length=255, blank=False, null=False, choices=( (POSITION_1, POSITION_1), (POSITION_2, POSITION_2), (POSITION_3, POSITION_3), )) A person can have several jobs with the same position and with different positions too. person1: [workplace1, POSITION_1], [workplace1, POSITION_2], [workplace2, POSITION_1] person2: [workplace1, POSITION_2], [workplace2, POSITION_2] person3: [workplace3, POSITION_3] I want to write a single method in PersonManager which will retrieve all persons with multiple jobs of a certain given position (and that position only); or if multiple positions are given then persons that work in all of these positions. Person.objects.get_multiple_jobs(jobs=[]) will return person1, person2 Person.objects.get_multiple_jobs(jobs=[POSITION_2]) will return person2 ONLY (as he's the only one with only POSITION_2 multiple jobs). Person.objects.get_multiple_jobs(jobs=[POSITION_1, POSITION_2]) will return person1 Person.objects.get_multiple_jobs(jobs=[POSITION_3]) won't return anything Using Person.objects.filter(jobs__position__in=[...]) won't work as in the 3rd case I'll get person2 as well. Chaining filter/exclude like Person.objects.filter(jobs__position=POSITION_1).exclude(jobs__position__in=[POSITION_1,POSITION_3] will work but it's not maintainable - what if in the future more positions will be added? Deciding which jobs to exclude dynamically is cumbersome. It also results in filters being very hard-codded when I wanted to encapsulate the logic under a single method … -
User Authentication in Django using MySQL database
My apologies, if the question has been asked multiple times. Trust me, I tried looking for an answer, but couldn't find it. I am building an Admin backend application in Django(Frontend is developed in PHP). I am trying to do user authentication. The user database is stored in UserInfo Table. I save the md5(password) in the UserInfo table. I would like to authenticate the user from the registered email address/password. Any idea how this can be achieved? Here is the small snippet of the code: from django.contrib.auth import authenticate email = 'kiran.chandrashekhar@gmail.com' passsword1 = '12345' user = authenticate(username=email, password=passsword1) print(user) -
error issue on connecting mysql for django project
I am new to Django.i am learning Django for the past few weeks,i have some trouble on changing the databse to sqllite to mysql. setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'USER': 'root', 'PASSWORD': ' ', 'HOST': 'localhost', 'PORT': '3306', }} When i try to run the server using py manage.py runserver It show me the error like django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") SPECIFICATION python-3.8 django-3 MySQL(xampp) OS-windows -
populate django model with scraped data
I had Scrapped Data from https://www.worldometers.info/coronavirus/ for countrywise stats using bs4. but i want to use that data to populate my django model with same fields as scrapped data which i dont know how. i am also having trouble with scraping tabular data with other libraries like scrapy (celery).this is the xpath of the table i am try to scrap "//*[@id="main_table_countries_today"]". if anyone could help me how to use this scarp data to store in django models would be great. PS not using external CSV or Json Files. -
Post-Form Validation using Ajax and Django
I'm using Ajax to submit a form in Djangos Updateview. When not using AJAX to Post the form but a "submit"-Button and the form is invalid, the page gets reloaded and the user gets Information about what went wrong (f.e. email in wrong format). This is a Default Django-Feature. I was wondering if I can use the exact same feedback on an AJAX Form-POST? I mean Posting the form with Ajax and displaying the same information to the user about what went wrong, as if the Form was submitted via a "submit"-Button. Thanks in Advance! -
Conditions in querysets
I have a Dashboards table and a table that defines the "editor" permission as follows: Dashboard ========= id Name Owner -- ---- ----- 1 Dashboard1 555 DashboardUsers ============== id dashboard_id user_id editor -- ----------- ------- ------- 1 1 222 true 2 1 333 true Lets say that Owner that exists in Dashboard table is also an editor but this info does not exists in DashboardUsers table. So i m trying to construct a queryset that checks editor rows (including the Owner ). So i replace @userparamexample with 222 the queryset will correctly return a row. But if i replace the @userparamexample with 555 i will not get anyting. How do i have to moderate the query to get if someone is an editor(owner). models.Dashboard.filter( dashboarduser__user_id=@userparamexample dashboarduser__editor=True ) -
OperationalError: no such column: django-modeltranslation. Django
I have a working app in English. I have started translating tables and istalled django-modeltranslation. I have 11 similar pre-populated tables with the similar content. 8 tables have successfully migrated via python3 manage.py makemigrations and python3 manage.py migrate Migration of remaining 3 tables causes the same error for all three tables. django.db.utils.OperationalError: no such column: rsf_dirt.dirt_en django.db.utils.OperationalError: no such column: rsf_application.application_en django.db.utils.OperationalError: no such column: rsf_dirtproperties.dirtproperties_en All tables properly work via admin panel. Please help. models.py from django.db import models from django.utils.translation import gettext_lazy as _ class FP_sealing(models.Model): value = models.CharField(_('Material Sealing'), max_length=10) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Seal: " + self.value) class FP_ventil(models.Model): value = models.CharField(_('Backflush valve'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") aufpreis_el_ventil = models.IntegerField(_('Extra Cost el.Valve'), default=0) def __str__(self): return("Ventil: " + self.value) class FP_motor(models.Model): value = models.CharField(_('Motor Power'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Motor: " + self.value) class FP_material_geh(models.Model): value = models.CharField(_('Material Housing'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Mat.Geh.: " + self.value) class FP_coating(models.Model): value = models.CharField(_('Coating'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Coating: " + self.value) class FP_color(models.Model): value = models.CharField(_('External Color'), max_length=25) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Color: " + self.value) class … -
How do I specify order of fields in Django form?
We are using Django 2.2 and I want to upgrade to Django 3.0. We have a mixin (written in 2017) that add fields to forms: class LocalizedFirstLastNameMixin(object): def __init__(self, *args, **kwargs): self.language_code = kwargs.pop('language_code', 'en') super().__init__(*args, **kwargs) for loc_field in reversed(self.get_localized_fields()): self.fields[loc_field] = User._meta.get_field(loc_field).formfield() self.fields[loc_field].required = True self.fields.move_to_end(loc_field, last=False) self.initial[loc_field] = getattr(self.instance, loc_field, '') This mixin is used as one of the bases classes for forms which inherit from ModelForm: class RegistrationForm(AddAttributesToFieldsMixin, CleanEmailMixin, CleanNewPasswordMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm): .... class ProfileForm(AddAttributesToFieldsMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm): .... It works with Django versions up to 2.2. But when I upgrade to 3.0, I get this error message: AttributeError: 'dict' object has no attribute 'move_to_end' This function's info: Move an existing element to the end (or beginning if last==False). And it belongs to OrderedDict. So I guess we want these fields to be in the beginning of the form fields. Is there a change in the implementation of the fields in forms in Django 3.0 and how do I specify the order of fields? And if I change it, will it work in previous versions such as Django 2.2? I checked the Django 3.0 release notes and also releases from 3.0.1 to 3.0.5 and I … -
How to Implement django model methods
I am trying to build a system where we run depreciation on all assets in the database. Asset models is defined as below: class Asset(models.Model): Asset_description=models.TextField(max_length=100) Tag_number=models.TextField(unique=True) Asset_Cost=models.IntegerField(default=0) Monthly_Depreciation=models.IntegerField(default=0) Current_Cost=models.IntegerField(default=0) def __str__(self): return self.Asset_description How can i implement the depreciation formula in the models, e.g. Monthly_Depreciation=Asset_Cost/3/12 and Current_Cost=Asset_Cost-Monthly_Depreciation? -
Accessing form.cleaned_data in get method in class based views
I have a situation where I should first display a form to the user where the user fill in two fields and after that base on the form fields I query database and show the user a list of objects. But the problem is I use class based views and I can't access to the cleaned data in my get method. I know that the forms must be handled in post methods not get methods so I can't process form in my get method. Here is my code: views.py class IncomeTransactionReport(LoginRequiredMixin, ListView): def post(self, request, *args, **kwargs): # here I get form from post request form = IncomeReportForm(request.POST) # if form is valid redirect user to the same page to show the results based on the filled # in form fields 'from_date' and 'to_date' if form.is_valid(): from_date = form.cleaned_data['from_date'] to_date = form.cleaned_data['to_date'] return redirect('income_report') # else render the same page with the form and form errors else: error_message = 'Please solve the error and try again' return render(request, 'report_income.html', context={'error_message': error_message, 'form': form}, status=422) def get(self, request, *args, **kwargs): # here I need to access 'from_date' and 'to_date' to query the database and show the results # in paginated pages … -
Django ManyToManyField auto adds Users
Working on a project and wanted to implement a bookmark feature. However, adding a ManyToManyField linking to the Django User model ends up adding every registered user to the table from django.contrib.auth.models import User class Headline(models.Model): title = models.CharField(max_length=300) url = models.URLField(max_length=500) site = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(blank=True) bookmark = models.ManyToManyField(User, blank=True) class Meta: ordering = ['-date'] def headline(self): if len(self.title) > 100: return f"{self.title[:90]}..." else: return self.title -
Django forms - submitting the data isn't working
I'm really new to Django and I want to teach myself my making a simple note. But I don't understand how django forms work. I made simple template when I can display the user's notes and now I am trying to make a view when the user can add new notes to account using a simple form. Here is my views.py file from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .forms import CreateUserForm, CreateNoteForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * # Create your views here. def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username or pasword is incorrect') context = {} return render(request, 'accounts/login.html', context) def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for '+ user) return redirect('home') context = {'form': form} return render(request, 'accounts/register.html', context) def logoutUser(request): logout(request) return redirect('login') @login_required(login_url='login') def home(request): if request.user.is_authenticated: username = request.POST.get('username') context = {'username': username} return render(request, 'accounts/home.html', context) def … -
no django file in the site packages
**Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.7/site-packages/rest_framework/authtoken/models.py", line 6, in <module> from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (/usr/local/lib/python3.7/site-packages/django/utils/encoding.py)** so i want to change the code in encoding.py to from django.utils.six import python_2_unicode_compatible from from django.utils.encoding import python_2_unicode_compatiblefile as i am using python3.7 . i cant find the django directory under the site-packages. so what to do ? -
Django,DRF, get another app's view name for a reverse
I'm trying to create a link for another app in my serializer using the solution provided here: https://stackoverflow.com/a/45850334/12177026 I'm trying to match the view's name but every way I try I get this error: Reverse for 'KnownLocationView' not found. 'KnownLocationView' is not a valid view function or pattern name. serializers: class MissionSerializer(HyperlinkedModelSerializer): gdt = ChoiceField(choices=lazy(get_locations, tuple)()) location = SerializerMethodField(label='Open Location') def get_location(self, obj): request = self.context.get('request') return request.build_absolute_uri(reverse('KnownLocationView', kwargs={'Name': obj.gdt})) class Meta: model = Mission fields = ('MissionName', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'gdt', 'location') KnownLoction/urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import KnownLocationView app_name = 'KnownLocation' router = DefaultRouter() router.register(r'knownlocations', KnownLocationView) urlpatterns = [ path('', include(router.urls)), ] I tried replacing view_name with either of the following: 'knownlocations' 'KnownLocation:knownlocations' 'KnownLocation:KnownLocationView' But get the same error even tried to reorder the installed apps. api/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('landingpage.urls')), # API Landing Page path('', include('ThreeLocations.urls')), # Triangulation between two Known GDTs and uav location. path('', include('SecondGDT.urls')), # Options For Second GDT Positioning. path('', include('KnownLocation.urls', namespace='knownlocations')), # Add Known Location To the map. ] + staticfiles_urlpatterns() -
Django - Circular import with multiple files
I have 3 python files within a package, I'm trying to import a class from one file into other 2 file. But i get error. models __init__.py a.py b.py c.py a.py class ATestOne() pass class ATestTwo() pass class ATestThree() pass b.py from app.models.a import ATestOne, ATestTwo from app.models.c import CTestOne class BTestOne() field1 = models.ForeignKey(ATestOne) class BTestTwo() field1 = models.ForeignKey(CTestOne) c.py from app.models.a import ATestOne, ATestThree from app.models.b import BTestOne class CTestOne() field1 = models.ForeignKey(ATestOne) class CTestTwo() field1 = models.ForeignKey(BTestOne) Returns below mentioned error ImportError: cannot import name 'ATestOne' Kindly advice in solving this. Thanks in advance. -
To get the weight of product in ebay api
Currenly i am working in ebaysdk. I am facing the problem which is the weight of the product. how can i can get product weight ? I used trading api but most of weight of the products equal to 0. is there any way to get product weight all the time? I requested like this: response = api_trading.execute('GetItem' , {"ItemID":"184097524395",'DestinationPostalCode':'2940','DestinationCountryCode':'GB'}) -
pip install mysqlclient returns Building wheel for mysqlclient (setup.py) ... error
[its show wheel error and fatal error error that cannot open file mysql.h pip install mysqlclient returns Building wheel for mysqlclient (setup.py) ... error] -
How to return multiple fields from a Model object?
I am doing testing in django and already created a model instance using ddf.G. Now I want to use this instance in a test case to return multiple fields of the model. I know how to return multiple fields using queryset like: model_values = models.User.objects.values_list( 'first_name', 'last_name', 'image__name', 'image__description' ) Now I want to return same fields but by using the instance I already have. Is there any way to achieve this?