Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Storage app, different "upload_to" depending on user's choice
I'm trying to implement functionality where user can upload file and choose (in the form) if this file is going to be global (available for everybody) or private (available only for him). The form would look like this Firstly I have doubled model, view, form etc. where only difference was: file = models.FileField(upload_to=user_directory_path) and file = models.FileField(upload_to='global files/') what destroys DRY rule. Obviously it's not what I want to achieve. So then I tried to make a boolean in model and change "upload_to" parameter depending on user's choice: title = models.CharField(max_length=50, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=user_directory_path) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) STATUS = ( (1, ('Global file')), (2, ('My file')), ) status = models.CharField(max_length = 30, choices=STATUS, default=2) if status == 'My file': file = models.FileField(upload_to=user_directory_path) elif status == 'Global file': file = models.FileField(upload_to='global files') Unfortunately it doesn't work. Does anyone has any idea how to implement that? -
An out of my knowledge error while executing a python script
I wrote a python script to populate my database with some fake data using the Faker library for a casual project as i am learning Django. My project name is "ProTwo" and there is an application inside of this project named "apptwo". This is the python script i wrote: (populate_users.py) import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'ProTwo.settings') import django django.setup() from apptwo.models import User from faker import Faker fakegen = Faker() def populate(N=5): for entry in range(N): fake_name = fakegen.name().split() fake_first_name = fake_name[0] fake_last_name = fake_name[1] fake_email = fakegen.email() user = User.objects.get_or_create(first_name = fake_first_name, last_name = fake_last_name, email = fake_email)[0] user.save() if __name__ == '__main__': print('POPULATING DATABASES!') populate(20) print('POPULATION DONE!') models.py: from django.db import models class User(models.Model): first_name = models.CharField(max_length = 264,null = True) last_name = models.CharField(max_length = 264, null = True) email = models.EmailField(max_length=254, unique = True) (views.py): from django.shortcuts import render from django.http import HttpResponse from apptwo.models import User def index(request): return render(request,'app_two/index.html') def users(request): user_list = User.objects.order_by('first_name') user_dict = {'users': user_list} return render(request,'app_two/users.html', context = user_dict) (urls.py): from django.contrib import admin from django.conf.urls import url, include from apptwo import views urlpatterns = [ url(r'^$',views.index, name = 'index'), url('admin/', admin.site.urls), url(r'^users/', include('apptwo.urls')), ] and this is the error on executing the … -
React app with Django error 'string indices must be integers'
I have a react app with Django Rest framework. Here is the folder structure where "api" is the app for rest API and "frontend" is an app for React App. here is code of frontend/urls.py urlpatterns = [ #path('', views.index), #url(r'^(?:.*)/?$', views.index), url(r'^.*$', TemplateView.as_view(template_name="frontend/index.html")),] Here is relevant part webpack.config.json const PATHS = { app: path.join(__dirname, "src"), template: path.join(__dirname, "templates/frontend"), build: path.join(__dirname, "static/frontend")};const productionConfig = merge([ parts.output({ path: PATHS.build, publicPath: '/frontend/' }), parts.extractStyles({ use: ["css-loader", "sass-loader", parts.autoPrefixer()] }), parts.minifyJs(), parts.minifyStyles({ options: { discardComments: { removeAll: true, }, // Run cssnano in safe mode to avoid // potentially unsafe transformations. safe: true, }, }), parts.bundleTracker({ filename: '../../../webpack-stats.json' }),]); Below is created webpack-stats.json {"status":"done","chunks":{"main":["vendor.css","vendor.js","main.css","main.js"]},"publicPath":"/frontend/","assets":{"main.css":{"name":"main.css","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\main.css","publicPath":"/frontend/main.css"},"main.js":{"name":"main.js","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\main.js","publicPath":"/frontend/main.js"},"vendor.css":{"name":"vendor.css","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.css","publicPath":"/frontend/vendor.css"},"vendor.js":{"name":"vendor.js","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.js","publicPath":"/frontend/vendor.js"},"vendor.js.LICENSE.txt":{"name":"vendor.js.LICENSE.txt","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\vendor.js.LICENSE.txt","publicPath":"/frontend/vendor.js.LICENSE.txt"},"index.html":{"name":"index.html","path":"E:\\freelance\\familytree\\frontend\\static\\frontend\\index.html","publicPath":"/frontend/index.html"}}}} When I run the application, I see below error. -
How to implement in-app purchase server to server notification in django or node js?
I am trying to implement in-app purchase server to server notification. Can anyone help me how to implement? -
Use Admin List Actions to Create New Object
I have a model with Email_address and Email_message, connected with a many-to-many relationship. Email_message.email_addresses refers to the recipients of the Email_message. models.py class Email_address(models.Model): address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) class Email_message(models.Model): email_addresses = models.ManyToManyField(Email_address, related_name='email_messages') subject = models.CharField(max_length=50) body = models.TextField() date_time = models.DateTimeField(null=True, blank=True) I would like to select many Email_address objects through the list view in Admin, then use an action to create a new Email_message. All of the selected Email_address objects would be saved as recipients. What is the simplest way to do this? I've thought about creating forms in a new template but it seems overly complicated. It should be possible to pass the email_address action's queryset to Django Admin's default add new email_message page but I can't figure out how this could be done. So again, what is the cleanest way to do this? -
How can i send real time data to a client on Django?
On a server, i'm hosting a Python script that streams some JSON data received by a lot of IoT sensors. I'm trying to find a way to have that data on a Django application: if the user opens the page for sensor 30, the user must get real time data from sensor number 30 and so on. I know that Django Channels is the standard to hadle real time data on Django, but in this case the data is not generated by the client and its not generated by Django Channels, the user only needs to receive the data. Using a database is out of question due to performances and because i don't need to store any data at all. Is there a way to do this? I was thinking of creating a websocket on my data generator script (using SocketIO maybe?), for every sensor i would create a room, while on my Django frontend i would add some Javascript to connect to the websocket server and to that sensor's room. So user opens the page for sensor 35, the frontend will connect it to my external websocket server and then to the room of that sensor. I know this …