Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
removing default --------- option from radio button rendering in template
I am trying to remove the -------- value in my radio button display. The field is declared like this in models.py my_field = models.CharField(max_length=50, choices=MY_CHOICE, blank=True, null=True) I am using this ModelForm to apply some custom CSS forms.py class MyAppForm(ModelForm): class Meta: model = MyApp exclude = [] def __init__(self, *args, **kwargs): super(MyAppForm, self).__init__(*args, **kwargs) self.fields['my_field'].empty_label = None for i, f in self.fields.items(): f.widget.attrs['class'] = 'custom-class' I have seen this line self.fields['my_field'].empty_label = None suggested in multiple Answers on StackOverflow, but, it seem to have no effect in my setup. I am getting the value of the selected choice using this piece of code in views.py def app_view(request, fk_id): app_value = MyApp.objects.get(my_fk=fk_id) # my_fk is a fk from another model app_form = MyAppForm(instance=app_value) I am rendering this form by simply {% for value, text in my_field.my_field.field.choices %} <li> <input id="{{ value }}" name="{{ app_form.my_field.name }}" type="radio" value="{{ value }}" {% if app_value.my_field == value %}checked="checked"{% endif %}> <label for="{{ value }}">{{ text }}</label> </li> {% endfor %} What could I be doing wrong in this setup that is not removing the default select option, ------? -
"Unable to log in with provided credentials." when trying to login my user
I'm getting this error when I try to login a registered user. I read a bunch of answers in people asking the same question but none of them have solved my issue so I'm confused at to what's happening. I added some stuff to my settings like some comments said and changed some things and so far this is what I've written to no avail. Maybe some extra eyes can help. Thank you. I'll show here my serializers: user = get_user_model() class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) email = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all(),lookup='iexact')] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta: model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords don't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class UserLoginSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, write_only=True, ) token = serializers.CharField( allow_blank=True, read_only=True ) password … -
Django error: ValueError at /cart/ -> The QuerySet value for an exact lookup must be limited to one result using slicing
I am getting a value error when adding the book to the cart. It points to for loop in views.py for orders. I am not able to figure a way to solve it. Any help is appreciated. bookstore-django/store/views.py", line 68, in cart for order in orders: Exception Type: ValueError at /cart/ Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing. models.py from django.db import models from django.db.models.query import prefetch_related_objects from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return "%s, %s" % (self.last_name, self.first_name) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField() publish_date = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.IntegerField(default=2) class Meta: verbose_name ='Book' verbose_name_plural = 'Books' db_table = 'book' #default is store_book class Review(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) publish_date = models.DateField(default=timezone.now) text = models.TextField() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) order_date = models.DateField(null=True) payment_type = models.CharField(max_length=100, null=True) payment_id = models.CharField(max_length=100, null=True) def add_to_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = BookOrder.objects.get(book=book, cart=self) preexisting_order.quantity += 1 preexisting_order.save() except BookOrder.DoesNotExist: new_order = BookOrder.objects.create( book=book, cart=self, quantity = 1 ) … -
I can't use cookies sent by a Django server
I created an authentication API on Django that sends csrf token in the response cookie when you send a request to a login endpoint. But it only works when I make these requests with Postman or directly from the browser: Postman login Postman Profile page access Response from a server to an axios request Here we see that there are no cookies in the browser: Cookies stored in the browser after request But here we clearly can see that server sent me cookies with csrf token and session id. Response cookies in the browser devtools But I can't access those cookies from the response object. There are not neither in document.cookies nor in response.headers['set-cookie']. I tried lots of things and unfortunately coundn't come up with anything. This is how I make requests: const login = (url) => { const creds = { "email": "example@gmail.com", "password": "hello" } axios.post(url + '/login', creds) .then( res => { console.log(res) } ).catch(err => console.log('ERROR: ' + err)) } const profile = (url) => { axios.get(url + '/profile', { withCredentials: true, }) .then( res => console.log(res) ).catch(err => console.log('ERROR: ' + err)) } And this is a login view in django: @api_view(['POST']) def login_user(request): user … -
Django Reverse Match Error with keyword arguments '{'pk': ''}' not found
I'm new to Django and programming in general. I'm going through the book Django For Beginners and have added my own flair in the forms section but have run into a problem. Below I have detailed the error and provided my code. ERROR NoReverseMatch at /drug/12/ Reverse for 'drug_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['drug/(?P[0-9]+)/edit/$'] Request Method: GET Request URL: http://127.0.0.1:8000/drug/12/ Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'drug_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['drug/(?P[0-9]+)/edit/$'] Exception Location: C:\Users\scott\django_sites\history_cloud1\history1_env\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: C:\Users\scott\django_sites\history_cloud1\history1_env\Scripts\python.exe Python Version: 3.8.3 models.py from django.db import models from django.urls import reverse class DrugInfo(models.Model): drug_name = models.CharField(max_length=75) patient_name = models.CharField(max_length=25, default='Enter Patient Name',) author = models.ForeignKey( 'auth.User',on_delete=models.CASCADE, ) def __str__(self): return self.drug_name def get_absolute_url(self): return reverse('drug_detail', args=[str(self.id)]) urls.py from django.urls import path from .views import ( drugListView, drugDetailView, drugCreateView, drugDeleteView, drugUpdateView, ) urlpatterns = [ path('drug/<int:pk>/delete/', drugDeleteView.as_view(), name='drug_delete'), path('drug/new/', drugCreateView.as_view(), name='drug_new'), path('drug/<int:pk>/', drugDetailView.as_view(), name='drug_detail'), path('drug/<int:pk>/edit/', drugUpdateView.as_view(), name='drug_edit'), path('', drugListView.as_view(), name='home'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import ( CreateView, UpdateView, DeleteView ) from django.urls import reverse_lazy from .models import DrugInfo class drugListView(ListView): model = DrugInfo template_name = 'home.html' class … -
Python django blog OperationalError
I want to enter the blog What should I do? enter image description here -
Django, use timedelta to add follow-up date to an invoice date
I've got this simple model that I'm using to practice various Django stuff: class Receivables(models.Model): agent = models.ForeignKey(Agents, on_delete=models.CASCADE, related_name='invoices') invoice_number = models.CharField(max_length=50) invoice_amount = MoneyField(decimal_places=2, default=0, default_currency='USD', max_digits=11) invoice_date = models.DateField() invoice_due_date = models.DateField() total_invoices = models.IntegerField(null=True) And I'm trying to create a follow-up date that is calculated to be 60 days from the invoice date. As I understand from researching, I need to use 'annotate' on my queryset, and so I tried this first: qry = Receivables.objects.annotate(follow_up_date=Receivables.invoice_date+timedelta(days=60)) And that threw a a TypeError for an unsupported operand for +: 'DeferredAttribute' and 'datetime.timedelta'. I found an anser on StackOverflow (to use an ExpressionWrapper), that I tried to work into my query like this: qry = Receivables.objects.annotate(follow_up_date=models.ExpressionWrapper(Receivables.invoice_date+timedelta(days=60))) But that throws the exact same error. Please help me understand what I'm doing wrong here. -
Webpack not creating bundle.js or error messages
I've tried installing webpack and babel-loader into my vue project. When I run 'npm run dev' in my terminal, I don't get any bundled files outputted to my dist folder and I get the following message: > vueproject@0.1.0 dev > webpack --watch --progress --mode=development Here's my file structure in my project: -vueproject -dist -src -deletethis.js package.json package-lock.json webpack.config.js babel.config.js package.json: { "name": "vueproject", "version": "0.1.0", "private": true, "scripts": { "test": "webpack", "dev": "webpack --watch --progress --mode=development", "prod": "webpack --mode=production", "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "@tailwindcss/line-clamp": "^0.2.0", "autoprefixer": "^9.8.6", "axios": "^0.21.1", "bcryptjs": "^2.4.3", "core-js": "^3.6.5", "mysql": "^2.18.1", "postcss": "^7.0.35", "postcss-loader": "^5.2.0", "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.0", "vue": "^3.0.0", "vue-router": "^3.5.1" }, "devDependencies": { "@babel/core": "^7.13.16", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/compiler-sfc": "^3.0.0", "autoprefixer": "^10.2.5", "babel-eslint": "^10.1.0", "babel-loader": "^8.2.2", "eslint": "^6.7.2", "eslint-plugin-vue": "^7.0.0", "path": "^0.12.7", "postcss": "^8.2.9", "postcss-cli": "^8.3.1", "tailwindcss": "npm:@tailwindcss/postcss7-compat@^2.1.0", "webpack": "^4.0.0", "webpack-cli": "^4.6.0" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/vue3-essential", "eslint:recommended" ], "parserOptions": { "parser": "babel-eslint" }, "rules": {} }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] } webpack.config.js: // webpack.config.js const path = require('path'); // Define the path module, which is used for handling and … -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__vacancies_company.owner_id error
I try to migrate and an error occurs: django.db.utils.IntegrityError: UNIQUE constraint failed: new__vacancies_company.owner_id from django.db import models from django.contrib.auth.models import User class Company(models.Model): name = models.CharField(max_length=64) location = models.CharField(max_length=64) logo = models.ImageField(upload_to="MEDIA_COMPANY_IMAGE_DIR") description = models.TextField() employee_count = models.IntegerField() owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name="owner_user") class Specialty(models.Model): code = models.CharField(max_length=32) title = models.CharField(max_length=32) picture = models.ImageField(upload_to="MEDIA_SPECIALITY_IMAGE_DIR") class Vacancy(models.Model): title = models.CharField(max_length=100) specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, related_name="vacancies") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="vacancies") skills = models.TextField() description = models.TextField() salary_min = models.FloatField() salary_max = models.FloatField() published_at = models.DateTimeField() class Application(models.Model): written_username = models.CharField(max_length=24) written_phone = models.CharField(max_length=12) written_cover_letter = models.CharField(max_length=300) vacancy = models.ForeignKey(Vacancy, on_delete=models.CASCADE, related_name="applications") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="applications") python manage.py runserver result: OperationalError at / no such column: vacancies_company.owner_id -
Django File Structure
On my Admin page I click the 'view site' link and I get a Page not found (404) error. What exactly should I be seeing? My homepage or something else? Here is my Django file structure |--myWebsite |--myWebsite |--_pycache_ |--_init.py_ |--asgi.py |--settings.py |--urls.py |--wsgi.py |--home |--_pycache_ |--migrations |--static |--templates |--_init_.py |--admin.py |--apps.py |--forms.py |--models.py |--test.py |--tokens.py |--views.py |--db.sqlite3 |--manage.py Here is are my templates so far home page, login page, create account page, account page Others I plan to add in the future: reset password page, verify email page, forgot username/password page, etc. Main Homepage http://138.0.0.1:8000/home Thanks -
How to create a Django Multi ModelForm
I wanna create one form from multiple models and I want to render the form on one page. I tried creating a simple form using the main model which is CompanyRegistration but it only gives me 4 fields. I wanna be able to create a form that will have all the models be cause all the models are related and are all supposed to serve one purpose. Below is my models.py file from django.conf import settings from django.db import models class CompanyRegistration(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.ForeignKey("CompanyName", on_delete=models.CASCADE) company_details = models.ForeignKey("CompanyDetail", on_delete=models.CASCADE) company_directors = models.ForeignKey("CompanyDirector", on_delete=models.CASCADE) class Meta: verbose_name = "Company Registration" def __str__(self): return f"New Company registration : {self.name.name1}" class CompanyName(models.Model): name1 = models.CharField(max_length=150, verbose_name="Company Name") name2 = models.CharField(max_length=150, verbose_name="2nd Choice") name3 = models.CharField(max_length=150, null=True, blank=True, verbose_name="3rd Choice") name4 = models.CharField(max_length=150, null=True, blank=True, verbose_name="4th Choice") def __str__(self): return self.name1 class CompanyDetail(models.Model): description = models.TextField(max_length=200) address = models.ForeignKey("CompanyAddress", on_delete=models.CASCADE, verbose_name="Company Address") class Meta: verbose_name = "Company Details" class CompanyAddress(models.Model): PROVINCE = ( ("Eastern Cape", "Eastern Cape"), ("Free State", "Free State"), ("Gauteng", "Gauteng"), ("KwaZulu-Natal", "KwaZulu-Natal"), ("Limpopo", "Limpopo"), ("Mpumalanga", "Mpumalanga"), ("North West", "North West"), ("Northern Cape", "Northern Cape") ) street_address = models.CharField(max_length=150) building = models.CharField(max_length=150, verbose_name="Building/Flat Number") city = models.CharField(max_length=150) … -
Stripe PaymentIntent credit card payment form refreshing the page instead of processing
would really appreciate the help. Everytime I hit the submit form on the Sripe credit card form, it simply refreshes the page and attaches the stripe token and card fields onto the URL instead of processing the payment. I checked on the Stripe dashboard, and the payment does not go through. The payment intent item gets captured in the models fine, but the payment status is None, presumably because the form is doing nothing. Previously it was not redirecting anywhere (which is fine, I have a fix planned for that), but the payment was going through on Stripe. After I fixed the form.submit() issue (had to change the button id), now the form is simply refreshing itself. The form html <section class="hero py-5"> <div class="container"> <div class='col-10 col-md-6 mx-auto'> <form id="payment-form"> <div id="card-element" class="form-control"><!--Stripe.js injects the Card Element--></div> <button class="btn btn-success" id="stripe-submit"> <div class="spinner visible" id="spinner"></div> <span id="button-text">Pay now</span> </button> <p id="card-error" role="alert"></p> <p class="result-message hidden"> Payment succeeded, see the result in your <a href="" target="_blank">Stripe dashboard.</a> Refresh the page to pay again. </p> </form> </div> </div> </section> The Javascript: <script src="https://js.stripe.com/v3/"></script> <script type="text/javascript"> var stripe = Stripe(XXXXX); var elements = stripe.elements(); var card = elements.create('card', { style: { base: … -
RuntimeError: There is no current event loop in thread 'Thread-1' with ib_insync and django
I am a newbie with ib_insync, I'm implementing ib_insync with django. When I place an order using placeOrder() I am getting the error RuntimeError: There is no current event loop in thread 'Thread-1'. my views.py def placeOrder(request, account): print("ACCOUNT: ", account) symbol = 'AAPL' action = 'BUY' strike = 145 date = '20210430' quantity = 1 currency = 'USD' secType = 'OPT' exchange = 'SMART' right = 'C' contract, order = create_contract(action, quantity, symbol, secType, date, strike, right,exchange, account) trade = place_order(contract, order) Here are the methods def place_order(contract, order): place_order = ib.placeOrder(contract, order) return place_order def create_contract(action, quantity, symbol, secType, lastTradeDateOrContractMonth, strike, right, exchange, account): contract = Option(symbol, lastTradeDateOrContractMonth, strike, right, exchange) order = MarketOrder(action, quantity) order.account = account return contract, order Error: File "C:\Users\Jason\Desktop\TradeApp\venv\lib\site-packages\ib_insync\client.py", line 268, in sendMsg loop = asyncio.get_event_loop() File "c:\users\jason\appdata\local\programs\python\python39\lib\asyncio\events.py", line 642, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'Thread-1' -
Does django-message library work properly?
I am following the tutorial Django-Messages library tutorial on the following address: https://django-messages.readthedocs.io/en/latest/usage.html Does this actually work properly? I am getting the following error: Traceback (most recent call last): File "c:\users\chandan\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\chandan\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "c:\users\chandan\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django_messages\models.py", line 9, in <module> from django.utils.encoding import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (D:\Programming\NewProjecttoReviseAllTechnologies\Django Blog\djangoNewEnv\django\lib\site-packages\django\utils\encoding.py) -
Django API Deployment to Heroku "ProgrammingError"
Please refer to this thread with a very similar issue that was not solved I created a web API through Django in order to service a mobile app that I am developing. Within that API, I configured an external MySQL database that is hosted on a remote server. The API runs fine locally. I pushed this API to a GitHub repository and deployed it through Heroku using a Heroku app. The app launches successfully, however when I try to access a path which I have defined in my API, for example "/guests" (accessing this path is supposed to collect data from a "guest" table in my external database, and return it), I get an error. From what I can gather, it seems that it's as if I don't have an external database configured. The comments in the thread which I referenced above seem to say the same thing. Does anyone know how to solve this? ProgrammingError at /guests/ relation "guest" does not exist LINE 1: SELECT "guest"."GUEST_ID" FROM "guest" ^ Here is the traceback Environment: Request Method: GET Request URL: https://queuedjangoapi2.herokuapp.com/guests/ Django Version: 3.2 Python Version: 3.7.9 Installed Applications: ['rest_framework', 'queueapi.apps.QueueapiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', … -
How to I send an external POST request to a Django app?
I need to send a POST request to a Django app to update a dictionary that the app references. The urls.py file looks like: from django.conf.urls import url from . import views urlpatterns = [url(r'^post/', views.receive] and the views.py file looks like: from django.shortcuts import render, HttpResponse import json def receive(request): if request.method == 'POST': contents = json.parse(request.body) When I try to send a POST to the url in urls.py with a simple body, I get a forbidden error. How do I structure my code/app to receive and record data from a POST? Is Django able to do this? -
'bool' object has no attribute 'save'
I am trying to work on a Django app and I would like to check if the boolean object in the database is False and save it as True, but every time I get the error above, I would appreciate any assistance or insight on what I'm doing wrong. views.py if request.method == 'POST': for data in Mpesa.objects.all(): all_receipts = data.MpesaReceiptNumber status = data.Completed verify_receipt = request.POST['verify'].upper() if verify_receipt in all_receipts: if status == False: status = True status.save() return redirect('realtor:create') models.py class Mpesa(models.Model): MpesaReceiptNumber = models.CharField(max_length=15, blank=True, null=True) PhoneNumber = models.CharField(max_length=13, blank=True, null=True) Amount = models.IntegerField(blank=True, null=True) TransactionDate = models.DateTimeField(blank=True, null=True) Completed = models.BooleanField(default=False) -
Python - Reactivating my virtualenv for django project
(Beginner) I am working with a virtualenv for a django project using my Macos terminal and Visual Studio Code. Recently, my terminal disappeared where I was running all of my code and I do not know how to reenter my virtualenv or my project that I still have on Visual Studio Code. I have tried everything including: source virtualenv/bin/activate Or, virtualenv/source/activate Or, cd my_project_name and then trying to enter my virtualenv following this step (^) with the commands above. Nothing is working and when I run "python manage.py runserver" it says there is no such file or directory. I am struggling and do not know how to continue my current project on django before getting back to my project and virtualenv. Any help is greatly appreciated! -
How to deal with foreign keys in the model adding form on the admin panel?
I have three based models with Foreign keys relations, defined as follows: class User(AbstractUser): username = None email = models.EmailField(('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email class Product(models.Model): id = models.CharField(primary_key=True, max_length=255) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="products", null=True, blank=True, ) class Viewer(models.Model): id = models.CharField(primary_key=True, max_length=255) product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="viewers" ) What I want is, instead of having a form for each model registered in the administration panel, to have a single common form, in which I can fill in the id of the models and these are created in the database if they do not exist. For this purpose, I have defined a new model with foreign keys to these fields: class Register(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) viewer = models.ForeignKey(Viewer, on_delete=models.CASCADE) What I would like is for the registration form to have only 3 charfields, one to enter the user's email, one for the product id and the last one for the viewer id. However, when I define a form in the following way: class RegisterForm(forms.ModelForm): user = forms.EmailField() product = forms.CharField(max_length=255) viewer = forms.CharField(max_length=255) class Meta: model = Register fields = ("user", "product", "viewer") … -
In django signals, how to pass sender's class variables (model fields) to receiver (management.call_command function) and use it
I am building a multi-tenant project using third-party package (django-tenants) which makes me derive the Tenant and Domain models from it's own classes: from django_tenants.models import TenantMixin, DomainMixin class Tenant(TenantMixin): name = models.CharField(max_length=100) email = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) auto_create_schema = True auto_drop_shema = True class Domain(DomainMixin): pass; Long story short, I want to create an API view to register tenants but I couldn't understand package code and failed when trying to create a TenantManager; But I did figure out how to call the CLI management commands provided by django-tenants (python manage.py create_tenant/create_tenant_superuser) from inside the code using django.core.management.call_commands: management.call_command( 'create_tenant', domain_domain = 'tenant1.mysite.com', schema_name = 'tenant1Schema', name ='tenant1Name', email = 't1@t1.com', domain_is_primary = True, ) So I figured the temporary simplified solution - another model (Founder) made with regular models.Model and with it's own genericAPIview which I know how to create. Upon posting this model I want to execute the signal to my custom management.call_command. As far as I understand, there are three parts to django signals: sender - this is supposed to be a "notify_about_sender_creation" method in my Founder model receiver - this is supposed to be a callable object, in my case it's this custom management.call_command signal … -
FileNotFoundError at /user/profile/edit [Errno 2] No such file or directory: 'user_3/profile.jpg'
I`m beginner of django and try to make small newsfeed like instagram. And I have issue, after I connect the backend storage to S3 for media and staticfiles, my media file has some problem. I have error "FileNotFoundError at /user/profile/edit [Errno 2] No such file or directory" I have searched about this problem, and there is something about file format between S3 and pillow is different. But when I try to save pic.save(self.picture.name) or pic.save(self.picture.path), then I have key error about image format. But it upload to S3 properly, just python can not find it. I have no idea which part is wrong. Can someone please tell me? model.py def user_directory_path_profile(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> profile_pic_name = 'user_{0}/profile.jpg'.format(instance.user.id) full_path = os.path.join(settings.MEDIA_ROOT, profile_pic_name) if os.path.exists(full_path): os.remove(full_path) return profile_pic_name def user_directory_path_banner(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> banner_pic_name = 'user_{0}/banner.jpg'.format(instance.user.id) full_path = os.path.join(settings.MEDIA_ROOT, banner_pic_name) if os.path.exists(full_path): os.remove(full_path) return banner_pic_name class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile') location = models.CharField(max_length=50, null=True, blank=True) url = models.CharField(max_length=80, null=True, blank=True) profile_info = models.TextField(max_length=150, null=True, blank=True) created = models.DateField(auto_now_add=True) picture = models.ImageField( upload_to=user_directory_path_profile, blank=True, null=True, verbose_name='Picture') banner = models.ImageField( upload_to=user_directory_path_banner, blank=True, null=True, verbose_name='Banner') def save(self, *args, **kwargs): super().save(*args, **kwargs) SIZE … -
Django: __init__() got an unexpected keyword argument 'email'
I am trying to create a new user registration form, but I get an error init() got an unexpected keyword argument 'email' How can I solve this problem? My code: views.py def add_person(request): if request.method == 'POST': # If the form has been submitted... form = RegistForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass email = form.cleaned_data.get("email") first_name = form.cleaned_data.get("first_name") last_name = form.cleaned_data.get("last_name") password = form.cleaned_data.get("password") password_conf = form.cleaned_data.get("password_conf") reg_from_form = RegistForm(email=email, first_name=first_name, last_name=last_name, password=password, password_conf=password_conf) reg_from_form.save() return HttpResponseRedirect('index') # Redirect after POST if request.method == 'GET': return render(request, 'words/registr.html') forms.py class RegistForm(forms.Form): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) password = forms.CharField(max_length=50) password_conf = forms.CharField(max_length=50) registr.html <form method="POST" action="add_person">{% csrf_token %} <input type="email" name="email"> <input type="text" name="first_name"> <input type="text" name="last_name"> <input type="text" name="password"> <input type="text" name="password_conf"> <input type="submit" value="Register"> -
django auto select the project in the form when commenting on it is not working
I want the project (or the article) to be selected when user clicks on it to comment. right now the user must select the project when he wants to comment it even thought he did click on the specified project. also if the user wants to comment on a project and clicks on that project than in the comment form select the wrong project then the comment goes to the wrong project. this is my models.py: # projects/models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from django.core.validators import MinLengthValidator class Project(models.Model): title = models.CharField( max_length=255, validators=[ MinLengthValidator( 10, "Title must be descriptif and greater than 10 characters") ] ) body = models.TextField( validators=[ MinLengthValidator( 100, "body must be descriptif and greater than 100 characters") ] ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('project_detail', args=[str(self.id)]) class Comment(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='comments', ) comment = models.TextField( max_length=140, validators=[ MinLengthValidator( 20, "comment must be descriptif and greater than 20 characters") ] ) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('project_list') this is my … -
Django query add year filter
I have a following query: queryset = Post.objects.annotate(month=ExtractMonth('date_posted')).values('month').annotate(count=Count('status')) for entry in queryset: date.append(entry['month']) data_nc.append(entry['count']) I would like to add an filter of a year. So I can append values only for a specific year, from 'date_posted'. -
Issue with spanish accents on django dumpdata output redirect to file content
I'm trying to generate some fixtures for loading initial data and I'm using powershell. Some of my db entries have spanish accents (them are persons names). Calling python manage.py dumpdata myapp.model works fine, their output its correct, but using the redirect output operator as this python manage.py dumpdata myapp.model > myfile.json or even this python manage.py dumpdata myapp.model | out-file myfile.json -encoding utf8 does not. The created json file has all characters with accents replaced with �, i.e César to C�sar. I've also tried to set powershell and python sys stdin and out encoding encoding to utf-8.