Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago - getting two entries in the database, one with null and other with all data captured
I have a form and am updating the database with the form entries. I see that there are two rows getting updated one with NULL entries and other with all data. There is something wrong in my view but I don't know what, please help. models.py class Metadataform(models.Model): Models = models.CharField(max_length=5000, blank=True) Device = models.CharField(max_length=500, blank=True) Document = models.FileField(upload_to='') views.py def submission(request): Models = request.POST["Models"] Device = request.POST["Device"] Error_Estimation = request.POST["Error_Estimation"] if request.method == 'POST': form = Fileuploadform(request.POST, request.FILES) if form.is_valid(): form.save() newdoc = Metadataform(Document = request.FILES['Document']) newdoc.save() return render(request, "home.html") else: form = Fileuploadform() There are two-row entries in the database. 1 row with NULL entries and the uploaded file link, another row with all the data and the file link -
Change Session Table Name and Customize Django Session Table
My problem: I'm trying to change the Django session table name from "django_session" to some other name as "User_session" What I tried: from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" I placed the above code in Project's __init__.py file. But I'm getting error as calling session before the Session middleware has been initialized. What I want: I need to change the django_session table name to some other table name and add few columns to that table. NOTE: I'm using Django 2.1.11 and Python 3.7 Kindly help me to get rid off this problem. -
gunicorn not starting (code=exited, status=1/FAILURE) error
not able to start gunicorn in my server sock file is not creating in my project directry Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2019-09-16 09:35:37 UTC; 2s ago Main PID: 22932 (code=exited, status=1/FAILURE) Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [INFO] Starting gunicorn 19.9.0 Sep 16 09:35:31 django gunicorn[22932]: [2019-09-16 09:35:31 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:32 django gunicorn[22932]: [2019-09-16 09:35:32 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:33 django gunicorn[22932]: [2019-09-16 09:35:33 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:34 django gunicorn[22932]: [2019-09-16 09:35:34 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:35 django gunicorn[22932]: [2019-09-16 09:35:35 +0000] [22932] [ERROR] Retrying in 1 second. Sep 16 09:35:36 django gunicorn[22932]: [2019-09-16 09:35:36 +0000] [22932] [ERROR] Can't connect to Sep 16 09:35:37 django systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Sep 16 09:35:37 django systemd[1]: gunicorn.service: Unit entered failed state. Sep 16 09:35:37 django systemd[1]: gunicorn.service: Failed with result 'exit-code'. -
I am trying to install django in my windows system with the command "conda install django" , anaconda python3 is already installed and working fine
while installing the django I am getting this error "TypeError: LoadLibrary() argument 1 must be str, not None" and a very long exception, how can I solve this as it comes even when I am creating a virtual environment. I am learning Django and it was my first step so please answer accordingly. -
How to write a mixin in this case in order not to repeat the code
Django==2.2.5 There are three levels logically nested one inside another. The problem here is the repeating code in save method. Could you help me create a mixin not to repeat myself. class Level_1(PhraseMixin, ArchivedMixin, models.Model): def save(self, *args, **kwargs): """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_2_set = self.level_2_set.all() for level_2_obj in level_2_set: level_2_obj.archived = True level_2_obj.save() super(Level_1, self).save(*args, **kwargs) class Level_2(ArchivedMixin, PhraseMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_1, verbose_name="Level 1", on_delete=models.CASCADE) """ If this level is archived, then make all sublevels archived too. """ if self.archived: level_3_set = self.level_3_set.all() for level_3_obj in level_3_set: level_3_obj.archived = True level_3_obj.save() super(Level_2, self).save(*args, **kwargs) class Level_3(PhraseMixin, ArchivedMixin, WhereMixin, ValidateParentMixin, models.Model): parent_level = models.ForeignKey(Level_2, verbose_name="Level 2", on_delete=models.CASCADE) -
Django vs Flask. Which one should I use?
So I have recently decided to learn Django, and so far I am going pretty well. However, I have also heard Flask is good. Which one is better for a beginner like myself, who is only making small sites at the moment? Thank you for any help -
Redirection and edge case handling
I am trying to run some compute engine and google cloud dns functions when a form is submitted. I want to know how to do following things: 1) If every thing has been done properly then redirect to newly created sub domain. 2) If some error arises then redirect visitor to a default page stating your instance cannot be created.Please try again. I do not know how to redirect to a url which itself is being created during form save. class Company(models.Model): registrant = models.CharField("Name of the Registrant",max_length=120,null=True,blank=False) company = models.CharField("Name of the company",max_length=120, null=False) email = models.EmailField("Official Email Id of registrant",null=True,blank=False) designation = models.CharField("Designation at the company",max_length=120,null=True,blank=False) size = models.PositiveIntegerField("No. of employees",validators=[MinValueValidator(1)]) subdomain = models.CharField(max_length=120,null=True) registration_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.company class CompanySignupForm(forms.ModelForm): class Meta: model = Company fields = ('company','registrant','email','designation','size') def clean_email(self): email = self.cleaned_data.get("email") qs = User.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError("Cannot use this email. It's already registered") return email def clean_company(self): company = self.cleaned_data.get("company") qs = Company.objects.filter(company__iexact=company) if qs.exists(): raise forms.ValidationError("This company is already registered") return company def save(self,commit=True): company = super(CompanySignupForm,self).save(commit=False) email = self.clean_email() company.company = self.clean_company() company.registrant = self.cleaned_data.get('registrant') company.designation = self.cleaned_data.get('designation') company.size = self.cleaned_data.get('size') company.save() name = company.company.lower() + str(generate_random()) company.subdomain = name+".mysite.com" … -
How to get the instance of current plugin object in class-based view
I am developing a plugin for django-cms. Right now, I have a class BaseMyPlugin extending CMSPlugin class and I need to get an attribute base_attr from that class in class-based detail view (MyDetailView) context. What should I import (for modules) or override (for functions) for my view? The attribute I want to get is set in runtime so I have to get the instance. It is reachable in the template context because there is an global instance of plugin. But in the view context, I can not get such an instance. I have tried the following: Import BaseMyPlugin class in the view context. Failed because it was not the instance. Override render_to_response/get_context_data/get_object methods in MyDetailView class. Failed because the parameters of these methods didn't contain the base_attr attribute. Code for my view: class MyDetailView(DetailView): ``` I want to get the BaseMyPlugin.base_attr in this view ``` view_attr='to be set accouding to BaseMyPlugin.base_attr' Code for my CMSPlugin class: class BaseMyPlugin(CMSPlugin): # target attribute base_attr='some value set in runtime' I need to get the base_attr anyway to set view_attr in view in runtime. Could you help me plz? -
Fixing Migrations and Django migrating error
I wrote migration to my Django project and then ı applied ' make migrations and migrate' commands.For django there is no problem . But when ı run project django.db.utils.ProgrammingError: column providers_providerhotel.is_active does not exist LINE 1: ...hotel"."hash", "providers_providerhotel"."stars", "providers... ^ Exception ignored in: <function GEOSGeometry.__del__ at 0x1107fb830> Traceback (most recent call last): ImportError: sys.meta_path is None, Python is likely shutting down I think there is problem for adding column to database from my model.And for django , there is no problem it alerts ' ı wrote it to database there is no issue'. but it doesn't. Can anybody help to solve it ? model.py is_active = models.NullBooleanField() 003_providerhotel_is_active.py +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2019-09-12 07:48 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('providers', '0002_auto_20170203_0707'), + ] + + operations = [ + migrations.AddField( + model_name='providerhotel', + name='is_active', + field=models.NullBooleanField(), + ), + ] providers/init.py 'is_active': None, } -
I am confused in connecting postgresql with django
this is my first time to connect with any database i am using POSTGRESQL as database but i am stuck totally when i save signup information it not showing in the database table that i have created in pgadmin This is settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'accounts', 'USER':'postgres', 'PASSWORD':'****', 'HOST':'localhost' 'PORT':'5432' } } -
How to fix object representaions in django admin page on `LogEntry` model. django 2.2
I've added a code in my view to log every add action in my add_new_staff page. However, everytime I add a user on that page, the columns object_id and object_repr in LogEntry model in admin page gets this weird data representations(objects encircled with black pen): The objects encircled with red pen are the users I added on the django admin page, and it didn't get weird representations. These are the code I added in my add_staff_view : log = LogEntry.objects.log_action( user_id=request.user.id, content_type_id=ContentType.objects.get_for_model(User).pk, object_id=User.id, # or any field you wish to represent here object_repr=repr(User.username), action_flag=ADDITION, # assuming it's a new object change_message=message,) # a new user has been added log.save() How can I fix this problem? Any help would be really appreciated. -
Django template re-rendering
So I have a django DetailView that I can easily render by getting all the data that I need from get_context_data in my class based view. But the problem is that each time to render this template I would need to choose a date in this template, get the date somehow and then re-render that same template from the date picked. I've been googling how to make this happen, there are something I could maybe do with AJAX, but maybe there is something easier to try, because I have little to no experience with AJAX/JS stuff class PlaceDetailView(LoginRequiredMixin, PermissionCheckMixin, PlaceViewMixin, DetailView): template_name = "places/place_detail.html" def get_context_data(self, **kwargs): context = super(PlaceDetailView, self).get_context_data(**kwargs) place = context.get("object") contract = Contract.objects.filter(pk=place.id).first() context["renter"] = User.objects.filter(pk=contract.renter_id).first() now = timezone.now() meters = MeterInstallation.objects.filter(places=place.id) context["active_meters"] = meters.filter(active_until__gte=now) context["old_meters"] = meters.filter(active_until__lt=now) context["services"] = ServiceTask.objects.filter(place=place) # Need to add more context values from more models, but the date has to be given, how? return context place_detail_view = PlaceDetailView.as_view() <div class="tab-pane fade show active" id="values" role="tabpanel" aria-labelledby="values-tab"> {% if values %} <div class="table-responsive-sm"> <table class="table small"> <thead> <tr> <th scope="col">#</th> <th scope="col">Values</th> </tr> </thead> <tbody> {% for value in values %} <tr> <th scope="row">{{ forloop.counter }}</th> <!-- todo add needed values … -
Use custom js file for FilteredSelectMultiple widget
I am struggling while trying to include FilteredSelectMultiple widget to user form. I finally managed to add it make make it show on regular user form (detailed way I did it in my previous question), but now I need to customize it a bit (resize, provide translations to buttons, tool-tips and similar things). I managed to find a similar question in this forum and determined that I need to edit SelectFilter2.js file (I do not know js, but managed to change required label/button text in it). Also will edited styles.css adjust widget size. And will put these files in my_app/static/ directory. But I cannot figure out - how to make django look at these custom files instead of original ones? Sorry if it noobish question, but please point me to the right direction, since I could not find any related material to it. My urls.py code: from django.urls import path from . import views from django.conf.urls import url from django import views as django_views urlpatterns = [ url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] My forms.py code: from django.contrib.admin.widgets import FilteredSelectMultiple class DrgSkaiciuokle(forms.Form): bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True, label="Bazinė kaina", initial= BazineKaina.objects.get(), ) def clean_bazine_kaina(self): bazine_kaina = self.cleaned_data['bazine_kaina'] return bazine_kaina drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), … -
Copying .csv file located on Heroku server to local drive
I have a Python/Django web application deployed to Heroku that writes information to a .csv file. Once the file has been written I want to pull it down from the Heroku server to the users local drive. I don't need to persist the file anywhere and so I am avoiding using S3 or storing in the database. I have used the Heroku "ps:copy" command which works but surely this would mean the user would need the Heroku CLI installed on their machine for this to work? Is there any other way? Thanks -
how to call class based view from another view, with parameters?
Say you used to call login_view(request, arg1, kwarg1='foo') Are you supposed to call LoginView.as_view()(request, arg1, kwarg1='foo') Additionally, In Drf, correct format is MyViewSet.as_view({ 'get': 'method_name' })(request, arg1, kwarg1='foo') And I wonder where the difference come from? -
How to use multiple forms in Django 2.1?
Sorry for asking similar questions, but other similar questions/answers do not help me with Django 2. Question: I have two actions, one is to show some data as a table. In the second form I edit this data and will save it as a table using django in the database. Here is some code: in simple_upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile" value="formOne"> <button class="btn btn-primary" type="submit">Upload</button> </form> The second form: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="mytable" value="formTwo"> <table class="table" border="1" id="tbl_posts"> <thead> <tr> ... </tbody> </table> <input type="submit" value="Submit"> </form> in views.py def simple_upload(request): if request.method == 'POST': ... if request.is_ajax(): return render(request, 'project/simple_upload.html', {'section': 'project', 'lines': zipped}) return render(request, 'project/list.html', {'section': 'project', 'lines': zipped}) return render(request, 'project/simple_upload.html') in urls.py: urlpatterns = [ ... path('', views.simple_upload, name='list'), ... ] in list.html: ... {% include "project/simple_upload.html" %} ... In this case only the first form works, the second one fails. Question 1: Can I do "if request.method == 'POST' and 'formOne' in request.POST:", I try but it does not react at all. Question2: How can I write two methods and assign them using urls.py? -
How to Implement Chained Dropdown List with Django with multiple fields?
I have created a form for a model(kit) which is connected by two different models by foreign key and manytomany field. Now, I want the form to automatically prefill data in the form fields as soon as an option is selected. This is my code. Code models.py # Parent model connected with both models class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) kit_info = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product_id = models.ManyToManyField(Product, related_name='kit_product') quantity_per_kit = models.IntegerField(default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='kit_owner') # connected by foreign key class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) # connected by many to many field class Product(models.Model): product_id = models.IntegerField(default=0) product_name = models.CharField(max_length=255, default=0) product_short_code = models.CharField(max_length=255, default=0) product_description = models.CharField(max_length=255, default=0) template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2 class="mb-3">Add a new Kit</h2> <div class="row"> <div class="col-md-6 col-sm-8 col-12"> <form method="post" novalidate> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'employee:products_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </form> </div> </div> {% endblock %} I followed this guide How to Implement Dependent/Chained Dropdown List with Django , and I want to expand this to have many fields being filled instead … -
Save rewrite method prevent data loss due to unsaved related object
I got the next models - Vacancy, Requirement, and Responsibility. Last two models related to Vacancy by foreign key. I want to rewrite save() method to create a page for every Vacancy, but there is an error on super(Vacancy, self).save(*args, **kwargs) line - save() prohibited to prevent data loss due to unsaved related object 'vacancy'. The default save works well, but begin to drop an error while I tried to rewrite it, why? class Vacancy(models.Model): title = models.CharField(max_length=100) short_description = models.CharField(max_length=300) slug = AutoSlugField(always_update=True,populate_from='title', unique=True) date_created = models.DateField(default=datetime.date.today()) background = models.ImageField(upload_to='uploads/images/') def __unicode__(self): return self.title class Meta: verbose_name_plural = 'Vacancy' def __str__(self): return self.title def save(self, *args, **kwargs): try: user = User.objects.filter(is_superuser=True)[0] vacancyPage = Title.objects.get(slug="vacancies",page__publisher_is_draft=True).page page = create_page(self.title, 'fullwidth.html', 'en', parent=vacancyPage, in_navigation=True, published=True) placeholder = page.placeholders.get(slot="content") add_plugin(placeholder, 'CMSVacancyPlugin', 'en', vacancy=self) super(Vacancy, self).save(*args, **kwargs) publish_page(page, user, 'en') except Exception as e: print(e) class Requirement(models.Model): text = models.CharField(max_length=250) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE) class Responsibility(models.Model): text = models.CharField(max_length=250) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE) -
csv File in Django Server
The following line gets saved in the CSV file alongwith form data onn every submission. csrfmiddlewaretoken,p3amPwSQ2WGU5KfxMWlc9vzumfBqoc9xmnBT6VrK3dNoo00mZRIlq9OnwbFt04qu How to correct this ? -
FOREIGN KEY constraint failed with Custome Model in Django
I customed the User in Django following the code providing by the Documentation (for the models.py and the admin.py) I have a custom User using his email to auth (and not the username) I can create new user but I cannot delete them in the django admin panel. When I try i go this error message: FOREIGN KEY constraint failed models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True … -
Retrieving user details using username from extended User Model in Django
I'm trying to retrieve the details of a user using the username test from an extended User model in Django. But I am unable to do it. It's giving me the error: ValueError at / invalid literal for int() with base 10: 'test' Following is my code: models.py class DocchainUser(models.Model): docchainuser_name = models.OneToOneField(User, on_delete = models.CASCADE, default='x') address = models.CharField(max_length=64,unique=True) def __str__(self): return self.address views.py def my_users(request): if request.method == 'POST': username = request.POST.get('username') user = authenticate(username=username) if user: if user.is_authenticated: signBool = signatureAuth(username) if signBool == 'AUTHENTICATED': login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0]) return HttpResponseRedirect('/dashboard') .... And the signatureAuth() now: def signatureAuth(username): userModel = DocchainUser.objects.filter(docchainuser_name=username) address = userModel.address print(address) ... I'm retrieving the user details using username: test in signatureAuth() method. test is already present in my User as well as DocchainUser model. -
django tutorial: testcase failed to create testuser on oracle express database
I am following the tutorial from django a link. When i trying to test the testcase using "py manage.py test polls" i get this: C:\Users\user\Documents\user_django_projects\mysite>py manage.py test polls Creating test database for alias 'default'... Failed (ORA-01543: tablespace 'TEST_SYSTEM' already exists) It appears the test database, test_system, already exists. Type 'yes' to delete it, or 'no' to cancel: yes Destroying old test database for alias 'default'... Creating test user... Failed (ORA-65096: invalid common user or role name) Got an error creating the test user: ORA-65096: invalid common user or role name django can't seem to create a temp user on my local oracle express database. Can someone help me sort it out? -
Settting up logger to send emails to address different than admins
In the settings file I have a logger set up to send any errors to ADMINS which is the default behavior. Here: LOGGING = { 'handlers': {'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler'} 'loggers': {'django.request': {'handlers': ['mail_admins'], 'propagate': True}} } But I would like to set up a second logger to log a different type of errors and email should be sent to a different address. I have my own logging function which writes to a file. Basically I want to send an email to that other address instead. How can I do this? -
How to override the db_table in model for a 3rd-party packages?
I want to override the "db_table" in models.py for 3rd-party packages. Therefore, the database table name could display what I need. models.py from admin_honeypot.models import LoginAttempt as oldLoginAttempt_Model class LoginAttempt_Model(oldLoginAttempt_Model): oldLoginAttempt_Model._meta.db_table = 'NEW-TABLE-NAME' class Meta: proxy = False app_label = 'admin_honeypot' db_table = 'NEW-TABLE-NAME' admin.py from admin_honeypot.admin import LoginAttemptAdmin as oldLoginAttempt_Admin from admin_honeypot.models import LoginAttempt as oldLoginAttempt_model from .models import LoginAttempt_Model admin.site.unregister(oldLoginAttempt_model) @admin.register(LoginAttempt_Model) class LoginAttempt_Admin(oldLoginAttempt_Admin): pass then, I do python manage.py makemigrations database table name still on the old version. -
Please help me with my skill recommendation system by machine learning code?
https://github.com/rishabhrana54/skillrecommendation hey!! i have a some issue with this skill recommendation in Views.py. you can check in by running this project In 'submitPofile(Req)' of views.py its not able to recommend me right language. please help me if anyone can