Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: I want a button that will perform calculations on form values until user satisfied, then click the submit button to save everything
I have my program working where user enters values in several form fields, name, address, phone, etc plus some numeric values. I do some calculations in the views.py file which populates other fields (after submit button) and saves the entire record including calculated fields to the db table. Although the calculated values don't get a chance to appear on the form, they are saved correctly in the db. Currently, all the form fields are being saved to the same table. I can split this up if necessary for my requirement below. I believe I've set up the Django/python models,forms,views,URLs, and the HTML files correctly so far. What I need is a "calculate" button for the user to enter some values in the form, click the calculate button, which will do the calculations and populate the respective fields and display on the form. The user can continue to change the values and click the calculate button until satisfied with the all the values. A kind of "what-if" scenario. Then click the submit button to save all the form field values to the user record in the table. The best analogy would be a loan calculator, where the user enters the loan … -
AttributeError: 'NoneType' object has no attribute 'save' python-django
I have a User model. when I go to the signup page and add user details. it gives an error " AttributeError: 'NoneType' object has no attribute 'save' " when I reload the error page it gives another error " 'NoneType' object has no attribute 'save' " Here is my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone # Create Your Models Here. class UserManager(BaseUserManager): def _create_user(self, username, password, is_staff, is_superuser, **extra_fields): if not username: raise ValueError('Users must have an username address') now = timezone.now() username = self.model.normalize_username(username) user = self.model( username=username, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, username=None, password=None, **extra_fields): return self._create_user(username, password, False, False, **extra_fields) def create_superuser(self, username, password, **extra_fields): user = self._create_user(username, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_username(self): return self.username class user_type(models.Model): is_service = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_admin … -
Writing python-written SQL code to interact with Django database
Currently, I'm having a Django project that has an API to let users interact with my database. This project is deployed on Google App Engine, connecting to Cloud SQL (MySQL core). I would like to add some SQL-based functions, written in python, into this project to perform tasks on the database, such as querying, predicting, calculating, etc. automate (1) Currently, I'm thinking of using mysql.connector.connect() to get the database from the Cloud SQL like below mydb = mysql.connector.connect( host="/cloudsql/project_name:region_name:instance_name", user="username", password="password", database="database", port = "3306", # port should not be specified in deployment? ) and after getting the database, I can do whatever SQL logic, written in Python. Could anybody suggest a way to achieve these? Thanks a lot. -
how to set the default value of a model field in django as a parameter taking function?
It says TypeError: getimg() missing 1 required positional argument: 'self' class Forimg(models.Model): products = models.OneToOneField(Products, on_delete=models.CASCADE, primary_key = True) def getimg(self): item = self.products.Product_description page = requests.get(f'https://www.google.com/search?tbm=isch&q={item}') soup = BeautifulSoup(page.text, 'lxml') item_head = soup.find('img',class_='t0fcAb') return item_head['src'] image = models.ImageField(upload_to = 'img/', width_field= 30, height_field = 40,default=getimg) def __str__(self): return self.products.Product_description -
Unresolved reference 'views' in django
urls.py from django.contrib import admin from django.urls import path, include from crudapplication import views urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp), path('show', views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] ModuleNotFoundError: No module named 'webapplication.crudapplication' program structure hierarchy -
Why is my css file not connecting to the html?
For some reason, my CSS code is not connecting with my HTML. I am not sure why this is happening what to do to fix the issue. home.html should be connecting to the CSS file main.css. I have added the static file block to the base.html and home.html since home extends base but the issue is still occurring. base.html {%load static%} <!DOCTYPE html> <html> <head> <title>TweetyBird</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type= "text/css" href="{% static 'css/main.css' %}" > <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">TweetyBird</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Company Registration</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Company Sign in</a> </li> <li class="nav-item"> <a class="nav-link" href="/search">Search by Tweet <span class="sr-only">(current)</span></a> </li> </ul> </nav> </div> </head> {%block staticfiles%} {% endblock %} </nav> {% block content %} {% endblock %} </body> </html> home.html {% extends 'base.html' %} {%load static%} {%block staticfiles%} <link rel="stylesheet" type= "text/css" href="{% static 'css/main.css' %}" > {% endblock %} <body> {% block content %} … -
Django Rest Framework save() method not saving
I have a Django Rest Framework class using APIView to implement a post() and delete() endpoint. The code is below, and an explanation of it is beneath that: class ReactedPostDetail(APIView): def post(self, request, uuid_field, format=None): data = request.data.copy() post = Post.objects.get(uuid_field=uuid_field) data["profile"] = Profile.objects.get( user=request.user).pk data["post"] = post.pk data["post_uuid"] = uuid_field serializer = ReactionSerializer(data=data) if serializer.is_valid(): reaction = serializer.validated_data["reaction"] if reaction == "R1": post.reaction_1_count += 1 elif reaction == "R2": post.reaction_2_count += 1 elif reaction == "R3": post.reaction_3_count += 1 elif reaction == "R4": post.reaction_4_count += 1 post.save() serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, uuid_field, format=None): logged_in_user_pk = Profile.objects.get(user=request.user).pk post = Post.objects.get(uuid_field=uuid_field) reactedPost = Reaction.objects.get(profile=logged_in_user_pk, post=post.pk) reaction = reactedPost.reaction if reaction == "R1": Post.objects.get(uuid_field=uuid_field).reaction_1_count -= 1 elif reaction == "R2": Post.objects.get(uuid_field=uuid_field).reaction_2_count -= 1 elif reaction == "R3": Post.objects.get(uuid_field=uuid_field).reaction_3_count -= 1 elif reaction == "R4": Post.objects.get(uuid_field=uuid_field).reaction_4_count -= 1 post.save() reactedPost.delete() return Response(status=status.HTTP_204_NO_CONTENT) Explanation: Models: I have a Post model and Reaction model. The Post model has a counter for each kind of reaction (there are 4 total, each is "R1", "R2", etc.). The Reaction model stores the type of reaction, the ID of the user who made that reaction, and the post the reaction was made on. … -
Django relation "personindustry" does not exist
I have a below model, class PersonIndustry(DFModel): person = models.ForeignKey( Person, models.DO_NOTHING, blank=True, null=True) industry = models.CharField(max_length=50, blank=True, null=True) class Meta: db_table = ‘person_industry' My postgres database contains person_industry table. When I registered this model in admin site it is giving me below error, ProgrammingError at /admin/apis/personindustry/ relation "personindustry" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM “personindustry" I am quite confuse why it is searching for personindustry instead of person_industry. Please advise. -
Django Allauth Not Associating gmail accounts directly
I have one registration page in my project in which user can create his account. I want such that if user's email address is of Google then it should autoconnect(associate) his/her account. But allauth is not doing so. Even i registered via gmail I have to go to /accounts/social/connections and manually add that, then only i can login via my gmail. If you have any solution pls. tell me. -
Django admin need to add reverse FK to admin site
I have below two models, class Person(models.Model): name = models.CharField(unique=True, max_length=200) nationality = models.TextField(blank=True, null=True) profession = models.TextField(blank=True, null=True) avatar = models.TextField(blank=True, null=True) active_scraping = models.BooleanField(blank=True, null=True) vuln_score = models.FloatField(blank=True, null=True, default=None) date_of_birthday = models.DateField(null=True, blank=True, verbose_name='Date of birth', help_text=date_help_text) gender = models.CharField(max_length=50, blank=True, null=True) date_of_death = models.DateField(null=True, blank=True, help_text=date_help_text) description = models.TextField(blank=True, null=True) wiki_names = ArrayField(models.CharField(max_length=200), blank=True, null=True) reviewed = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True, help_text=datetime_help_text) class PersonIndustry(DFModel): person = models.ForeignKey( Person, models.DO_NOTHING, blank=True, null=True) industry = models.CharField(max_length=50, blank=True, null=True) class Meta: db_table = 'person_industry' I have an admin page for Person with all the fields in model. I need to add Industry for each person as a read only field. I tried inline and tabularinline but I am doing something wrong. I am not sure how it can be done. Please advise. -
"Unique constrainted failed" problem when running migrations
I have been tryed to change a django model by applying and running migrations but I have been getting this error django.db.utils.IntegrityError: UNIQUE constraint failed: new__startup_home_mates.user_id How can this error be fixed? I have already investigated a lot but I have found nothing that fits my situation. I have already tried to use RenameField and AlterField directly from the migrations file and it is still not working maybe I was doing it wrong. models.py class Mates(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True) users_requests = models.ManyToManyField(User, related_name="users_requests") req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) If you need to see more code please let me know:) -
Why doesn't user deletion work in Django, working on AWS EC2?
So I've deployed my Django project with AWS EC2. I'm using Ubuntu OS and Nginx. Also, I'm using Django's built-in authentication system for registration. I have a test user whom I'd like to delete now. So in 'Authentication' -> "User" in Django admin, I selected the user and tried deleting it. But then it returned an error, saying TypeError at /admin/auth/user/ : __str__ returned non-string (type tuple) Since I'm using the built-in authentication, I have not created any model regarding it. What do you think can be the problem? Thank you very much in advance :) -
Django 2FA OTP And Recaptcha v3 On The Admin Login Page
I want to secure the admin login page as much as possible by adding 2FA django-otp and recaptcha v3 validation together. I was able to get recaptcha v3 to show up on the admin page and it seems to validate but as soon as I add admin.site.__class__ = OTPAdminSite to urls.py, the django-otp login page takes over and my custom login page and form disappears. When I try to add {{ form.otp_token }} and {{ form.otp_device }} to my overridden project/templates/admin/login.html file, it does not show the form fields for django-otp. How do I get the two of them to work together? project/templates/admin/login.html: <form action="{{ app_path }}" method="post" id="login-form">{% csrf_token %} <div class="form-row"> {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} </div> <div class="form-row"> {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} <input type="hidden" name="next" value="{{ next }}"> </div> {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} <div class="submit-row"> <input type="submit" value="{% trans 'Log in' %}"> </div> <script nonce="{{request.csp_nonce}}" src="https://www.google.com/recaptcha/api.js?render=PUBLIC"></script> <script nonce="{{request.csp_nonce}}"> grecaptcha.ready(function() { var grecaptcha_execute = function(){ grecaptcha.execute('PUBLIC', {action: "/admin/login/"}).then(function(token) { document.querySelectorAll('input.django-recaptcha-hidden-field').forEach(function (value) { value.value … -
Notifications in Django
What's the best way to build daily browser notifications into a Django app? I've tried django-webpush but it hasn't worked for me. -
Passing dyanmic querysets to Django template
I am trying to pass a dynamic queryset from views.py to my django template (company_detail.html) based off whether there are notes of a particular "note type." EXAMPLE IMAGE I have a "notes" model which is related to "Company" model, as shown: models.py class Company(models.Model): family = models.ForeignKey(Family, on_delete=models.CASCADE) type = models.ForeignKey(Type, models.CASCADE) name = models.CharField(max_length=200) phone = PhoneField(blank=True) email = models.EmailField(blank=True, max_length=100) address = AddressField(null=True, blank=True, on_delete=models.CASCADE) history = HistoricalRecords() class Notes(models.Model): NOTE_CHOICES = [ ('sales_structure', 'Sales Structure'), ('product_prefs', 'Product Preferences'), ('personnel', 'Personnel'), ('misc', 'Miscellaneous') ] account = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='notes') note_type = models.CharField(max_length=50, choices=NOTE_CHOICES) note_text = models.TextField(max_length=300) history = HistoricalRecords() My view uses django.views.generic.base.View as follows: views.py class CompanyDetail(View): def get(self, request, *args, **kwargs): company = get_object_or_404(Company, pk=self.kwargs.get('pk')) contact_table = ContactTable(Contact.objects.filter(account=self.kwargs.get('pk'))) notes = Notes.objects.filter(account=self.kwargs.get('pk')) note_types = [] for type in Notes.NOTE_CHOICES: text = type[1] notes_sub = notes.filter(note_type=type[0]) quant = notes_sub.count() if quant > 0: note_types.append((text, quant, notes_sub)) notes_form = NoteForm(account=company) return render(request, 'companies/company_detail.html', {'company': company, 'notes': notes, 'note_types': note_types, 'note_form': notes_form, 'contact_table': contact_table }, ) Which is passed to template: <h3>Account Notes</h3> <div class="accordion" id="NotesAccordion"> {% for type in note_types %} <div class="card"> <div class="card-header" id=Heading_{{ type.0 }}> <h2 class="mb-0"> <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target=#{{ type.0 }} … -
Can't Get Event To Fire On Select Box Change
I have a $(document).ready(function() function on this page which fires successfully (so my javascript is loading successfully). I am trying to fire an event when my select box is changed, but cannot get it to fire at all (even when I make it a click event). This is in Django Admin, so I cannot easily add an id to the element (I'm sure it's not that difficult but I can't find how). This is the element I'm trying to listen for: <select name="base_module" required="" id="id_base_module"> These are a few things I've tried: var test = document.querySelector('[name="base_module"]'); $(test).click(function(){ console.log("success") }); $(#id_base_module).click(function(){ console.log("success") }); $('select#id_base_module').change(function(){ console.log("success") }); Any help setting an event listener on this element which will be fired when the item in the select box is changed would be appreciated. Thank you. -
Getting operational Error while processing django models
Kept getting "Operational-error" message while trying to complete my first app model using Django administration. Made some changes on my terminal & code editor but still yields same error message The error loads up once I hit the save button. Please, what could be the solution? Here is the code on sublime text editor Same with this, after importing -
Python - CSV sniffer on InMemoryUploadedFile
def post(self, request, *args, **kwargs): uploaded_file = request.FILES['file'] if len(uploaded_file) != 0: try: df = pd.read_csv(uploaded_file) id = str(uuid.uuid4()) read_file = uploaded_file.read(1024) if not csv.Sniffer().has_header(read_file): df = pd.DataFrame(df.values, columns=[n for n in range(len(df.columns))]) df.to_csv(f'{TRAIN_FILES}/{id}.csv', index=False) except Exception as e: return JsonResponse({'msg': str(e)}, status=500) return JsonResponse({'msg': id}, status=200) else: return JsonResponse({'msg': 'File is empty'}, status=500) I have this code for uploading a csv, I'm trying to check if the csv has a header using csv.Sniffer, but .has_header complains about it coming in as bytes. What's the proper way to sniff InMemoryUploadedFile? I also realize that checking if a csv is valid using both sniffer and pandas is less than ideal so if anyone has any suggestions I'm open to it. -
Travis showing 'No other branches for this repository'
I am using Travis for the first time and I have enabled Travis for my project in Travis website and I was looking for the builds and I found this above message No other branches for this repository .travis.yml language: python python: - "3.7" services: - postgresql install: pipenv install script: - python manage.py test github link -
Cannot resolve keyword 'result' into field. Choices are: id, image_profile, user, user_id
i'm new to Django and i am trying to create a profile update form. I get the following error when trying to update my profile: Cannot resolve keyword 'username' into field. Choices are: id, image_profile, user, user_id Here is my models.py from django.db import models from django.shortcuts import render, redirect from django.contrib import messages from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from django.utils.text import slugify from django.conf import settings class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image_profile = models.ImageField(upload_to='media/profilepics', null=False, blank=False) def __str__(self): return f'{self.user.username} Profile' class Profile_update(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=50, null=False, blank=False) image_profile = models.ImageField(upload_to='media/profilepics', null=False, blank=False) Here is my forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] class ProfileAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Profile fields = ['user', 'password'] def clean(self): if self.is_valid(): user = self.cleaned_data['user'] password = self.cleaned_data['password'] if not authenticate(user=user, password=password): raise forms.ValidationError("Invalid login") class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['user', 'image_profile'] def clean_user(self): if self.is_valid(): username = self.cleaned_data['user'] try: profile = Profile.objects.exclude(pk=self.instance.pk).get(username=username) except Profile.DoesNotExist: return … -
How to have two types of users on the site: Buyers/Sellers
I am new to Django. I'm currently trying to create two users on the site which are buyers/Sellers. How to implement the model is an issue. Also whether to use CustomUserModel and the Profiles. Thanks in Advance. -
Django ORM how to get raw values grouped by a field
I have a model which is like so: class CPUReading(models.Model): host = models.CharField(max_length=256) reading = models.IntegerField() created = models.DateTimeField(auto_now_add=True) I am trying to get a result which looks like the following: { "host 1": [ { "created": DateTimeField(...), "value": 20 }, { "created": DateTimeField(...), "value": 40 }, ... ], "host 2": [ { "created": DateTimeField(...), "value": 19 }, { "created": DateTimeField(...), "value": 10 }, ... ] } I need it grouped by host and ordered by created. I have tried a bunch of stuff including using values() and annotate() in order to create a GROUP BY statement, but I think I must be missing something because in order to use GROUP BY it seems I need to use some aggregation function which I don't really want to do. I need the actual values of the reading field grouped by the host field and ordered by the created field. This is more-or-less how any charting library needs the data. I know I can make it happen with either python code or with raw sql queries, but I'd much prefer to use the django ORM, unless it explicitly disallows this sort of query. -
401 Unauthorized Error on Put Request with React-Redux
I'm have just started working on Django & Django-rest. I'm trying to prepare a task manager with django rest API & react.js. I completed the user register, user login and tasks with authentication. Now I cand create new tasks, delete them but I can't update a task. I have a check button which complete tasks and I had kept an "is_completed" variable in my task data (default is false). I want to change it to True when I click check button. There are my codes, I'm a beginner and any help can save my night, thanks in advance. check button handleCheck=(e)=>{ //find the task text's div let text= e.target.parentElement.nextSibling; text.classList.toggle("line-through"); e.target.classList.toggle("done-button-active") //toggle true/false is_completed on every click this.setState({ is_completed: !(this.state.is_completed) }); //send update request with id const id = e.target.getAttribute('name'); this.props.updateTask(id,this.state); } updateTask Action export const updateTask = (task,id) => (dispatch,getState) => { axios.put(`/api/tasks/${id}/`,tokenConfig(getState)) .then(res=>{ dispatch({ type : "UPDATE_TASKS", payload : task, }); }) .catch(err=>console.log(err)) } and my reducer else if (action.type ==='UPDATE_TASK') { return { ...state, tasks:action.payload, } } Finally, I got this error on console; PUT http://127.0.0.1:8000/api/tasks/[object%20Object]/ 401 (Unauthorized) I followed this code for the rest of the project. https://github.com/bradtraversy/lead_manager_react_django -
Create a django form with two models
I’m creating a request form that will allow multiple file attachments (uploads). I’ve decided to have one model for the request, another model for the files being attached. I’m really struggling to get the form operational in that the request data and attached files are displayed together prior to submitting the request. My code has to many issues to display. Can anyone suggest any links that would be helpful to point me in the right direction? I’m striking out. Thank you. -
Why am I getting this invalid syntax error?
from django.contrib.admin import helpers, widgets File "/Users/Scott/Desktop/myvirtualenv/crazy/lib/python3.7/site-packages/django/contrib/admin/widgets.py", line 152 context['related_url'] = mark_safe(related_url) ^ SyntaxError: invalid syntax I'm not sure why I am getting this error and was hoping someone could let me know what I need to do here?