Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't login my users, they don't seem to be registering properly
I'm trying to login the users I registered in my registration view (where I get a 200 code that says POST request was successful) but I get "Unable to log in with provided credentials." when I try to log them in. When I check in the shell with User.objects.all(), I only get my superuser back so I think the users are not being saved to the database. I don't understand why this is happening so if anyone has an idea, it'd be appreciated. Here's the code. Models: from django.db import models, transaction from django.conf import settings from django.contrib.auth.models import BaseUserManager, AbstractUser class UserManager(BaseUserManager): @transaction.atomic def create_user(self, email, username, password=False): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def get_by_natural_key(self, username): return self.get(username=username) def create_superuser(self, username, password, email): user = self.create_user( username=username, email=email, password=password, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name= 'username', max_length= 50, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return str(self.username) Serializers: … -
iterating issue in a for loop (Python3 + Django)
I am a newbie so please be kind, working on a blog app within my django project the idea is to check if there are articles , if there is list each article. if there is not articles show no articles found below is my view function, however when I test this it only list the first item in my list which mike, other names are not showing on the page or on source like they do not exist ??? any help with this would be great. thanks in advance def add(request): articles=["mike","sammy","ahmed"] if not articles : return HttpResponse("<body><h1>No Articles to display here</h1></body>") else: for article in articles: return HttpResponse(f"{article}") -
How can I allow a user to upload the template for a landing page for another user in Django?
I have the admin user able to upload via forms a landing page for a selected role (Student, Advisor, Admin) and I want to be able to get it to render properly. Right now, it renders properly the html and the css but prints out in plain text the {{ }}'s and the {% %}'s which isn't helpful. The view for the roles landing pages as of right now sends the plain text html (context['page'] = LandingPage.objects.get(role='adm', live=True)) stored in the database to the html stored in templates which has nothing in it except {{ page| safe}}. -
Add celery (tasker) To Django Admin panel on Search click
I am using the Admin panel of django for searching. Sometimes it can take 15 + minutes for search to finish and I get timeout (502). But search process still exist (consuming resources). I would like to show a progress bar waiting for task to finish when clicking: What is the best option for me ? -
django-channels: PUT request info not saving when user disconnects from websocket then reconnects
I have a problem. The app in question is basically complete, but there's a bug with the user PUT endpoint to edit the user info. If the websocket is disconnected, the endpoint works well. same if the websocket is connected. But If I edit the profile with the websocket connected, disconnect the websocket and connect it again, the changes I made are reverted. anyone know why? What's also weird is that the websocket is used only in chat, not for profile editing (chat is an entirely different app) Any help is appreciated -
Django HTML Email, Table List not working
Im working with Django HTML email. Sending Email with HTML template is working but my problem is the data not showing in table once already sent via email but in my localhost present. Please help me to fixed my issue,Thank You! This is the output when I show via localhost: This is the output when template already sent via email, The data in the table are missing. Here is my django email script: elif month == 4: cstatus = Regdata.objects.filter( Registration_month="APR", sent_email="No") s = "" for carreg in cstatus: print(carreg.PLATE_NO) s += carreg.PLATE_NO cstatus.update(sent_email="Yes") if s != "": subject = 'Hi' html_message = render_to_string('email.html', {'context':'value'}) plain_message = strip_tags(html_message) from_email = 'From <example@gmail.com>' to = 'example@gmail.com' mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) Html Email Template: <body> <h2>Hi,</h2> <p>Body message..........</p> <table id="example" class="display nowrap" style="width:100%"> <thead> <tr> <th>Plate Number</th> <th>CR Name</th> <th>Model</th> <th>Brand</th> </tr> </thead> <tbody> {% for object in apr_email %} <tr class="odd gradeX"> <td>{{ object.PLATE_NO }}</td> <td>{{ object.CR_NAME }}</td> <td>{{ object.MODEL }}</td> <td>{{ object.BRAND }}</td> </tr> {% endfor %} </tbody> </table> </body> -
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") …