Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How django + restframework implements the parameter interface through inherited classes
When my RegisterView inherits APIView and cannot display parameters, what should I do to make RegisterView display parameters like LoginViewHow to make register display interface parameters like login. -
Error when connecting to a scss file in django
I am trying to connect to my scss file in static, but I get the following error: sequence item 1: expected str instance, WindowsPath found The error supposedly comes from the following line of code in my base.html: <link href="{% sass_src "css/main.scss" %}" rel="stylesheet" type="text/css" /> When I looked up in the Internet, I read that some say it is a specific error that happens for people using a windows os. Do you guys know why this error is happening, and how to solve this issue so that I could use my scss file for the templates? Please ask me any questions. -
How can I get latest record by queryset. like group by
Data name data1 data2 create_date iron man ia ib 1630000000 hulk ha hb 1630000000 hulk hc hd 1630500000 captain ca cb 1630000000 captain cc cd 1630500000 captain ce cf 1630590000 I want to get latest data each name name data1 data2 create_date iron man ia ib 1630000000 hulk hc hd 1630500000 captain ce cf 1630590000 like this wish_data = [ {'name':'iron man', 'data1': 'ia', 'data2': 'ib', 'create_date':1630000000}, {'name':'hulk', 'data1': 'hc', 'data2': 'hd', 'create_date':1630500000}, {'name':'captain', 'data1': 'ce', 'data2': 'cf', 'create_date':1630590000}, ] I tried... Model.objects.filter(**conditions).values_list('name').annotate(cdate=Max('create_date')) => [('iron man', 1630000000), ('hulk', 1630500000), ('captain', 1630590000)]> but i need to other columns... Q Is it possible with ORM? Or do I have to write the logic with for and if statements? -
How to change Django admin url for rewrite urls
I have Django project, which is deployed to kubernetes, where I need to rewrite the admin url to different endpoint. Currently my admin endpoint is mapped as below: url(r'^admin/', admin.site.urls) Which works fine in local and ingress url when I try to access my it using <BASE_URL>/admin. But now I have to rewrite my service url to different endpoint in Kubernetes for example as below: spec: prefix: /app/sevice/admin/ rewrite: /admin/ After this I'm able to access my admin panel home page with ambassador url <AMBASSODER_BASE_URL>/app/service/admin only when I'm already logged-In to admin and after I click on any of the table listed in admin UI it throws me to <AMBASSODER_BASE_URL>/admin> because I can still see admin UI html href /admin/../... Is there any way to make those href to use relative path rather then full path. I mean just the path after /admin. -
Search Bar Problems showing email
My search bar showing me to give it a email address or it will not accept it. Thanks in advance. for email bar def index(request): if request.method =='GET': email = request.GET.get('email') if email: subscribe(email=email).save() views.py def search(request): q = request.GET.get('q') posts = Post.objects.filter( Q(title__icontains = q) | Q(overview__icontains = q) ).distinct() parms = { 'posts':posts, 'title': f'Search Results for {q}', 'pop_post': Post.objects.order_by('-read')[:9] } return render(request, 'all.html', parms)` base.html : -
Django: How to do full-text search for Japanese (multibyte strings) in Postgresql
It is possible to create an index for searching using SearchVector, but However, Japanese words are not separated by spaces, and the full-text search does not work properly. How can I perform full-text search in Japanese (multi-byte character strings)? I thought about implementing a search engine such as ElasticSearch, but other problems came up. If possible, I would like to do FTS with Postgres. # models.py class Post(models.Model): title = models.CharField(max_length=300) search = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["search"])] # update search column Post.objects.update(search=SearchVector('title')) -
Django Show Code in Template if Logged In
In a Laravel Blade template, I can do this to show code only if a user is logged in: @auth <div>Show code only if logged in.</div> @endauth Does Django have a template tag or something similar that does the equivalent? E.g.: {% auth %} <div>Show code only if logged in.</div> {% endauth %} -
Which is better framework Django or Flask? [closed]
I asked this question with my friends but they didn't know about it i am looking for a better framework for Web Development that is coded in Python please help ;/ -
How to add event to multiple dates at the same time in HTMLcalendar
I'm using the htmlcalendar module in Django. When adding an event by setting a period, I want the event to be added at the same time on the relevant date. In the code implemented so far, it is possible to add events only for 1 day. Where do I need to change to get the desired result? models.py class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) leave_date_from = models.DateField(blank=True, null=True) leave_date_to = models.DateField(blank=True, null=True) ----> I just added this field take_over = models.TextField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(leave_date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Leave.objects.filter(leave_date__year=self.year, leave_date__month=self.month, is_deleted=False) cal = f'<table border="0" cellpadding="0" … -
Not Found: /socket.io/
Does anyone have any experience with creating a chat in Django using the python-socketio library? When I launch a Docker container, the backend gives the following error on the Get request: "GET /socket.io/?EIO=3&transport=polling&t=NUzXPq6 HTTP / 1.1" 404 2124 Not Found: /socket.io/ -
I keep getting a 403 forbidden error in Django
Problem 1: I made a notes app. I made a login function, that logs in people. I keep getting an error after I log in and try to create a new note, it is saying "403 forbidden error" in the console. But if I dont log in, it works perfectly. Heres the backend code : @api_view(["POST"]) def login_view(request): data = request.data username = data["username"] password = data["password"] if request.user.is_authenticated: return Response("hpr") else: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response("hpr") return Response("An error occured, please try again later.") this is the login view. I have created a model with a foreign key, that might be the problem too. class Note(models.Model): body = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name="notes", on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] here is the view that creates a note : @api_view(['POST']) def createNote(request): data = request.data note = Note.objects.create( body=data['body'], ) serializer = NoteSerializer(note, many=False) return Response(serializer.data) Problem 2: I also have another doubt. I have a function that gets the notes from the database and displays it. I have made the serialised get all the fields of the note model. But when I try … -
ValueError at /freshleadaction for uploading .csv file in Django
I am stuck on an error in django while uploading a .csv file for fresh leads and I have searched a lot on google for the solution but couldn't find the solution so now decided to upload it so that community can help me. I am displaying the code that I have done so. Models.py: class fresh_leads_model(models.Model): fname = models.CharField(max_length=20) lname = models.CharField(max_length=20) street_number = models.CharField(max_length=20) street_name = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) bedrooms = models.CharField(max_length=20) legal_description = models.CharField(max_length=100) sq_ft = models.CharField(max_length=50) address = models.CharField(max_length=50) orign_ln_amt = models.CharField(max_length=50) prop_value = models.CharField(max_length=50) equity = models.CharField(max_length=255) email = models.CharField(max_length=50) cell = models.CharField(max_length=50) submitted_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(auto_now_add=True) my views.py file for fresh leads upload: @login_required @allowed_users(allowed_roles=['admin']) def upload_fresh_leads(request): get_type = request.GET['type'] lst = [] if request.method == 'POST': leads = Fresh_leads_Form(request.POST, request.FILES) data = request.FILES.getlist('csv') # data = Fresh_leads_Form(request.FILES) # csv_file = request.GET['csv'] # df = pd.read_csv(csv_file) # return HttpResponse(print(df))) # data = [] # message = 2 # return render(request, 'admin/src/tabs/fresh_leads.html', {'message': message}) if get_type == '1': if leads.is_valid(): # csv = data['csv'] for d in data: # df = pd.read_csv(d, usecols=['Owner First Name']) # return HttpResponse(df.to_string()) df = pd.read_csv( d, dtype='str', usecols=[ 'Owner First … -
pass field to distinct() in Django
I have a Django web app, using MYSQL. model.py class CourseInfo(TimeStampedModel): code = models.CharField(max_length=20, db_index=True) title = models.CharField(max_length=190) discipline_code = models.CharField(max_length=20, blank=True, null=True) pattern = models.CharField(max_length=120, choices=PRESENTATION_PATTERN, blank=True, null=True, help_text="Presentation Pattern") I want to achieve this filter: query_results_2 = CourseInfo.objects.filter(discipline_id=id).values('discipline_code', 'code', 'title', 'pattern').distinct('discipline_code', 'code') But seems like in mysql, distinct() could not have parameters. How could I achieve this function?---- get 'discipline_code', 'code', 'title', 'pattern' fields but only use 'discipline_code', 'code' for distinct filter. -
How to render contents of two models in a single template where one model is linked by Foreign Key through another in django?
I am trying to create a site for financial purpose. I have two models "Company" and "Reports". Reports model has a foreign key linked to Company. I want to render contents of Company and Reports in a single template in a detail view. When i try to render only one of the model's content is shown not both.. Is there any solution to this? -
Digital Ocean Django Buckets
I am following along on this youtube tutorial: https://www.youtube.com/watch?v=AeCZvXZn5dg&list=PLEsfXFp6DpzRMby_cSoWTFw8zaMdTEXgL&index=77 and I've read this question: DigitalOcean spaces with django code:conf.py AWS_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME="unlock-optimal-performance" AWS_S3_ENDPOINT_URL="https://nyc3.digitaloceanspaces.com" AWS_S3_OBJECT_PARAMETERS={ "CacheControl":"max-age=86400" } AWS_LOCATION="https://unlock-optimal-performance.nyc3.digitaloceanspaces.com" DEFAULT_FILE_STORAGE="cmfitness.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE="cmfitness.cdn.backends.StaticRootS3Boto3Storage" backends.py: from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' and my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'), # https://unlock-optimal-performance.nyc3.digitaloceanspaces.com STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles-cdn") # in production we want cdn MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles-cdn', 'uploads') from .cdn.conf import (AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_STORAGE_BUCKET_NAME,AWS_S3_ENDPOINT_URL,AWS_S3_OBJECT_PARAMETERS,AWS_LOCATION,DEFAULT_FILE_STORAGE,STATICFILES_STORAGE) The Error: Traceback (most recent call last): File "C:\Unlock-Optimal-Performance\manage.py", line 23, in <module> main() File "C:\Unlock-Optimal-Performance\manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 194, in handle collected = self.collect() File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 118, in collect handler(path, prefixed_path, storage) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 345, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 255, in delete_file if self.storage.exists(prefixed_path): File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\storages\backends\s3boto3.py", line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 388, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 694, in _make_api_call http, parsed_response = self._make_request( File "C:\Users\Deborah\anaconda3\envs\main\lib\site-packages\botocore\client.py", line 714, in _make_request return self._endpoint.make_request(operation_model, request_dict) … -
Get data from Django to Vue Template
I'm trying to get data from Django to Vuetemplate variables. views.py def index(request): myvar = 1 return render(request, 'index.html',{'myvar':myvar}) in index.html <span> {{ myvar }} </span> Is working, and shows 1, but how can i get this 1/myvar to data inside of the vue instance? var app = new Vue({ el: "#app", data: { // here i need the data/value of myvar } -
How to throw django 404 error as error message on the same page
I am trying to query an instance of a particular model, FoodRedistributor and I would like to throw a pop up error message on the same page if a FoodRedistributor of the given name does not exist. I tried doing Http404 but that redirects me to a 404 page which is not how I would like the user to see the error. Using the messages.info does not give me any output. if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") try: user = FoodRedistributor.objects.get(name=username) except: raise Http404("No food redistributor matches the given query.") -
Different bootstrap(V 4.0) alerts not getting displayed as expected
{% if form.errors %} <div class="alert alert-danger" role="alert"> {% for field in form %} <p>{{field.errors}}</p> {% endfor %} </div> {% endif %} {% if messages %} <div class="alert alert-success" role="alert"> {% for message in messages %} <p>{{message}}</p> {% endfor %} </div> {% endif %} This is a Django project and the above is the order in which I have placed the alerts. The thing is all alerts are getting displayed in as alert-danger, i.e both the form.errors & message are getting displayed within the alert-danger. How can we avoid this isssue? -
heroku failing to process requirements.txt "because these package versions have conflicting dependencies."
I have pushed this project many times before and have made no changes to the requirements.txt file located in the root directory of the project, however. Heroku will no longer accept the same requirements.txt file citing a dependency issue Heroku still opens the last valid push to allow me to "pip freeze" pushed heroku requirements.txt appnope==0.1.2 asgiref==3.4.1 backcall==0.2.0 backports.entry-points-selectable==1.1.0 blis==0.7.4 catalogue==2.0.6 certifi==2021.5.30 charset-normalizer==2.0.4 ChatterBot==1.0.4 chatterbot-corpus==1.2.0 click==8.0.1 colorgram.py==1.2.0 cymem==2.0.5 debugpy==1.4.3 decorator==5.1.0 distlib==0.3.3 dj-database-url==0.5.0 Django==3.2.8 django-filter==2.4.0 django-heroku==0.0.0 django-simple-chatbot==0.0.9 django-widget-tweaks==1.4.8 djangorestframework==3.12.4 en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.1.0/en_core_web_sm-3.1.0-py3-none-any.whl entrypoints==0.3 filelock==3.3.0 future==0.18.2 greenlet==1.1.2 gunicorn==20.1.0 heroku==0.1.4 httpie==2.4.0 huggingface-hub==0.0.12 idna==3.2 ipykernel==6.4.1 ipython==7.28.0 ipython-genutils==0.2.0 jedi==0.18.0 Jinja2==3.0.1 joblib==1.0.1 jupyter-client==7.0.3 jupyter-core==4.8.1 line-bot-sdk==1.20.0 MarkupSafe==2.0.1 mathparse==0.1.2 matplotlib-inline==0.1.3 murmurhash==1.0.5 nest-asyncio==1.5.1 nltk==3.6.2 numpy==1.21.2 packaging==21.0 parso==0.8.2 pathy==0.6.0 pexpect==4.8.0 pickleshare==0.7.5 Pillow==8.3.2 Pint==0.17 pipenv==2021.5.29 platformdirs==2.4.0 preshed==3.0.5 print==1.3.0 prompt-toolkit==3.0.20 psycopg==3.0b1 psycopg2==2.9.1 psycopg2-binary==2.9.1 ptyprocess==0.7.0 pydantic==1.8.2 Pygments==2.10.0 pymongo==3.12.0 pyparsing==2.4.7 PySocks==1.7.1 python-dateutil==2.7.5 pytz==2021.3 PyYAML==5.4.1 pyzmq==22.3.0 regex==2021.8.28 requests==2.26.0 requests-toolbelt==0.9.1 sacremoses==0.0.46 six==1.16.0 smart-open==5.2.1 spacy==3.1.3 spacy-alignments==0.8.3 spacy-legacy==3.0.8 spacy-transformers==1.0.6 SQLAlchemy==1.2.19 sqlparse==0.4.2 srsly==2.4.1 textblob==0.15.3 thinc==8.0.10 tokenizers==0.10.3 torch==1.8.1+cpu torchvision==0.9.1+cpu tornado==6.1 tqdm==4.62.2 traitlets==5.1.0 transformers==4.9.2 turtle==0.0.1 typer==0.4.0 typing-extensions==3.10.0.2 urllib3==1.26.6 virtualenv==20.8.1 virtualenv-clone==0.5.7 wasabi==0.8.2 heroku now tells me the following error when i try to deploy my latest version using identical requirements.txt files. The conflict is caused by: The user requested PyYAML==5.4.1 chatterbot-corpus 1.2.0 depends on PyYAML<4.0 and >=3.12 To fix this you could … -
Error when pip installing Django-Sass-Processor
I get the following error when running the code: pip install libsass django-compressor django-sass-processor Here is the error: ERROR: Command errored out with exit status 1: command: 'c:\users\jsooh\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"'; __file__='"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jsooh\AppData\Local\Temp\pip-record-0h133shl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\jsooh\appdata\local\programs\python\python39\Include\rcssmin' cwd: C:\Users\jsooh\AppData\Local\Temp\pip-install-htugdym8\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\ Complete output (9 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 copying .\rcssmin.py -> build\lib.win-amd64-3.9 running build_ext building '_rcssmin' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\jsooh\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"'; __file__='"'"'C:\\Users\\jsooh\\AppData\\Local\\Temp\\pip-install-htugdym8\\rcssmin_25699a9d5e6f4f74bfe031fe694d8529\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\jsooh\AppData\Local\Temp\pip-record-0h133shl\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\jsooh\appdata\local\programs\python\python39\Include\rcssmin' Check the logs for full command output. Does anyone know how to fix this? Thanks, and please let me know if you have any questions. -
Calendar lost formatting after adding bootstrap
My site is used to add and delete items on and from the calendar, my site looked like this at first then when I added the bootstrap libraries, my calendar lost the formatting and the checkbox to delete items disappeared: enter image description here enter image description here -
How to get the entity after form.save()
I have form class which receive the POST request from web browswer. class WaveFileForm(forms.ModelForm): class Meta: model = WaveFile fields = ('description', 'document', ) then it will be saved as model entity by form.save() if request.method == 'POST': form = WaveFileForm(request.POST, request.FILES) if form.is_valid(): form.save() print(form.cleaned_data.get('document'))// it returns filename, but I want to have saved file path, so I want entity itself WaveFile.objects.get("(saved_one)") But now I want to get the entity immediatelly it self which is saved by form.save() How can I do this?? -
'datetime.date' object has no attribute 'tzinfo'
I don't have any date type field neither in my model nor in the database. What is the reason to get this error? enter image description here enter image description here enter image description here -
Django: automatically save foreign key fields
I'm trying to populate automatically my foreign key field when my form is submitted. I successeffuly set the user field but I have trouble with form.instance.staff and form.instance.event since I'm getting error like 'User' object has no attribute 'staffduty' . I'd also like to pass and save some variables like the date_appointment and the event name but I don't know how to do so. Thanks for your help models.py class Event(models.Model): name = models.CharField(max_length=255) staff_needed = models.PositiveIntegerField() date = models.DateField() def __str__(self): return self.name def get_absolute_url(self): return reverse('event_details', args=[str(self.id)]) class StaffDuty(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) date_work = models.DateField() shift = models.CharField(max_length=255) def __str__(self): return self.event.name | str(self.date_work) class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) def __str__(self): return self.event.name | str(self.staff.date_work) def get_absolute_url(self): return reverse('home') views.py class StaffDutyAddView(CreateView): model = StaffDuty form_class = StaffDutyForm template_name = 'reservation.html' success_url = reverse_lazy('home') class UserAppointmentAddView(CreateView): model = UserAppointment form_class = UserAppointmentForm template_name = "reservation.html" def form_valid(self, form): form.instance.user = self.request.user.userinformation form.instance.staff = StaffDuty.objects.filter(user=self.request.user.staffduty).first() #form.instance.date_appointment = # add date_work from StaffDuty class form.instance.event = Event.objects.filter(user=self.request.user.event).first() #form.instance.event_name = # add name of the event from Event class return super(UserAppointmentAddView, … -
How to get a value of foreign key between apps of Django?
Need a little bit of help :) I have two apps (accounts and company). accounts/models.py class Organization(models.Model): organization_name = models.CharField(max_length=20) #custom user model class NewUser(AbstractBaseUser): which_organization = models.ForeignKey(Organization, on_delete = models.CASCADE, null=True, blank=True) #other fields company/models.py from accounts import models as accounts_model class Branch(models.Model): branch_name = models.ForeignKey( accounts_model.Organization, on_delete = models.CASCADE, null=True, blank=True) #other fields company/forms.py from .models import Branch class BranchForm(forms.ModelForm): class Meta: model = Branch fields = '__all__' company/views.py from .forms import BranchForm def some_function(request): form = BranchForm() if request.method == 'POST': form = BranchForm(request.POST, request.FILES) if form.is_valid(): form.save(commit=False) form.branch_name = request.user.which_organization print("User organization: ", request.user.which_organization) form.save() return render(request, 'company/index.html', {'form': form}) P.s. Everything works well. I am able to print the user's organization with print("User organization : ", request.user.which_organization) But cannot save it with form.branch_name = request.user.which_organization in views.py. Instead of getting exact organization name of the user, created object lists all organization names... How to achieve it?)