Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a mysql pool globally for multiple processes
I'm using Django and Celery workers to transfer data from one MySQL table to a table in another database. Each Celery worker do the same thing: 1. select n rows of data from the source table; 2. insert into the dest table; 3. repeat 1 and 2 until all data transfered. How to avoid creating mysql connection for each worker each time it hit the database? I want to create a connection pool for the database the first time a worker hit the database, and then every worker just use "get_connection" method of the pool object to get a connection. I tried to cache the pool globally using Django's cache, but failed. What should I do? How to create a global pool for all the processes or is there a better way? -
Related Field got invalid lookup: title_icontains
My model.py: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from django.utils.text import slugify # Create your models here. class Stocks(models.Model): title = models.ForeignKey('Product', verbose_name="Ürün", on_delete=models.CASCADE) stock = models.DecimalField(max_digits=3,decimal_places=0,default=0,verbose_name="Stok") seller = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,verbose_name="Fiyat") def __str__(self): return str(self.title) class Meta: verbose_name = "Stok" verbose_name_plural = "Stoklar" def upload_image_location(instance, filename): return "%s/%s" %(instance.id, filename) class Product(models.Model): title = models.CharField(max_length=100,verbose_name="Başlık") slug = models.SlugField(blank=True, unique=True) category = models.ForeignKey('Category', null=True, blank=True, verbose_name="Kategori",on_delete=models.CASCADE) description = models.TextField(null=True,blank=True,verbose_name="Ürün Açıklaması") price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,verbose_name="Fiyat") sale_price = models.DecimalField(max_digits=100,decimal_places=2,default=0.00,null=True,blank=True,verbose_name="İndirimli Fiyat") tax = models.DecimalField(max_digits=3,default=18,decimal_places=0,verbose_name="KDV") status = models.BooleanField(default=True,verbose_name="Aktif/Pasif") image1 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Vitrin Fotoğrafı") image2 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 1") image3 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 2") image4 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 3") image5 = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Galeri Fotoğrafı 4") def get_absolute_url(self): view_name = "detail_slug" return reverse(view_name, kwargs={"slug": self.slug}) def __str__(self): return self.title class Meta: verbose_name = 'Ürün' verbose_name_plural = 'Ürünler' def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Product.objects.filter(slug=slug) exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def product_pre_save_reciever(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(product_pre_save_reciever, sender=Product) My views.py class ProductDetailView(LoginRequiredMixin, MultiSlugMixin, DetailView): model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) … -
Django application not working on a new centos server
I have a django application that was tested and working fine in our UAT environment which is a centos 7 server. When the time came to migrate the same to production, I copied the files to production server which is again a centos 7 server and applied the migrations. When I am trying to access my application through localhost it doesn't show the index page. It just gives a generic error the site can't be reached. I removed all the .pyc files and ran compileall but nothing worked. Any clue how to run a already functioning django app in a new server? -
Django rest framework not displaying MongoDB embedded fields correctly
I am having trouble displaying the codes array as an embedded field on Django. I am connecting Django up to a MongoDB where there are embedded documents. (See below) Adding the fields in Django Administration works fine. (See below) However, on the Django Rest Framework it is not showing it as an embedded field. Here is my code for Django models.py from djongo import models from django import forms class Order(models.Model): code = models.CharField(max_length=3, blank=False, null=False) quantity = models.IntegerField() def __str__(self): return '%s %s' % (self.code, self.quantity) class OrderForm(forms.ModelForm): class Meta: model = Order fields = ( 'code', 'quantity' ) class Portfolio(models.Model): username = models.CharField( primary_key=True, max_length=65, default="", blank=False, null=False) codes = models.ArrayModelField( model_container=Order, model_form_class=OrderForm ) Thank you! -
Add user to a model by clicking on a link
I created a unique token that is link to a property, when the user goes to the link there is a button to validate is will to join this property. Now, I am a bit confused on how to finish my code. Models.py : class Property(models.Model): name = models.CharField(max_length=250, verbose_name="Nom de l'établissement") contributors = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés") token = models.CharField(max_length=500, verbose_name="Token") payday = models.CharField(max_length=500, verbose_name="Jour de paye", null=True, blank=True) planning = models.ImageField('Planning', null=True, blank=True ) My views.py def join_property(request, property_id): property = Property.objects.get(pk=property_id) contributors # now this is where I cannot figured out ... contributors.save() So I get the logic but not fully understand the middle part of my code. Thanks for your help. -
How to autofill editable forms in Django
tl;dr How to autofill an editable form with information stored in database Hey, Im creating a profile page for an application using Django as a framework. And Im having some annoying issues when a user is editing their page. As it is now, the user has to retype every field in the form, to edit a single field.. Cause my view has to delete the previous information in each field, or I get some annoying errors. So my question is, is there a way to autofill these fields in profile_edit.html with the strings corresponding to each field in the form, from the database? Any help would be greatly appreciated :D view.py @login_required def profile_edit(request): form = ProfileUpdateForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): user = request.user if 'image' in request.FILES: user.profile.image = request.FILES['image'] user.profile.bio = form.cleaned_data.get("bio") user.profile.birth_date = form.cleaned_data.get("birth_date") user.profile.location = form.cleaned_data.get("location") user.save() return redirect('profile') else: form = ProfileUpdateForm() context = { 'form' : form } return render(request, 'webside/profile_edit.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) image= models.FileField(upload_to='profile_image/', blank = True) def __str__(self): return self.user.username profile_edit.html '{% csrf_token %} {% for field in … -
solrpy‘s highlight response and django: how-to?
I would like to know to to implement solrpy's highlight response into an django based application. AS the highlight results are shown as a dictionary of dictionaries, How could I use those highlighted fragments? namely, How could I integrate the highlighted fragments into the template in order to substitute for corresponding content in original results? Thanks a lot -
Django finding the field name containing a string
If I have a list: my_list=['item1', 'item2', 'item3', 'item4'] My Model includes: class DataTwins(models.Model): set1a = models.OneToOneField(Dinners, on_delete=models.CASCADE) set1b = models.CharField(null=True, blank=True, max_length=10) set2a = models.CharField(null=True, blank=True, max_length=10) set2b = models.CharField(null=True, blank=True, max_length=10) set3a = models.CharField(null=True, blank=True, max_length=10) set3b = models.CharField(null=True, blank=True, max_length=10) ... Each item in my list will only be in the database once. In python how do i search my model to see which field the list item is in? I then need to store the field name, check the corresponding numbered field and store the data within it. -
(Re)Create table from "backup" table description
Issue Recently I came across an issue with a client, that has many solutions, but none was easy. This application uses Postgresql DB and there are two environments: dev and prod. At some point someone thought that it was a good idea to delete one of the tables (module_people_new) from prod without taking care of the FK and other issues that it could carry. Luckily, it was a module that was not very coupled with the application so the application kept working just fine. When I started working with this application, some functions were failing with integrity errors, so I found out it was because of that. I tried the same functions in dev and saw that they were working, so the table was there. Postgresql table description Now, I was wondering if there is a way to "recover" that table in prod, from the information I have in dev. I know that I could just get the table description and built a create query from there, but I was wondering if there is a more "direct" way. With table description I mean: db-> \d+ module_people_new Table "public.module_people_new" Column | Type | Modifiers | Storage | Stats target | Description … -
BeautifoulSoup django parsing
I need to get data/string from XML file with tag description. I have: <description>&lt;img src="https://www.somepicture.jpeg" align="left" hspace="8" width="400" height="200" /&gt; DESCRIPTION TEXT I WANT TO PARSE </description> Im using BeautifoulSoup4 and Django, also, previous I made new soup from which I parse one item. If I try "item.description.text" I'm also getting this img tag. How can I escape it, and get just desired description? Thanks -
Django ORM fetch data by 2 levels of foreign key relation
I have the following models: class Project(models.Model): name = models.CharField(max_length=300, unique=True) description = models.CharField(max_length=2000) class TemporaryUser(models.Model): username = models.CharField(max_length=400) project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='users' ) class QuestionSession(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='sessions', blank=True, null=True, default=None ) class Question(models.Model): # stores the main json object with all required information description = JSONField( max_length=10000, blank=True, null=True, default=None ) question_session = models.ForeignKey( QuestionSession, on_delete=models.CASCADE, related_name='questions', blank=True, null=True, default=None ) class Answer(models.Model): question = models.ForeignKey( Question, related_name='answers_list', on_delete=models.CASCADE) answer = models.CharField(max_length=500) answered_by = models.ForeignKey( TemporaryUser, on_delete=models.CASCADE, related_name='answers', blank=True, null=True, default=None ) In a nutshell, my app contains questions, session is a collection of questions, and a project is a collection of sessions. All users are unique per project. I can fetch all users and all answers within a specific project with the following: TemporaryUser.objects.all().filter(project__id=project_id) How can I do the same within a session? I don't really know how to do it, I need to filter users by session, is there a way how to do it with my relations? -
Custom Django Rest JWT Login
I'm trying to write custom jwt login view for django rest api authentication. But it doesn't work, and I don't know why.Could you help me to fix this code or put some example. Thanks in advance. my serializer: class LoginSerializer(serializers.Serializer): token = serializers.CharField(max_length=256) username = serializers.CharField(max_length=128) password = serializers.CharField(write_only=True, required=True, style={ 'input_type': 'password', 'placeholder': 'password' }) my view: from .serializers import TokenSerializer class UserLogin(APIView): """ POST login/ """ permission_classes = (permissions.AllowAny,) queryset = User.objects.all() def post(self, request, *args, **kwargs): username = request.data.get('username', '') password = request.data.get('password', '') user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) serializer = TokenSerializer(self.queryset, data={ 'token': jwt_encode_handler(jwt_payload_handler(user)), 'username': username, 'password': password, } ) if serializer.is_valid(): return Response(serializer.data) return Response(status=status.HTTP_401_UNAUTHORIZED) -
module 'django.db.models' has no attribute 'EmbeddedModelField'
I am connecting Django up to a MongoDB where there are embedded documents. I followed the documentation on https://djongo.readthedocs.io/docs/using-django-with-mongodb-data-fields/. However, I am recieving the error "module "django.db.models' has no attribute 'EmbeddedModelField" models.py from django.db import models from django import forms from datetime import datetime class Code(models.Model): code = models.CharField(max_length=3) quantity = models.IntegerField() purchasePrice = models.FloatField(default=1, blank=False, null=False) datetimeBuy = models.DateTimeField(default=datetime.now, blank=False, null=False) class Meta: abstract = True class Portfolio(models.Model): username = models.CharField(primary_key=True, max_length=65, default="", blank=False, null=False) codes = models.EmbeddedModelField(model_container=Code,) Stack trace Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x043D9ED0> Traceback (most recent call last): File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Python\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Python\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, … -
Django tasks with deadline date
So i got the model Task with a date it should be finished class Task(models.Model): end_date = models.DateTimeField(auto_now_add=False) ..... how can i compare the date in template that if deadline date is earlier than today then do something? -
django rest auth: user register with is_active=True
I'm creating an API using django-rest-auth. And I noticed the user is registered with is_active=True even before email verification is done in RegisterView. How can I override the default behavior properly? And I'm wondering why the library let the user reigiter with is_active=True. Is there a reason? -
Django: instance one field from form
I have a form (a regular one, not a ModelForm), which I need one of its fields to load initialized. I would need to do something like this: views.py def my_view(request): my_var = MyClass.objects.get(my_filter=my_value).a_var form = MyForm(my_form_field = my_var) I would need to initialize the value of one of the fields of MapeoForm. I only know how to populate a ModelForm with a class object instance so far. Take into account that this form has more than one field, but I need to load the form with only this field populated and the rest by default (blank). -
How to use for loops in Django to create a table
I am a beginner at Django and I am attempting to create a custom table using a html template called law.html. Within law.html I have the following code. <table class="table table-striped"> <thead> <tr> <th>Solicitor_Names</th> <th>Offices</th> <th>Addresses</th> <th>Primary_Role</th> <th>Secondary_Role</th> <th>Other_Role</th> <th>Other_Role_1</th> <th>Other_Role_2</th> <th>Other_Role_3</th> <th>Other_Role_4</th> </tr> </thead> <tbody> {% for name in all_data.Solicitor_Name %} <tr> <td>{{ name }}</td> <tr> {% endfor %} {% for office in all_data.Office %} <tr> <td>{{ office }}</td> <tr> {% endfor %} </tbody> The output produces the desired table headings perfectly. Also, the Solicitor_Name column is filled with the desired data. However, I fail in my attempt to place the Office data in the next column. Instead, the data continues to populate the cells under the Solicitor_Name column. How do I format the code so that I can get my desired output that looks like this? Solicitor_Name Offices Address John Orange LLP 123 Main St Bill Apple LLP 124 Bone St -
Django Automatically Update Records after a certain timespan
I have a model "Grade" which has one field: "name". I also have an instance of this Grade. i.e "Grade One". Is there a way in which I can automatically update that particular instance to "Grade Two" and all it's other related models after a given time span (Let's say one year), and then after another year change it to "Grade Three" and so on? -
Add marker by set lat and long inside popup (leaflet-django)
Now i'm working in django-leaflet project i have been successfully set up leaflet widgets inside form but i need to add marker by write lat and long, not by drawing like leaflet widget provides so if there are a way to customize leaflet widget form to be drawn marker by write the coordinates -
Track REST API calls using google analytics/
I want to track which resources are popular using the data from google analytics. Is this possible with google analytics? -
Open EDX - LMS : Unable to send verification email
I have a server setup for python 2.7. I have followed the below link for open edx setup and configuration. Click here After doing a lot of stuff, I have successfully run CMS and LMS on different domains. Everything is working except emails. When I registered from LMS, I didn't found verification mail. Because of that, I am not able to login to LMS system. I have added SMTP details in lms.env.json I have also replaced the console by smtp in aws.py, common.py I have also restarted all the services after doing this but none worked for me. Please help me to get out of this. -
Get Content of .doc-File
Hi i want to get a File from Dropbox. And get the Text as String. I am using Django I want a simple soultion from .DOC to String. I tryed to download and convert the file, but somehow nothing works. And i am not shure if the file uploads fails or the conversion or something else. The Error i get is 'tuple' object has no attribute 'seek' My Python Code is: def convertotxt(request): data = {} sfile = None sfile = request.GET['file'] output = urllib.request.urlretrieve( sfile, settings.MEDIA_ROOT+"\\doc\\temp.doc") print(output) try: document = Document(output) docText = '\n\n'.join([ paragraph.text.encode('utf-8') for paragraph in document.paragraphs ]) data["value"] = docText except Exception as e: data["value"] = str(e) return JsonResponse(data) My Js Code is: options = { success: function (files) { link = files[0].link.replace("dl=0", "dl=1") converttotxt(link) }, extensions: ['.pdf', '.doc', '.docx'], }; var button = Dropbox.createChooseButton(options); document.getElementById("container").appendChild(button); function converttotxt(file) { $.ajax({ url: '/music/songs/ajax/convertotxt', data: { 'file': file, }, dataType: 'json', success: function (data) { console.log(data) } }); } -
Getting an error 'function' object has no attribute '_meta' django 2.0
trying to use login and registration with Django custom user using AbstractUserModel Now getting this error during makemigrations I am using Django 2.0.7 and python 3.6.6 models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self,email,full_name,password=None,is_active = True,is_staff=False,is_admin=False): if not email: raise ValueError("Put an email address") if not password: raise ValueError("Input a password") if not full_name: raise ValueError("You must add your fullname") user= self.model( email=self.normalize_email(email), fullname=full_name ) user.set_password(password) user.staff = is_staff user.admin = is_admin user.active = is_active user.save(using=self._db) return user def create_staffuser(self,email,full_name,password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True ) return user def create_superuser(self,email,full_name=None,password=None): user = self.create_user( email, full_name=full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=50,unique=True) full_name = models.CharField(max_length=200,blank=True active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = UserManager() def __str__(self): return self.email def get_full_name(self): if self.full_name: return self.full_name return self.email def has_perm(self, perm, obj = None): return True def has_module_perms(self, app_level): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User User = get_user_model class UserAdminChangeForm(forms.ModelForm): password … -
Not to pass ID in URL - UpdateApiView
I want to make update using my API. For that i am passing id in URL which is pk. http://localhost:8000/api/manager/update/96 Where 96 is primary key. Now instead of passing id in url i want to pass id in body and update data. My url should look like this http://localhost:8000/api/manager/update Views.py class ManagerUpdateAPIView(APIView): def post(self, request, pk, *args, **kwrgs): user = get_object_or_404(User, id=pk) userprofile = get_object_or_404(UserProfile, user=pk) serializer1 = EmployeeRegisterSerializer(user, data=request.data) serializer2 = EmployeeProfileSerializer(userprofile, data=request.data) user_role = ACLRoles.objects.get(id=4) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() serializer2.save() return Response(status=status.HTTP_200_OK) print(serializer1.errors) print(serializer2.errors) return Response(status=status.HTTP_404_NOT_FOUND) Serializers.py class EmployeeProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = [ 'user_employee_id', 'user_phone', 'user_payroll_id', 'user_hire_date', 'user_pay_rate', 'user_salaried', 'user_excempt', 'user_groups', 'user_state', 'user_city', 'user_zipcode', 'user_status', ] class EmployeeRegisterSerializer(serializers.ModelSerializer): # userprofile = EmployeeProfileSerializer(read_only=True) class Meta: model = User fields = ['first_name','last_name', 'email',] How can i update data without passing id in url. -
LDAP authentication using django
Could anyone of you please help me to implement LDAP authentication using Django. I want to develop a web application which should allow users to access the application post LDAP authentication. I have coded the basic things but I get some failures. Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '4xkkb*m!&@^xzhkpe6#gxe@xeee0ug3q0h$@-)#lv8+0dqpid*' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'NewHandBook.apps.NewhandbookConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'HandBook.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'HandBook.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] Views.py from django.shortcuts import render from django.contrib.auth import authenticate, login from django.template import RequestContext from django.shortcuts import render_to_response def login(request): return render(request, 'login/login.html') def login_user(request): username = password = "" state = "" if request.POST: username = request.POST.get('username') password = request.POST.get('password') print(username, password) user = authenticate(username=username, password=password) if user is not None: login(request, user) state = "Valid …