Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Data not saving in models sequentally
Want to save data in sequence I am using react as front and I am trying to save data from an array to django backend model.Suppose I have array of length 5, I am saving 5 indexes separately in django model, but the problem is data is not saving in model in sequence, e.g: arr[0]=data1 arr[2]=data2 arr[3]=data3 but in model, It displays : id=1 data=2, id2=2 data=3, id3=3 data=1, I want to save in sequence,like data1,data2,data3 or data3,data2,data1 can also work,below is my code: for (let i=0;i<rowdata.length;i++){ console.log("rows",rowdata[i]); //1,2,3,4,5,6 payload={ product:this.state.productid, row_name:rowdata[i] // indexes data is 1,2,3,4,5,6 }; axios.post('http://127.0.0.1:8000/pharmacy/create_row/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) } django rest Response: { "id": 43, "row_name": "4", "product": 17 }, { "id": 44, "row_name": "1", "product": 17 }, { "id": 45, "row_name": "5", "product": 17 }, { "id": 46, "row_name": "2", "product": 17 }, { "id": 47, "row_name": "3", "product": 17 }, { "id": 48, "row_name": "6", "product": 17 } whereas it should be 1,2,3,4,5,6 (row_name) from top to bottom,but they are not in sequence How can I resolve it should save in like 1,2,3,4,5,6 or 6,5,4,3,2,1 both will work. -
Can anyone explain or suggest a tutorial to create a listView in android?
Can anyone explain or suggest a tutorial to create a listView in android? Here are my requirements: I should be able to dynamically add new elements by pressing a button. Should be simple enough to understand (possibly without any performance improvements or convertview, for instance) -
How to display field text instead of the ID for a model connected by a foreign key in Django?
I have a simple model (kit) connected by another model(client_id) with a foreign key, and also by a ManyToMany field. I have a form view for the kit model, in which user can create new kits, by selecting a few products, and then choosing which client it is made for. Problem is, the fields are being displayed correctly, but with only ID displayed, instead of their names. User does not know what is he selecting as he does not know the ID of all products or clients. How should I approach this ? I searched on SO but found nothing useful. 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) Current output -
Data Table functionalities are not working
I have tried all the orders of my css and js cdn files but still my data tables search option,entries and pagination functions are not working and this project is in django for dynamic data Base.html file <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Makerobos json data</title> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css"> <script> $(document).ready( function () { $('#Robos').DataTable(); } ); </script> </body> </html> my another table file where i have created table according to the datatable using thead and tbody {% extends 'robosapiapp/base.html' %} {% load dateformat %} {% block content %} <div class="container"> <table id="Robos" class="display"> <thead> <tr> <th>Username</th> <th>Email</th> <th>First Name</th> <th>Last Name</th> <th>Plan</th> <th>Date Joined</th> <th>Contact</th> </tr> </thead> <tbody> <tr> {% for x in data %} <td>{{x.username}}</td> <td>{{x.email}}</td> <td>{{x.first_name}}</td> <td>{{x.last_name}}</td> <td>{{x.plan}}</td> <td>{{x.date_joined|dateformat|date:"d/m/Y"}}</td> <td>{{x.profile.contact}}</td> </tr> </tbody> {% endfor %} </table> </div> {% endblock %} -
Static files not loading while using python3 manage.py runserver 0.0.0.0:8000 in my server
ive added the static root file in my setting.py and also done collectstatic but while loading using bind in my virtualenv and if try to access my page using ipaddress:8000 the static files is not loading it is showing "GET /static/images/image1.jpg HTTP/1.1" 404 77" error for all static files im attaching my settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static") before i was able load all static file without using any port by directly accesing ip address coz i have given the static directrey enter code herein my nginx conf file but now im not able to acces to that also please comment if any clarification -
I want to publish post in django interactive console
Hi I was using django interactive shell and I wanted to create new post as this code. post = Post.objects.get(title="Sample title") post.publish() but It doesn't work. actually, I was following tutorial I have already check code. It's definitely same and I've already imported timezone module. I can check whatever work or not as this code. Post.objects.filter(published_date__lte=timezone.now()) and this is my error message post.publish() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/cosmian/myvenv/my_site/blog/models.py", line 13, in publish self.published_date = timezone.now() TypeError: 'NoneType' object is not callable this is my manage.py file from django.db import models from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Detecting line breaks within Python/Django textarea fields
I have a textarea field in Django from which I want to detect line breaks. I can see that the line breaks are stored as reloading the page with the user input shows the breaks that the user inputted, but I can't detect them in Django/Python. When I look at the output from PostgreSQL I can see \r characters, but these don't seem to show up within the Python environment. I'd like to do something like this: text_blocks = text_area.split("\r") But this doesn't work and I suspect is naive. How can I detect these seemingly invisible line breaks within Python/Django? -
How to override the renderer_classes to send extra information in REST API
I have created the rest api for authentication of user, and in the response I am getting the token. I also want to add whether the user has staff permission or not, I have already got the information is serializers but I am not able to pass to the view. And I need to authentication whether user is active or not This part is not working at all. My serializer code : class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): """Validate and authenticate the user""" email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) #This part I am trying to authenticate whether the account is active or not if user is not None: if not user.is_active: msg = _('The password is valid, but the account has been disabled! ') raise serializers.ValidationError(msg, code='not_active') if not user: msg = _('Unable to authenticate with provided credentials') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user attrs['is_staff'] = user.is_staff #Here I am getting the user has permission of staff or not. return attrs And the views.py is : class CreateTokenView(ObtainAuthToken): """Create a new auth token for the user""" serializer_class = …