Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing django user login failing to redirect appropriately (url issue?) with selenium and pytest
I've got a project that I'm having some issues with and I think it might have to do with the URL's. My project URL's look like this: urlpatterns = [ path("", include("dock.urls"), name="dock"), path("admin/", admin.site.urls, name="admin"), ] My app (named dock) URL's look like this: urlpatterns = [ path("", views.dock, name="dock"), path( "login/", LoginView.as_view(template_name="dock/login.html"), name="login", ), path("dock/", views.dock, name="dock"), path( "logout/", LogoutView.as_view(template_name="dock/thanks.html"), name="logout", ), ] My views.py is pretty simple and only has the dock method in it since I use the Django built-ins for logging in and logging out: @login_required(login_url="dock:login") def dock(request): if not request.user.groups.all(): return render(request, "dock/no_docks.html") return render( request, "dock/dock.html", { "apps": App.objects.filter( groups__in=request.user.groups.all() ).distinct() }, ) My test looks like this (I create the user in the setUp method and can confirm it is all setup properly): def test_log_in_for_userone(self): # Opening the link we want to test self.client.get(self.live_server_url) assert "log in" in self.client.page_source time.sleep(2) self.client.find_element_by_id("id_username").send_keys("userone") self.client.find_element_by_id("id_password").send_keys("thepassword") self.client.find_element_by_id("log_in").click() time.sleep(2) # Check the returned result assert "You are logged in!" in self.client.page_source When I run this test - it fires everything up fine, opens firefox, enters the username and password and the user is appropriately logged in (according to the timestamps in the database); however the browser itself … -
Docker Compose with Django error when I add new command to compose
Docker compose doesn't recognize an echo command. Recently I added the command: echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', '2222bbbb')" | python manage.py shell Compose code: version: '2' services: postgres: image: postgres container_name: app_postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres django: image: python:3.6.8 container_name: app_django environment: - DJANGO_SETTINGS_MODULE=project.settings_staging - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_HOST=postgres working_dir: /code volumes: - ./:/code - ./requirements.txt:/code/requirements.txt ports: - 6000:8000 command: bash -c "pip install -r requirements.txt && python manage.py migrate --noinput && echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', '2222bbbb')" | python manage.py shell && python manage.py test" depends_on: - postgres When i execute this compose Django finished with next message: app_django | Apply all migrations: account, admin, auth, authtoken, contenttypes, filters, sessions, sites, users app_django | Running migrations: app_django | No migrations to apply. app_django | from app_django exited with code 0 Django doesn't recognize the echo command -
How to Assign States to Viewers of Django Web Application?
Problem Statement I'm working on building out a single-page Django web app and am trying to implement the following functionality: - All viewers of the page are associated with a state. There are buttons on the page which enable viewers to change their state. - The application stores a list of all current viewers of the page, and their associated states. Whenever a user changes their state, this stored list of viewers updates with this new information. - The application should display how many people are online (viewing the page) at a given time. Blockers I'm unsure of how to collect a list of all current viewers of a page in Django, nor how to collect how many users are currently viewing the page. Ideally, my application would not require a login to use: therefore, I'd rather either associate viewer state with a user object that doesn't require sign-in, or not associate viewer state with a user object (I'm still new to user objects though, so forgive me if this point doesn't make complete sense). What I'm Looking For A discussion of higher-level strategies which I can use to implement this functionality, or other places to look to gain insight … -
How to load a form with options from a querryset in Django
I am trying to load a form with user payment options, so this is needing a query set from the users profile. I have tried initializing the form (below code) with user being required. The issue is if I make self.options when I am initializing. I have also tried creating the choice_field class ListPaymentOptionsForm(forms.Form): choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=options) def __init__(self, user, *args, **kwargs): self.options = list(UserPaymentOption.objects .values_list('last_four', 'last_four') .filter(user=user, active=True)) super(ListPaymentOptionsForm, self).__init__(self, *args, **kwargs) The above code gives this error: choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=options) NameError: name 'options' is not defined Then I have tried adding the options on the view instead like this form = ListPaymentOptionsForm(user=request.user) form.fields['choice_field'].choices = list(UserPaymentOption.objects .values_list('id', 'last_four') .filter(user=request.user, active=True)) This causes an error with the form being used on post, it seems like because it is trying to validate the options is allowed but in the actual form the option is set. The reason I believe this is the problem is this is what the form returns as form=ListPaymentOptionsForm(request.POST) print(form) This returns: Choice field:Select a valid choice. 54 is not one of the available choices. Any input on this would be very appreciated. Thanks. -
How to login with different user type in django?
How can I properly authenticate a type of user based on the models below. It only seems to be working for Manager type therefore I wonder what is wrong about my implementation. models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class User(AbstractUser): is_customer = models.BooleanField(default=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers') bio = models.CharField(max_length=200) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='managers') company_name = models.CharField(max_length=50) def __str__(self): return self.user.username forms.py from django.contrib.auth.models import User from django import forms from django.contrib.auth import ( authenticate, login, ) class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('This user does not exist') if not user.check_password(password): raise forms.ValidationError('Incorrect password') if not user.is_active: raise forms.ValidationError('This user is not active') return super(UserLoginForm, self).clean(*args, **kwargs) views.py from django.contrib.auth import ( authenticate, login, ) from django.shortcuts import ( render, redirect ) from user.forms import UserLoginForm def login_view(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user.is_active: # Redirect to the appropriate type of … -
How to redirect from a CreateView of model A to another CreateView of a model B while passing key information from model A to the next view?
I am new to Django and do not know what I need to know to do this task. I am tasked with creating a web app that has two models. Model A is the employee and model B is a company that contains many employees. During signup, I have a form for model A. Once model A form is filled out, I need to pass an id from the employee to the company signup url so that when I save the company model to the table, I can make sure that the employee id is stored and so the two tables are related. How do I go about sending the employee_id to the company form page? Do I need to use some sort of redirect? Flow: dashboard/employee_signup -> dashboard/company_signup -> completed_signup I've looked through multiple tutorials on Django and most seem to be too simple to solve what I need done. Here is my EmployeeSignUpView. Right now it redirects to a 'login' page. I need to instead redirect to a CompanySignUpView while passing along an employee_id. A company can't have zero employees, so the first person to signup for the company needs to be stored in the company model. The … -
issues with template after a ajax request in django
i have added like feature to my project ajax and django is perfectly working fine ajax is able to send a request and django is able to recieve it and vice versa but the thing where i'm stuck is i cant update it in my template properly ,i'm able to update the changes but that not happening for all objects whenever i click on like button the count is getting incremented for only one object lets say i have two objects with title facebook and instagram when i click on facebook the count increments to 1 and click the same button it decrements to 0 its perfectly working but when i click the like button for my instagram object instead of updating its own object its is updating the facebook object the facebook likes counts is incrementing/decrementing i'm not sure if the issue is with the template or it is with the ajax part AJAX: $('button').on('click',function(event){ event.preventDefault(); var element=$(this); $.ajax({ url: $(this).attr("data-href"), type:'GET', success:function(response){ // $('#lik').html(response); // console.log(response); // alert(response.message); // alert('Company likes count is now ' + response.likes_count); // document.getElementById('like-count').innerHTML = response.like_count; // $('#like_count').html(response.likes_count); $('#lik').html(response.likes_count); // element.html(' ' + response) } }); }); template : <div class="reaction" > <button … -
Creating a Django object from a dict - obj must be an instance or subtype of type
I'm trying to create an object from a json: r = requests.post(url, headers=headers, data=data) response = r.json() link = MyObject.objects.create(**response['data']) link.save() This generates the following error: web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method web_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) web_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 422, in create web_1 | obj.save(force_insert=True, using=self.db) web_1 | File "models.py", line 106, in save web_1 | super(Issue, self).save(*args, **kwargs) web_1 | TypeError: super(type, obj): obj must be an instance or subtype of type While reponse is valid and everything else seems to be okay, I don't see from where comes this error. Any ideas ? -
How to access the __str__ method of a model via a ForeignKey?
I have created a File model and a Folder model. The File model is connected to the Owner (User) and a Folder via a Foreign key. Now I want to upload the file at the path: 'owner_username/folder_title'. My question is how to access the str method of the Folder model using the ForeignKey, from inside the File Model ? My guess was to set at the FileField the argument upload_to equal to str(folder) but as a result my file was uploaded at:<django.db.models.fields.related.ForeignKey>/graph2.jpg at models.py: class Folder(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length = 20) def __str__(self): return self.title class File(models.Model): owner = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) folder = models.ForeignKey(Folder, related_name = 'files', on_delete=models.CASCADE, default="") file = models.FileField(upload_to = !!!!?ownername/foldername?!!!!) def __str__(self): return str(self.file) I expect somehow to upload the file at the path that has the following format: nameOfTheOwner/nameOfTheFolder -
django crop already loaded image (without using the input tag)
This solution lets the user crop the image when he uploads it. What I want to do is to let him do the crop on an already loaded image after clicking on a "crop" button for example. The big picture here is that the user uploads a pdf file, I convert it into images, he selects the one he wants to work on, THEN, I need him to select the Region Of interest for me to work on by cropping that selected image. Any approach on how I can do that? -
How do I get Python to execute a command the same way I run it on the command line (bash)?
I'm using Mac Mojave. I can run this command from my termianl (bash) successfully ... PATH=/Users/davea/Documents/workspace/starter_project/selenium/dev/:$PATH selenium-side-runner -c "goog:chromeOptions.args=[--headless,--nogpu] browserName=chrome" /tmp/81a312ad-8fe1-4fb0-b93a-0dc186c3c585.side I would like to run this from Python (3.7)/Django, so I wrote the below code SELENIUM_RUNNER_CMD = "/usr/local/bin/selenium-side-runner" SELENIUM_RUNNER_OPTIONS = 'goog:chromeOptions.args=[--headless,--nogpu] browserName=chrome' SELENIUM_WORKING_DIR = "/Users/davea/Documents/workspace/starter_project/selenium/" SELENIUM_DRIVER_PATH = "/Users/davea/Documents/workspace/starter_project/selenium/dev" ... def execute_selenium_runner_file(file_path): print("runner cmd:" + settings.SELENIUM_RUNNER_CMD) new_env = os.environ.copy() new_env['PATH'] = '{}:' + settings.SELENIUM_DRIVER_PATH + ':/usr/local/bin'.format(new_env['PATH']) out = Popen([settings.SELENIUM_RUNNER_CMD, "-c", settings.SELENIUM_RUNNER_OPTIONS, file_path], cwd=settings.SELENIUM_WORKING_DIR, env=new_env, stderr=STDOUT, stdout=PIPE) t = out.communicate()[0], out.returncode return t But when running through Python, the process dies with the following error ... Running /tmp/c847a3ce-c9f2-4a80-ab2a-81d9636c6dab.side Error: spawn find ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:248:19) at onErrorNT (internal/child_process.js:431:16) at processTicksAndRejections (internal/process/task_queues.js:84:17) The exit code is "1". I'm not clear on what I need to do to get Python to execute my command line the same way I'm able to run it the same way I do through bash. Any advice is appreciated. -
How to override Model.delete() so that no cascade deletion ever happens for an instance?
I need to customize a Model.delete() so that it doesn't perform any cascade deletes and instead raises an exception if there are any objects that reference the instance. It seems the default implementation doesn't allow to skip the deletion of related objects: def delete(self, using=None, keep_parents=False): using = using or router.db_for_write(self.__class__, instance=self) assert self.pk is not None, ( "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) ) collector = Collector(using=using) collector.collect([self], keep_parents=keep_parents) return collector.delete() How can I make sure Django doesn't cascade delete any related objects? -
How to update the total score in a trivia game backend efficiently?
I am trying to implement a trivia game backend in Django. I have several models but I will mention two of them which are Score and Player. Here is the important part of Player: class Player(BaseModel, AbstractUser): overall_score = models.PositiveIntegerField(default=0) class Meta: ordering = ['-overall_score'] and here is the important part of Score: class Score(BaseModel): score = models.PositiveSmallIntegerField() player = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='scores') def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.player.overall_score += self.score There are other fields in Score and Player but I did not mention them. What I am trying to do is letting the player to solve a quiz, and after saving the single quiz score to the database, I want to calculate the all-the-time overall score which is the sum of all of his scores. It is just a sum, not an average. Is my implementation of save method correct? I am afraid that the saving procedure will fail for any reason, but the overall_score would be already updated. Also, I am afraid that if I used aggregation, it will not be an efficient way because every time the user will access the leaderboard, the sum will be calculated which can be avoided by saving the sum so … -
django extending Abstract User, not allowing non-unique username
I have a model like so: class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am creating multiple instances of User, without passing a username. I am hitting this error: def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_user_username_key" DETAIL: Key (username)=() already exists. How do I fix this? -
periodic task on user using celery or iterate all users with celery beat
I want to perform certain operations on the Django "User" model once the last time since logging in is more than 60 days. I want to know what is the best practice for these kinds of operations. I thought of the following: 1- when the user logs in I start a Celery task that activates after 60 days to do the operation from datetime import datetime, timedelta send_date = datetime.utcnow() + timedelta(days=2) email_user.apply_async([user], eta=send_date) 2- set up a Celery Beat task that runs everyday at a certain time and iterate over all the users in the database to check every user's last login time and if the last login time is > 60 the perform the operation users = User.objects.all() for user in users: email_user(user) first method would cause too many tasks to be open at the same time and I don't know what would happen in case of system failures will the tasks remain or not? and the second method would iterate all the users in the DB everyday but it will be only 1 task I am not sure which way is the best or if there is a 3rd better way. -
Django newly created instance - DateTime field is type 'str'
I am using Django 2.2.3 and Celery 4.3.0 One of my celery tasks creates a new instance of one of my django models and saves it. After I have saved that new instance, if i access one of the fields of the saved instance called DateTimeStamp which is a DateTimeField, the value returned is a string object. However, if i return the same instance from the database, the value of DateTimeStamp is a datetime.datetime object. my model in models.py: class StgAvailabilityConfirmation(models.Model): ServiceType = models.CharField(max_length=50) ContractID = models.CharField(max_length=20) Confirmation = models.CharField(max_length=8) FileReason = models.CharField(max_length=200, blank=True, null=True) DateTimeStamp = models.DateTimeField() status = models.TextField(null=True, blank=True) the code in django_tasks.py (where top_level_record is a dictionary new_instance = target_model(**top_level_record) new_instance.save() print(top_level_record) print(new_instance.pk) created_instance = target_model.objects.get(pk=new_instance.pk) print(new_instance.DateTimeStamp) print(type(new_instance.DateTimeStamp)) print(created_instance.DateTimeStamp) print(type(created_instance.DateTimeStamp)) output from worker: [2019-07-24 14:27:32,670: WARNING/ForkPoolWorker-16] {'ServiceType': 'STOR_FLEXIBLE', 'ContractID': '35.41', 'Confirmation': 'ACCEPTED', 'DateTimeStamp': '2018-07-25T13:01:00.000'} [2019-07-24 14:27:32,670: WARNING/ForkPoolWorker-16] 62 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] 2018-07-25T13:01:00.000 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] <class 'str'> [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] 2018-07-25 13:01:00+00:00 [2019-07-24 14:27:32,693: WARNING/ForkPoolWorker-16] <class 'datetime.datetime'> What is the cause of this behaviour? -
why this variable(userinfo.user.addinfo) is not defined in react graphql?
I want to get information about addinfo of user. if i coding { userinfo(token: "token") { user { id addinfo } } } in 127.0.0.1:8000/graphql, i get the data like that { "data": { "userinfo": { "user": { "id": "4", "addinfo": false } } } } but below code show me user is undefined. console.log(userinfo) show me the correctly data. export default () => { const { data: { isLoggedIn } } = useQuery(QUERY); const { data: { userinfo } } = useQuery(Addinfo_QUERY, { variables: { token: localStorage.getItem("jwt") } }); return ( <React.Fragment> {console.log(userinfo.user.addinfo)} <HashRouter> <AppPresenter isLoggedIn={isLoggedIn} addinfo={addinfo} /> </HashRouter> </React.Fragment> ); }; why user is not defined? i cannot understand. -
Dynamically update form_list to point to some subclass(known at run time only) for a step, and render that form
I have a scenerio where the forms to be used for steps are known at runtime only. Currently, form_list is static for every step. But in the updated requirements, Each step has some runtime logic to determine the corresponding form_class. I was thinking of a way to update the form_list dynamically. I have tried overriding get_form_list, which uses the runtime logic to determine the form, and modifies form_list accordingly. urls.py named_forms = views.FormView.form_list contact_wizard = views.FormView.as_view(named_forms, url_name=<the url name>, done_step_name='finished') url-patterns = [ path('path', contact_wizard, name='form1') ] Wizard class FormView(NamedUrlSessionWizardView,): form_list = ( //static one ("step-one", FormStepOne), ("step-two", FormStepTwo), ("step-three", FormStepThree), ) def get_form_list(self): //updates form_list according to some logic self.form_list = OrderedDict() self.form_list["step-one"] = self.integration_class.step_one_form_class self.form_list["step-two"] = self.integration_class.step_two_form_class self.form_list["step-three"] = self.integration_class.step_three_form_class return super().get_form_list() Form_list is getting updated correctly,but the form is not getting rendered according to the new form-list. Rendered form is getting picked up from old static form_list only. -
Django - context modified when passing to template
I have a function which return a presign url for a S3 object, and I want to use it in my template. Here is my function in views.py: def player_index(request): mpd_url = update_file.mpd_url() vtt_url = update_file.vtt_url() context = { 'mpd_url': mpd_url, 'vtt_url': vtt_url, } return render(request,'index.html',context) and here is a part of my template with context: var url = '{{ mpd_url }}'; player.vttThumbnails({ src: '{{ vtt_url }}' }); But it seems like urls doesn't match in my function and in my template: when I print it in views.py : https://realtime-video-logs.s3.amazonaws.com/test/manifest.mpd?AWSAccessKeyId=AKIAVT3T733IUIUYBBMB&Signature=ZA9mgVjXvBShKAdvjw6hgeOwC1o%3D&Expires=1563980730 and in my template : https://realtime-video-logs.s3.amazonaws.com/test/thumbs.vtt?AWSAccessKeyId=AKIAVT3T733IUIUYBBMB&amp;Signature=jqDfi15GLB77DmzrNkVn743HPdA%3D&amp;Expires=1563981729 the '&' is replace by ';' and I don't understand why. -
recognizing template file names in PyCharm
When looking at a typical view in Django, there's usually an icon in the margin beside the template filename passed to render. You can also click on the string and hit "Ctrl+B" to jump to the template. I have my own methods that I pass a string defining which template to use and it'd be nice if I could have PyCharm recognize that and allow me to quickly jump to the file. Is there a way to get PyCharm to recognize that method argument as being a template filename? -
How to render a custom form in a django inline block?
I like to render a custom form in a TabularInline. On this form I want to have some custom fields which I will write to a model inside the save method. The custom form should not be assoziated to a model. I hope the following code will make it more clear: class MyInLine(admin.TabularInline): form = MyForm class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(max_length=100) def save(self): # do something with name pass -
KeyError in city name
I have made an small weather web app in django & it is working properly but when a wrong city name is entered it start showing KeyError page. from django.shortcuts import render, redirect from django.contrib import messages import requests # Create your views here. #search page def search(request): return render(request, 'index.html') #forecast result page def forecast(request): c = request.POST['city'] url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=7fee53226a6fbc936e0308a3f4941aaa&units=metric'.format(c) r = requests.get(url) data = r.json() weather = { 'description': data['weather'][0]['description'], 'icon': data['weather'][0]['icon'], 'city': c.title(), 'temperature': data['main']['temp'] } print(r) return render(request, 'weather.html', {'weather': weather}) On entering wrong city name it is giving KeyError,So I want that instead of giving KeyError django will redirect it to my homepage i.e index.html with an error message below it. -
\u0000 cannot be converted to text in django/postgreSQl
i have a project with django .on the host when i want to upload an image sometime error occurred(problem with specific images)! the below show how i resize uploaded images: def save_files_to_media(request, is_public=False, klass=None, conversation=None): from apps.file.models import File fs = FileSystemStorage() file_items = {} for data_item in request.data: file_match = re.search('^fileToUpload\[(\d+)\]$', data_item) if file_match and file_match.groups(): item_index = file_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['file_to_upload'] = request.data[data_item] else: optimize_match = re.search('^optimizeType\[(\d+)\]$', data_item) if optimize_match and optimize_match.groups(): item_index = optimize_match.groups()[0] if item_index not in file_items: file_items[item_index] = {} file_items[item_index]['optimize_type'] = request.data[data_item] files = [] for file_item_key in file_items: input_file = file_items[file_item_key]['file_to_upload'] # TODO: checking validation. if input_file.name is not exist optimize_type = file_items[file_item_key].get('optimize_type') file_uuid = str(uuid4()) if is_public: orig_filename, file_ext = splitext(basename(input_file.name)) directory_name = join(settings.MEDIA_ROOT, file_uuid) filename = file_uuid + file_ext else: directory_name = join(settings.MEDIA_ROOT, file_uuid) mkdir(directory_name) filename = input_file.name filepath = join(directory_name, filename) fs.save(filepath, input_file) is_optimized = False if optimize_type == 'image': is_success, filepath = image_optimizer(filepath) filename = basename(filepath) is_optimized = is_success file_obj = File( orig_name=filename, uuid=file_uuid, md5sum=get_md5sum(filepath), filesize=get_filesize(filepath), meta=get_meta_info(filepath), is_optimized=is_optimized, creator=request.user ) if is_public: file_obj.is_public = True else: file_obj.klass = klass file_obj.conversation = conversation file_obj.save() files.append(file_obj) return files here is the error i got with … -
How do I check if users belongs to a certain model
I have models: Student, Teacher, and CustomUser. A CustomUser belongs either to student or teacher. When logged in, I want to check if the user is instance of student or teacher in the template html. I've tried the following, but it doesn't work. {% if user is a student %} <a class="dropdown-item" href="{% url 'edit_student_profile' %}">Profile</a> {% elif user is a teacher %} <a class="dropdown-item" href="{% url 'edit_teacher_profile' %}">Profile</a> {% else %} <a>Error. Go signup as teacher or student!</a> {% endif %} -
This is a number guess generator, Please help to pass arguments to checker() function
This is a program for matching out input with random number generated by a function. There are three functions, 'index()' for display the webpage, there we can input a value to check with the random number generated by rangen() , 'rangen()' for generating the random number, 'checker()' for checking the values. here I need to pass the value generated by 'rangen()' to my 'checker()' how it is possible? views.py from django.shortcuts import render from django.http import HttpResponse import random # Create your views here. def rangen(request): rannumber= random.randint(1,3) print(rannumber) return rannumber def index(request): return render(request,'generator/index.html') def checker(request): print(rannumber) if request.method=='POST': innum = int(request.POST['inputnumber']) print(innum) if (rannumber==innum): flag = 'Congratulation!!! Number Matched' return render(request,'generator/index.html',{'flag':flag}) elif(innum>rannumber): flag = 'Oops!!! You Entered a High Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) else: flag = 'Oops!!! You Entered a Low Value, Try Again!!!' return render(request,'generator/index.html',{'flag':flag}) index.html <div class="formclass"> <h1>Random Generator</h1> <form action="checker" method="post"> {% csrf_token %} <h3>Enter you guess</h3> <input type="text" name="inputnumber" placeholder="Enter Your Guess" required><br><br> <button type="submit" name="button">Submit</button> <h1>{{flag}}</h1> </form> </div> No errors when I run the server, but when i provide my guess value it showing ' NAME ERROR: name 'rannumber' is not defined'