Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Routing does not work in Django: page not found (GET)
I've tried multiple methods of writing views but I don't think it is a problem here. App is installed in settings.py It displays error every time. project structure: structure url.py in apps folder from django.urls import path from . import views urlpatterns = [ path('home_view/', views.home_view) ] apps.py in app folder from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' urls.py in store folder from django.contrib import admin from django.urls import path, include from app import views urlpatterns = [ path('app/home_view/', include('app.url')), path('admin/', admin.site.urls), ] error message: error -
Fetching data using eact native
I am trying to fetch my user infomations from django database. But I only get the following message {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "bodyUsed": false, "headers": {"map": {"allow": "GET, POST, HEAD, OPTIONS", "content-length": "94", "content-type": "application/json", "date": "Sat, 19 Mar 2022 22:02:40 GMT", "referrer-policy": "same-origin", "server": "WSGIServer/0.2 CPython/3.6.8", "vary": "Accept, Origin, Cookie", "x-content-type-options": "nosniff", "x-frame-options": "DENY"}}, "ok": true, "status": 200, "statusText": "", "type": "default" I can use it to determine if the status is OK to long in, but I would like to be able to gather the user information and send them to the next page. Any help? -
Update global variable in an asychrounouus way in Django
I have a tacky problem. On my website, you can find current price tracker for crypto coins as a purely content filler element. I get my data from coin API, you are allowed 100 request's per day. def crypto_api_prices(request): api_base_url = 'https://rest.coinapi.io/v1/exchangerate/' api_key = '===============' headers = { 'X-CoinAPI-Key': api_key, } crypto_tickers = ["BTC","ETH","ETC","RVN"] crypto_api_links = [api_base_url+x+"/"+"USD" for x in crypto_tickers ] crypto_api_prices = [requests.get(x, headers=headers).json()['rate'] for x in crypto_api_links] context = { "cryptoPrices":crypto_api_prices } return context I'm calling this function in my home view. Unfortunately, if I have couple of visitors daily this generates 100 requests pretty fast and my element isn't working anymore. What I want to achieve is set crypto_api_prices as a global variable and update it every hour, so no matter how many users will be on my page I will generate only 24 requests. Is this a good idea? Are there alternatives? Of course I can buy more requests but this website is a "passion" project so I want to keep costs down -
DRF IsAuthenticated seems to be not working properly in remote server
I started a migration of a personal project between two servers and I get a very weird behavior. My APP uses TokenAuthentication from DRF and is working perfectly in a local environment and in the previous server but in the new one I get the following error: "Authentication credentials were not provided.". At the first time I thought that it was because Nginx was not sending the right headers to the backend but after doing some debugging I found that the headers were ok. Im totally lost at this point, hope I can get some help. Thanks to everyone. My REST_FRAMEWORK config: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", #"rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, "DEFAULT_FILTER_BACKENDS": [ "django_filters.rest_framework.DjangoFilterBackend" ], } Current view: class UserInfoView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = self.request.user return Response({"type": user.user_type, "username": user.username}) Request made by CURL: % curl 'http://myapp.com:8000/api/user-info/' \ -H 'Connection: keep-alive' \ -H 'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"' \ -H 'Accept: application/json, text/plain, */*' \ -H 'Authorization: Token 144e22bc66c9b145596690c8673ef9aaefbaad1d' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36' \ -H 'sec-ch-ua-platform: "macOS"' \ -H 'Sec-Fetch-Site: cross-site' \ -H 'Sec-Fetch-Mode: … -
Django 3.2 makemigrations ProgrammingError: table doesn't exist for abstract model
I'm currently updating my website to use Django 3.2, but I use the zinnia blog which is no longer receiving updates. I'm making the necessary changes to bring it up to compatibility with 3.2 but I'm now getting the error that the AbstractEntry table doesn't exist. This is, however, an abstract table so I'm confused why it would try to find the table at all. Full traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.8/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.8/dist-packages/zinnia/models/__init__.py", line 4, in <module> from zinnia.models.entry import Entry File "/usr/local/lib/python3.8/dist-packages/zinnia/models/entry.py", line 6, in <module> class Entry(load_model_class(ENTRY_BASE_MODEL)): File "/usr/local/lib/python3.8/dist-packages/zinnia/models_bases/__init__.py", line 18, in load_model_class _class … -
How do I fix: Your branch is ahead of 'heroku/main' by 1 commit. (Heroku/Django)
I am trying to drill down a major problem I have created syncing my Heroku and local PostgreSQL databases. I believe I may have found the source of the problem: I am new to web development and this is my first deployed application so I have made some clumsy mistakes along the way. My current flow for pushing is this: Local migration: python3 manage.py makemigrations Commit: git add and git commit -a Deploy: git push heroku main Migrate to server: heroku run python3 manage.py migrate I currently get this message: On branch main Your branch is ahead of 'heroku/main' by 1 commit. It looks like my Heroku DB may be out of sync by 1 commit with my local db - hence I am getting a whole host of errors in my deployed application. I would like to know how to rectify this and hope to have some advice prior to doing anything to make sure I don't mess it up. Below is the terminal log for the push that led to the above message. I am not sure if the WARNINGS are linked to the current issue, because they reference STATICFILES I assume not. Terminal Log (venv) xx % … -
How to get IntergrityError data Django
I have an IntegrityError data as follow : ERROR: Duplicate key value breaks unique constraint "CampaignNamingTool_year_month_advertiser_na_aedc5c8c_uniq" DETAIL: The key “(year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. I would like to get the key: (year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. How can I do that? Any help is appreciated try: CampaignNamingTool.objects.bulk_create(list_of_campaign_naming_tool) except IntegrityError as e: messages.error(request, e) return redirect('bulk_create_campaign_naming_tool') else: msg = "Campaigns successfully uploaded" messages.success(request, msg) return redirect('bulk_create_campaign_naming_tool') -
When to use OAuth in Django? What is it's exact role on Django login framework?
I am trying to be sure that I understand it correctly: Is OAuth a bridge for only third party authenticator those so common like Facebook, Google? And using it improves user experience in secure way but not adding extra secure layer to Django login framework? Can I take it like this? Thanks in advance! -
Submitting 2 custom Crispy Forms with 1 button Django
I have 2 forms with the second form referencing the first form. I can get the forms to execute correctly using crispy forms, however, when I customize each form using helper = FormHelper() they will no longer submit together. Essentially one form is submitted and the other form thinks it is missing all of its input data. Forms.py from django.forms import ModelForm, forms from .models import Item, Item_dimensions from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column # Create the form class. class List_Item_Form(ModelForm): class Meta: model = Item exclude = ('id','creator','created_on','updated_on' ) helper = FormHelper() helper.layout = Layout( Row( Column('item_name', css_class='form-group col-md-6 mb-0'), Column('price', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'short_description', 'description', Row( Column('main_image', css_class='form-group col-md-2.5 mb-0'), Column('image_2', css_class='form-group col-md-2.5 mb-0'), Column('image_3', css_class='form-group col-md-2.5 mb-0'), Column('image_4', css_class='form-group col-md-2.5 mb-0'), Column('image_5', css_class='form-group col-md-2.5 mb-0'), css_class='form-row' ), 'quantity' ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' class List_Item_Dimensions(ModelForm): class Meta: model = Item_dimensions exclude = ('id','item_id') helper = FormHelper() helper.layout = Layout( Row( Column('x_dim_mm', css_class='form-group col-md-4 mb-0'), Column('y_dim_mm', css_class='form-group col-md-4 mb-0'), Column('z_dim_mm', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), 'weight_grams', Submit('submit', 'add_listing') ) helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) helper.form_method = 'POST' I have tried removing helper.add_input(Submit('submit', 'Submit', css_class='btn-primary')) and using just one submit button but … -
How to give access for a model object to a specific user in Django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Django: How do I check if a User has already read/seen an article?
I am building a web-application for my senior design project with Python and Django. I have a user model that is able to read/write articles to display on the website. I want to make it so that if an article is accessed (read) by a user, it is indicated for only that user that the article has been previously accessed. If I were to log into a brand new user account, the same article wouldn't be indicated as "accessed" for the new account. How can I go about implementing this? Below are my models and views User model class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True, max_length=255, blank=False) university = models.CharField(max_length=200, null=True, blank=True) newsletter_subscriber = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) is_staff = models.BooleanField( default=False, help_text=( 'Designates whether the user can log into ' 'this admin site.' ), ) is_active = models.BooleanField( default=True, help_text=( 'Designates whether this user should be ' 'treated as active. Unselect this instead ' 'of deleting accounts.' ), ) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email Article model class Article(models.Model): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=False) author = models.CharField(max_length=200, null=True, … -
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django
How can I sum up and display a model method field and also display it on the dashboard without looping through the template in Django. I aim to display two values on my dashboard. Total Invested and total Earned. I am able to display total Invested by using the code below. My view investments = Investment.objects.all() total_invested = Investment.objects.aggregate( total_invested=Sum('amount_deposited ')) context = { 'investments': investments, 'total_invested': total_invested, } return render(request, 'list-investments.html', context)``` Then displaying it in my template ```{{total_invested.total_invested}}``` Note: I didnt use **for loop** in my template but I was able to get the total sum invested. I tried repeating the same procedure to get the total amount earned but Its not working. Any idea how to go about it? I also want to know how I can save these model methods values in the database. **My Model Class** ```class Investment(models.Model): PLAN_CHOICES = ( ("Basic - 4% - max 6", "Basic - 4% - max 6"), ("Premium - 5% - max 12", "Premium - 5% - max 12"), ) plan = models.CharField(max_length=50, choices=PLAN_CHOICES, null=True) duration = models.IntegerField(max_length=50, null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) active_investment = models.BooleanField(default=True) amount_deposited = models.IntegerField(null=True) def __str__(self): return self.plan def basic_profit(self): self.basic_pro = … -
How to "open" locked terminal when Django server is running on VSCode?
I am trying to do this Django tutorial and came a cross problem where I cannot write to terminal when Django server is running. Here is excact spot on tutorial: https://youtu.be/uhSmgR1hEwg?list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&t=552 Tuotorial teacher clearly presses some hotkey to "enable" writing to terminal (that reveals PC: C:\Users... line). But what might that hotkey be? -
How to create individual id's per model per user account [Django]
I have come across an issue where everytime a different account that is logged in creates a new collection, the id for that collection is id '1' (127:0.0.1/collections/1), but when you log into another account the and that user creates a new collection, the collection id is '2' (127:0.0.1/collections/2) when I want that one to start as a id = 1. I want each user to have their own ID when creating collections. Same goes for the items inside of the collection. It's like all users on the website are sharing ID's. I wasn't sure what exactly it is I should search up online so I was unable to find any suggestions. Also I am using a built-in user profile instead of a custom one. Any resources or ideas would be great. My Django version is 4.0.3 Models.py class Collection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="collection", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Input(models.Model): name = models.ForeignKey(Collection, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text views.py def create(response): if response.user.is_authenticated: username = response.user.username if response.method == "POST": form = NewInput(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = Collection(name=n) t.save() response.user.collection.add(t) return HttpResponseRedirect("/collections/%s" % username) else: form … -
What in this python program can make my memory goes to sky and freeze the program?
I have written a python program that connect to my mqtt server and process the data! BUt the memory start very low and get higher and higher over time! I would says pretty fast like in 2 hours it goes from ~20% to ~80% if i don't restat the process, it will just hang and stop the program. It does over a week i am looking at the code searching for my errors trying different things and nothings seems to fix the problem!! This code is where i am at now! Thanx a lot! #!/usr/bin/python from __future__ import unicode_literals import os, sys, django, json, time, datetime, socket, _thread, multiprocessing, queue import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import django.db BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) #here store is root folder(means parent). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "EraIoT.settings") django.setup() from vac300s.models import vac300, vac300Stat from vac200sV1.models import vac200V1 from shared.utils import * mqtt.Client.connected_flag = False clear = lambda: os.system('clear') messagesReceivedQ = queue.Queue() messagesQueuedQ = queue.Queue() activeThreadQ = queue.Queue() processingTimeQ = queue.Queue() processingTimeMysqlQ = queue.Queue() processingTimeMemcachedQ = queue.Queue() processedRequestQ = queue.Queue() topics = ["data/vac300s/#", "message/vac300s/#", "alarm/vac300s/#"] q = queue.Queue() def on_disconnect(mqttc, userdata, rc): print("*****************************************") print("Disconnected from MQTT server:") print(str(rc)) print("*****************************************") mqttc.connected_flag = False def on_connect(mqttc, obj, flags, … -
Populate/filter one <select> with another <select>
I have a form to create projects in my app. In this form the user must select a client in a and then a farm in another . How do I when selecting a client, the next only offers options from farms that are from the selected customer? I believe it's impossible to do this with just Django, am I right? simplified models.py class Project(models.Model): farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') class Farm(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='client', null=True, default=None) name = models.CharField(max_length=100, verbose_name='Nome') forms.py class NewProjectForm(ModelForm): class Meta: model = Project fields = ['owner','farm','warranty','modal','harvest_year','culture','value','final_date'] def __init__(self, *args,**kwargs): super(NewProjectForm, self).__init__(*args,**kwargs) self.fields['value'].required = False self.fields['final_date'].required = False self.fields['owner'].queryset = Owner.objects.all().order_by('name') farm_query = Farm.objects.all().order_by('name') self.fields['farm'].queryset = farm_query self.fields['warranty'].queryset = farm_query self.fields['final_date'].widget.attrs['data-mask'] = "00/00/0000" for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' -
H14 Error regarding favicon when deploying Django app to Heroku
Attempting to deploy my Django web application to Heroku. This is the first time I have ever deployed the app on Heroku however the app works as expected when running at localhost:8000. I have followed the documentation and can confirm the presense of 'Procfile' in the root directory of the app. The contents of Procfile are as follows: web: gunicorn my_app.wsgi This is consistent with the name of the app as referened everywhere in the project directory/folders. The 'requirements.txt' file is also present, with the necessary dependencies stated within it. When I deploy the app I get a success message as illustrated below. Yet, when I navigate in the browser to the url I see this... If I then consult the logs using the commmand heroku logs --tail --app myapp I see the following at=error code=H14 desc="No web processes running" method=GET path="/" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https 2022-03-19T19:07:35.123190+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=[REDACTED] fwd="51.9.111.101" dyno= connect= service= status=503 bytes= protocol=https Further investigaton leads me to believe that that there are currently no dynos assigned to the app, so I then attempt to spin up some resources using the following command … -
Real time chat application with Django Channels
My real time chat application refuses to send message. no errors at all. I have tried tracing the errors by logging to the console at every stage passed and also tried printing to the terminal. I think the problem might be from consumers.py here is my consummers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_name, self.channel_name, ) await self.accept() async def disconnect(self): print('\nOguh... disconnecting\n') await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def recieve(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] print('\nOguh... recieving a message\n') await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username, 'room': room } ) async def chat_message(self, event): print('\nOguh... Chat message\n') message = event['message'] username = event['username'] room = event['room'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'room': room, })) Here is my room.html: {% extends 'core/base.html' %} {% block tittle %} {{ room.name }} | {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{ room.name }}</h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id='chat-messages'> <div class="p-4 bg-gray-200 rounded-xl"> <p class='front-semibold'>Username</p> <p> A sample … -
django image form does not save image
hey i got a issue with saving image. when i use the admin side it works well, but when i add a employee with frontend form it save evrything exept the image. <form id="form" method="POST" action="{% url 'addForm' %}" enctype="multipart/form-data" > {% csrf_token %} {{form | crispy}} <input type="submit" name="submit" value="submit" > </form> def index(request): employe = Employe.objects.all() form = EmployeForm teamFilter = Employe_Filter(request.GET, queryset=employe) employe = teamFilter.qs count = employe.count() context = { 'employe': employe, 'form': form, 'teamFilter': teamFilter, 'count': count } return render(request, 'managements/index.html', context) class EmployeForm(forms.ModelForm): class Meta: model = Employe fields = '__all__' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Why 'pip' stopped working even though it was working fine before?
I am a bit new to programming and have been learning for a few weeks now. I am following Corey Schafer basic python videos and in the middle of his Django Series. To run the server, I run a virtual env. In cmd (in the project directory) I type: 1-pip shell 2-python manage.py runserver The server runs and I work on the project. Not Today. When I wrote pip shell, it gave me an error that: 'pip' is not recognized as an internal or external command, operable program or batch file. enter image description here I reinstalled Python after uninstalling it. pip is installed on my system. I added a new variable from the python folder (scripts) in my system. I did not work and it's still showing me the same error. -
Django Streaming
I just started with django and I want to make a spotify clone. I want to make it so then when you click on an album it shows the songs for that album. this is my models.py from django.db import models class album(models.Model): title = models.CharField(max_length=50) artist = models.IntegerField() genre = models.CharField(max_length=20) id = models.AutoField(primary_key=True) artwork = models.CharField(max_length=1000) class artist(models.Model): name = models.CharField(max_length=50) id = models.AutoField(primary_key=True) class song(models.Model): name = models.CharField(max_length=60) artist = models.IntegerField() album = models.IntegerField() id = models.AutoField(primary_key=True) This is my views.py from django.shortcuts import render from .models import album, song def home(request): context = { 'albums': album.objects.all(), } return render(request, 'main/index.html', context) Thank You -
StaticLiveServerTestCase with Selenium: ERR_CONNECTION_REFUSED
I'm running the default snippet from the docs for testing with selenium but 'm using Chrome driver. When I run the tests using python manage.py test it can't connect to the server seems it won't start, throwing the error ::ERR_CONNECTION_REFUSED. Any ideas? Here is the snippet: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from selenium import webdriver class MySeleniumTests(StaticLiveServerTestCase): # fixtures = ['user-data.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = webdriver.Chrome(executable_path='./chromedriver') cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() def test_login(self): self.selenium.get('http://localhost:8000/accounts/login') -
Django: How to autopopulate foreign key with the corresponding model class instance
Working on my first Django project and could use some help. I have 2 models (Decisions, Votes) linked by the foreign key called 'decision'. The template, vote_list.html, shows the user a list of decisions (generated by other users) that are contained in Decisions. The user taps a particular decision and is re-directed to a second template to vote on options pertaining to that decision. How do I autopopulate the foreign key 'decision' in Votes with the corresponding instance of Decision so that the second template, vote_form.html, displays the options for the decision they tapped on? I assume it's coded in views.py (I commented an attempt below that doesn't work), but how might it be done? Thank you! urls.py path('vote-list/', views.VoterView.as_view(), name='vote_list'), path('vote-list/<pk>/vote-form/', views.VoteForm.as_view(), name='vote_form'), models.py class Decisions(models.Model): custom_user = models.ForeignKey(CustomUser, default=None, null=True, on_delete=models.SET_NULL) description = models.CharField(default="", max_length=100, verbose_name="Decision Summary") class Votes(models.Model): decision = models.ForeignKey(Decisions, default=None, null=True, on_delete=models.SET_NULL) vote = models.CharField(default="", max_length=100, verbose_name="Your vote") views.py class VoteForm(LoginRequiredMixin, CreateView): model = Votes form_class = VotingForm template_name = 'users/vote_form.html' def post(self, request, *args, **kwargs): super() form = self.form_class(data=request.POST) if form.is_valid(): instance = form.save(commit=False) # instance.decision = Decisions.description instance.save() return redirect('users:vote_list') forms.py class VotingForm(forms.ModelForm): class Meta: model = Votes fields = ['vote'] vote_list.html {% … -
Django Related model 'vendor.newuser' cannot be resolved
NewUser app in the settings.py ALLOWED_HOSTS = [] LOGIN_URL ='login' LOGIN_REDIRECT_URL ='vendor_admin' LOGOUT_REDIRECT_URL ='home' AUTH_USER_MODEL = 'vendor.NewUser' models.py its only the app and also dont pay attetin to the (-() its just diffren languge class NewUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField(_('ایمیل'),max_length=255,unique=True) username = models.CharField(_('نام کاربری'),max_length=255, unique=True) realstate= models.CharField(_('نام املاک'),max_length=80) date_joined= models.DateTimeField(_('تاریخ ثبت نام'),auto_now_add=True) last_login = models.DateTimeField(_('اخرین_ورود'), auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_pic = models.ImageField(_('عکس پروفایل'),max_length=255 ,upload_to=get_profile_image_filepath,null=True ,blank=True, default=get_default_profile_image) objects = CustomAccountManger() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] def __str__(self): return self.username def get_profile_image_filenames(self): return str(self.profile_pic)[str(self.profile_pic).index(f'uploads/{self.pk})/'):] this happens when i try to migrate -
Local and heroku database out of sync (Django/Heroku)
I have been having challenges with my migrations from local to heroku. It appears that the schemas are out of sync. Here is my local database schema from python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict testingland [X] 0001_initial Here is the heroku schemas from heroku run python manage.py showmigrations account [X] 0001_initial [X] 0002_email_max_length admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique socialaccount [X] 0001_initial [X] 0002_token_max_lengths [X] 0003_extra_data_default_dict I believe the problem stems from deleting the migrations folder in my testingland app earlier. I ran python3 manage.py makemigrations testingland and the migrations folder came back but when I run: python manage.py makemigrations git commit -a git push heroku main …