Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django calculate percentage for population pyramid
I have a data set with population by gender and age groups, 0-4 men population, 0-4 women population etc. I tried calculate percantage in views.py but it didn't work well. so i want to it calculate one time in models.py and save it in my database. class Pyramid(models.Model): city = models.CharField(max_length=15) year = models.IntegerField(default=0) men_population_0_4 = models.IntegerField(default=0) women_population_0_4 = models.IntegerField(default=0) men_population_5_9 = models.IntegerField(default=0) women_population_5_9 = models.IntegerField(default=0) . . . men_population_90_over = models.IntegerField(default=0) women_population_90_over = models.IntegerField(default=0) def __str__(self): return '%s %s' % (self.city, self.year) so firstly i need calculate total men and women population then calculate percentage according to each of gender and age group in models.py and storage it to database. -
How to show category to user
I practice coding with html and django and I have a project "Movie Reviews" and I have some question. how to show category for user who often click that category? e.g You often like to chose Romantic category.Website should show romantic category to you when you come to this website again.(already login) sorry for my English.I'm beginner for English and Coding. Thankyou -
Django update form for users: set current user's group by default to the group choice in the form
In my website, Staff members can modify user's fields, and change their permission group. However, the group choice field is not set by default to the current user's group. I searched and tried something using init in the form but I get 'ManyToManyDescriptor' object has no attribute 'all'. N.B: User is assigned to only one permission group. views.py # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): i = User.objects.get(id=id) if request.method == 'POST': form = UpdateForm(request.POST, instance=i) if form.is_valid(): user = form.save() user.groups.clear() if form.cleaned_data['group_name'] == 'Staff': user.is_staff = True else: user.is_staff = False # remove staff status is user is no longer a Staff member group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) user.save() messages.success(request, "User has been updated!") return redirect('accounts:users') else: form = UpdateForm(instance=i) return render(request, 'accounts/update_user.html', {'form': form, 'username': i, 'i': i.id})``` forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'group_name', 'is_active', 'password',) def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.initial['group_name'] = [User.groups.all()[0].name] -
Django Model error: Related model cannot be resolved
I'm creating a simple Django Model to use with Django Rest Framework. Suppose this model: from django.db import models class DeviceInfo(models.Model): device_id = models.IntegerField(primary_key=True) def __str__(self): return str(self.device_id) class CenterCommands(models.Model): device_object = models.ForeignKey( DeviceInfo, on_delete=models.CASCADE) command = models.CharField(max_length=512) def __str__(self): return str(self.device_object.device_id) class CenterCommandsRawData(models.Model): center_command = models.OneToOneField( CenterCommands, on_delete=models.CASCADE, primary_key=True) data = models.CharField(max_length=512) def __str__(self): return str(self.center_command.device_object.device_id) But whenever I'm trying to run python manage.py makemigrations deviceApp and python manage.py migrate, I get the following error: (myDjangoEnv) F:\Work\Vehicle Tracking System\Codes\Server\OVTSServer>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, deviceApp, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying deviceApp.0001_initial...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 "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 83, in … -
Django: Trying to return sum of objects between two dates, instead returns sum of all objects
I have a Django table containing events, each marked with a timestamp. For testing purposes I put in some future dates (2020), but instead of returning the count of events between the two dates (0), this returns the sum of all of the events since the beginning of the DB (5). The Django request is as follows: queryset = queryset.annotate( value=aggregate_operation( f"{MESSAGEMODEL_ATTRIBUTE_NAME_IN_DEVICEMODEL}__press_count", filter=timestamp_filter ) ).values(DEVICE_REFERENCE_ATTRIBUTE_NAME, "value") I printed all of the variables involved: filter = (OR: ('messages__timestamp__gte', datetime.datetime(2020, 1, 2, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619ed0c18>)), ('messages__timestamp__lte', datetime.datetime(2020, 8, 30, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619e9bf60>))) value = Sum(F(messages__press_count), filter=(OR: ('messages__timestamp__gte', datetime.datetime(2020, 1, 2, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619ed0c18>)), ('messages__timestamp__lte', datetime.datetime(2020, 8, 30, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619e9bf60>)))) queryset = <QuerySet [{'name': '001 - CHANTIER1 - LIVRAISONS', 'value': 5}]> Why isn't this request behaving as expected? -
Couldn't find WSGI module deploying Heroku
Trying to deploy my app with this tutorial. Have a ModuleNotFoundError: No module named 'radio.wsgi' message. 2019-08-21T08:08:21.409841+00:00 app[web.1]: __import__(module) 2019-08-21T08:08:21.409849+00:00 app[web.1]: ModuleNotFoundError: No module named 'radio.wsgi' 2019-08-21T08:08:21.409960+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-08-21T08:08:21.441211+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [4] [INFO] Shutting down: Master 2019-08-21T08:08:21.441415+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [4] [INFO] Reason: Worker failed to boot. In some other questions people recomends python manage.py run_gunicorn but I have Unknown command: 'run_gunicorn' Procfile: web: gunicorn radio.wsgi --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'radio.settings') application = get_wsgi_application() In only those files WSGI is mentioned. requirements.txt dj-database-url==0.5.0 Django==2.2.4 gunicorn==19.9.0 lxml==4.4.1 psycopg2-binary==2.8.3 pytz==2019.2 sqlparse==0.3.0 whitenoise==4.1.3 This is project structure ├── radio │ ├── db.sqlite3 │ ├── manage.py │ ├── player │ ├── radio │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── setup.py │ └── static ├── README.md ├── .gitignore ├── requirements.txt ├── runtime.txt └── Procfile -
How to add username in admin page who logged in when withdrawing an amount?
I have made a form to give an option for user to withdraw money. That data is saving in admin page but the problem is I have owner variable also, which I want that as the amount data is going to be saved in admin page the owner username should also be saved in admin, which shows who is desiring this amount? models.py from django.contrib.auth.models import User class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Balance' views.py @login_required def withdraw(request): if request.method == 'POST': form = WithdrawBalance(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, f'Your request has been submitted.') return redirect('index') else: form = WithdrawBalance() context = {'form': form} return render(request, 'nextone/withdraw.html', context) forms.py class WithdrawBalance(forms.ModelForm): class Meta: model = WithdrawPayment fields = ['payment'] -
Can't find static file in specified dir Django?
Here's my project tree: project1 ├─app1 ├─views.py ├─gg_task.py └─urls.py ├─static ├─1.json └─2.yaml ├─templates └─project1 ├─settings.py ├─urls.py And main codes below, I want to use 1.json in gg_task.py: project1.settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] import sys sys.path.append(os.path.join(BASE_DIR, "static")) app1.urls.py urlpatterns += [ re_path( r'^authenticate_gg/', AuthenticateGgView.as_view(), name='AuthenticateGg'), ] app1.views.py from .gg_task import GgManager class AuthenticateGgView(View): def get(self, request): manager_id = request.GET.get("manager_id", "5851848752") auth_url = GgManager(manager_id).get_auth_url() return redirect(auth_url) app1.gg_task.py class GgManager(object): _SCOPES = ['https://www.googleapis.com/auth/adwords'] def __init__(self, manager_id): self.manager_id = manager_id print(sys.path) # /path/to/static already in sys.path self.yaml_file_name = "{}.yaml".format(self.manager_id) self.json_file = "{}.json".format(self.manager_id) self.client = (google.ads.google_ads.client.GoogleAdsClient .load_from_storage(self.yaml_file_name)) I think I've already set /path/to/static in settings.py at start of django set-up, and I can directly use file 1.json and 1.yaml in gg_task. But I always get No such file or directory: '1.yaml', can you help me about this error? -
Django field clash with multiple abstract base clases
I am trying to define entity architecture that, if simplified, can be expressed like this: class M(models.Model): field_m = models.CharField(max_length=255) class Meta: abstract = True class A(M): field_a_1 = models.CharField(max_length=255) field_a_2 = models.CharField(max_length=255) class Meta: abstract = True class B(A): class Meta: abstract = True class C(A): class Meta: abstract = True class D(A): class Meta: abstract = True class DD(D): class Meta: abstract = True class X(B, C, DD): pass As you can see, X has some mixins (abstract entitites). Each of the mixin has their own custom logic implemented inside them. But ultimately all of them have 1 common parent- abstract class A. As far as I understand, this should work. And MRO resolution, indeed, works. However, when starting the project I get 2 errors per each field field A (that are inherited in X): X.field_a_1 : (models.E006) The field 'field_a_1 ' clashes with the field 'field_a_1 ' from model 'X'. X.field_a_1 : (models.E006) The field 'field_a_1 ' clashes with the field 'field_a_1 ' from model 'X'. X.field_a_2 : (models.E006) The field 'field_a_2 ' clashes with the field 'field_a_2 ' from model 'X'. X.field_a_2 : (models.E006) The field 'field_a_2 ' clashes with the field 'field_a_2 ' from model … -
Not able to run django for cache
I am not able to run django even any command like migrate, makemigrations. I am facing this below error ValueError: Related model 'blog.User' cannot be resolved I don't have any app with name 'blog'. Don't know where this app coming from. This is my settings.py file """ Django settings for pushnoty project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6rr$mj_@+*^5a#w=2-#koxj2nv2kpeb&0#jw0%-71fr@9@y)qc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pushnoty.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pushnoty.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Variable form action="/"
There is a web application that collects data from different sites. The form on the home page is presented in the form of two fields where you can choose from several variants of languages and cities. When you press the search button, the result is displayed only for one pair of languages and cities, regardless of the selected variant in the form, as there is only one url in the form action='''. How to make a dynamic change of form action='' depending on the choice of variant in the form on the main page. I hope I have explained it clearly. Thank you for any help! https://ibb.co/VNcQqDp screenshot models.py from django.db import models class Page(models.Model): language = models.CharField(max_length=100) city = models.CharField(max_length=100) def __str__(self): return self.language views.py from django.shortcuts import render, redirect from .forms import PageForm from page.parsers.kiev_python_parser import * from page.parsers.kiev_javascript_parser import * from page.parsers.kiev_java_parser import * from page.parsers.kiev_c_parser import * def index_page(request): form = PageForm() return render(request, 'page/index_page_form.html', context= {'form':form}) def kiev_python(request): kiev_python_main() return render(request, 'page/kiev_python_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_javascript(request): kiev_javascript_main() return render(request, 'page/kiev_javascript_result.html', context={'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_java(request): kiev_java_main() return render(request, 'page/kiev_java_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_c(request): kiev_c_main() return render(request, 'page/kiev_c_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) … -
Resize a textfield in Django Admin
I'm trying to change the size of a TextField inside my Admin Panel. I've read this: Resize fields in Django Admin but no matter the number of cols and rows I choose for my models.TextField this just get smaller than the default size and doesn't change. admin.py : class FileOTRSAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 5000, 'cols': 400})}, } admin.site.register(tmodels.FileOTRS, FileOTRSAdmin) models.py : class FileOTRS(models.Model): content = models.TextField(_(u"Contenu")) -
How to reset mongo session ttl on each request in django?
I'm working on a django project and using mongo_sessions.session as SESSION_ENGINE. I want to set an expiration time to session but when I use MONGO_SESSIONS_TTL, it doesn't reset session on each request of user. How can I fix this? -
Salesforce as Idp unable to logout (django + pysaml2)
Related question: SP-initiated Single Logout not working with SalesForce I'm implementing single-sign-on service using Salesforce as identity provider. My app is now working well with single login. My goal is to make logout from my app (service provider) initiate log out in the identity provider (salesforce). For this purpose I send SAML2 request to Salesforce, however, I always get "We are unable to log you out." error. I searched logs of salesforce to find the cause of the error but didn't find any. In my app i use django, to generate saml I use pysaml2 lib. This is my code to generate logout request: req_id, request = saml2_client.create_logout_request( destination,"<entity-id>",name_id=NameID(text=request.user.email, format=NAMEID_FORMAT_TRANSIENT), expire=soon) # request = saml2_client.sign(request) rstate = saml2_client._relay_state(req_id) msg = http_redirect_message(request, destination, rstate) headers = dict(msg['headers']) location = headers['Location'] return HttpResponseRedirect(location) Generated xml: <ns0:LogoutRequest Destination="<logout_endpoint>" ID="<id>" IssueInstant="2019-08-21T06:44:29Z" NotOnOrAfter="2019-08- 21T06:49:29Z" Version="2.0" xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns1="urn:oasis:names:tc:SAML:2.0:assertion"> <ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid- format:entity">https://localhost:8000/saml2_logout/</ns1:Issuer> <ns1:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid- format:transient">username</ns1:NameID> </ns0:LogoutRequest> I'm not sure if params I pass to create_logout_request are correct, but I couldn't find any guide on what they have to be, currently entityid value is the url of my salesforce identity provider. -
How to grant temporary permissions to user?
In my application I want the user to re-enter their password before being able to complete a sensitive action such as editing their subscription. After successfully re-authenticating the permissions would be time-limited. I can't find django functionality that enables this, but since django seems to do just about everything else I thought it worth asking - can django do this or can it be configured to do this? -
How to remove this big error while creating super user?
I have three apps in django. When I makemigrations, it only added one app after migrate to database. After using command python maange.py createsuperuser, it is giving me error. I am using mongodb database. djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s) Params: ['pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', None, True, 'bilalkhangood4', '', '', '', True, True, datetime.datetime(2019, 8, 21, 6, 41, 58, 512948)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: username_1 dup key: { : "bilalkhangood4" }', 'op': {'id': 4, 'password': 'pbkdf2_sha256$150000$Lpi7ZmtZQTKU$Rgi4yfUgX/lNGMOnhDIIyCELKvz/JvwUutBPVyTv6/o=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhangood4', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 8, 21, 6, 41, 58, 512948), '_id': ObjectId('5d5ce7b62dd232236aa5a188')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} -
How I can write only one django orm query?
The goal is to filter Fitness objects by specified SportType objects, i.e. all Fitness objects which contains at least one specified SportType object as foreignkey. Here is my models and example: class Fitness(models.Model): name = models.Charfield(max_length=100) class SportType(models.Model): name = models.CharField(max_length=100) class FitnessSportType(models.Model): fitness = models.ForeignKey(Fitness, related_name='sport_type_set') sport_type = models.ForeignKey(SportType, related_name='fitness_set') f1 = Fitness.objects.create(name='foo') f2 = Fitness.objects.create(name='bar') f3 = Fitness.objects.create(name='goo') s1 = SportType.objects.create(name='a') s2 = SportType.objects.create(name='b') s3 = SportType.objects.create(name='c') FitnessSportType.objects.create(fitness=f1, sport_type=s1) FitnessSportType.objects.create(fitness=f1, sport_type=s2) FitnessSportType.objects.create(fitness=f2, sport_type=s1) FitnessSportType.objects.create(fitness=f2, sport_type=s3) FitnessSportType.objects.create(fitness=f3, sport_type=s2) SOME_MAGIC_FUNCTION([s1, s3]) = [f1, f2] P.S: sorry for bad English :) -
Retrieve data in API based on ID in Django Rest Framework
I made an APIView of a django function Views.py class TakenQuizListViewAPI(APIView): def get(self, request, *args, **kwargs): queryset = self.request.user.supplier.taken_quizzes.select_related('quiz', 'quiz__truck_type').order_by( 'quiz__posted_on') query = suppliertakenquizSerializer(queryset, many=True).data return Response(query) and it returns data like this: { "id": 5, "score": 0.0, "date": "2019-08-20T13:31:15.156691", "least_bid": 99, "confirmed": "Not Confirmed", "supplier": 32, "quiz": 16 }, How can I get all the details of the quiz in the API ?? Expected Output: { "id": 5, "score": 0.0, "date": "2019-08-20T13:31:15.156691", "least_bid": 99, "confirmed": "Not Confirmed", "supplier": 32, "quiz": { "foo": "", "bar": "" } }, serializer: class suppliertakenquizSerializer(serializers.ModelSerializer): class Meta: model = TakenQuiz fields = "__all__" Model.py: class TakenQuiz(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) least_bid = models.IntegerField(default=0) confirmed = models.CharField(max_length=100, default='Not Confirmed') -
Django how to save logs in transaction.atomic()
Suppose you are processing order when payment is confirmed. with transaction.atomic(): do something like subtract stock log stuff in DB so that we can later investigate what went wrong if something goes wrong: # this line of code may reside in a function nested deep raise do more to finalize the order When there's an exception, db rolls back fine, but I want the logging to be persisted in the db. I'm thinking creating a celery task and do the logging the background, (not sure if it's going to work). Are there better alternatives? -
Copy the data from one ID to another ID in same table in django ORM
Copy the data from one ID to another ID in same table in django ORM -
How do I pass the primary key from one model to another model and display some fields of the first model in the template?
I have 2 models, 'Candidate' and 'Tracker' . I want to add the candidates to the tracker list if I wish to. The tracker has some additional fields. However in the tracker template I wish to display some details of the candidate like name, phone etc. Basically the tracker page contains added candidates with some extra details about them. Candidate models.py class Candidate(models.Model): candidate_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.EmailField() current_company = models.CharField(max_length=100) current_designation = models.CharField(max_length=100) def __str__(self): return self.candidate_name def get_absolute_url(self): return reverse('candidate-detail', kwargs={'pk': self.pk}) Tracker models.py class Tracker(models.Model): candidate_name = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='candidates') position_applied = models.CharField(max_length=100) current_CTC = models.CharField(max_length=100) expected_CTC = models.CharField(max_length=100) def __str__(self): return self.position_applied def get_absolute_url(self): return reverse('tracker-detail', kwargs={'pk': self.pk}) views.py files.. class TrackerCreateView(LoginRequiredMixin, CreateView): model = Tracker fields = ['current_CTC', 'expected_CTC', 'position_applied', 'candidate_name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CandidateCreateView(LoginRequiredMixin, CreateView): model = Candidate fields = ['candidate_name', 'phone', 'email','current_company', 'current_designation'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Uptil now I have just included candidate as a foreign key. But this requires selecting the candidate name from the dropdown which is not practical. How can I display the name,phone,email etc. in the tracker list? I have a button on the … -
local variable 'board' referenced before assignment
I am getting an unbound local error while creating website in Django from django.shortcuts import render, get_object_or_404 from .models import Board from django.http import HttpResponse # Create your views here. def home(request): boards = Board.objects.all() return render(request, 'home.html', {'boards' : boards}) def board_topics(request,pk): board = get_object_or_404(board, pk=pk) return render(request,"topics.html",{'board' : board}) boards = Board.objects.all() return render(request, 'home.html', {'boards' : boards}) -
How can I change this SQL? Django SQL syntax error: near from
I don't know how can I change this. This def is in Desktop\DjangoProject\dj_board\board\views.py boardList = DjangoBoard.objects.raw('SELECT Z.* FROM(SELECT X.*, ceil( rownum / %s ) as page FROM ( SELECT ID,SUBJECT,NAME, CREATED_DATE, MAIL,MEMO,HITS \ FROM BOARD_DJANGOBOARD ORDER BY ID DESC ) X ) Z WHERE page = %s', [rowsPerPage, current_page]) near "FROM": syntax error -
How to fix, 'PyInstallerImportError: Failed to load dynlib/dll', while executing executable file in docker?
I created the executable file for a Python-Django application using PyInstaller. I am trying to run the executable file in docker, which gives me the error. This is the dll which is missing: /home/user/app/mxnet/libmxnet.so' , which is already present in the .exe file folder. The exe file gets executed when not run using Docker. Tried manually installing mxnet and running the docker image, but still not working import mxnet Error: Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2a02dde510> Traceback (most recent call last): File "PyInstaller/loader/pyiboot01_bootstrap.py", line 149, in __init__ File "ctypes/__init__.py", line 347, in __init__ OSError: libgomp.so.1: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django/utils/autoreload.py", line 227, in wrapper File "django/core/management/commands/runserver.py", line 125, in inner_run File "django/core/management/base.py", line 359, in check File "django/core/management/base.py", line 346, in _run_checks File "django/core/checks/registry.py", line 81, in run_checks File "django/core/checks/urls.py", line 16, in check_url_config File "django/core/checks/urls.py", line 26, in check_resolver File "django/urls/resolvers.py", line 254, in check File "django/utils/functional.py", line 35, in __get__ File "django/urls/resolvers.py", line 405, in url_patterns File "django/utils/functional.py", line 35, in __get__ File "django/urls/resolvers.py", line 398, in urlconf_module File "importlib/__init__.py", … -
Is django rest framework overtaking django with the increasing popularity of javascript frameworks?
I have learning django since 2-3 months and I did pretty good web apps with it.But nowadays with the iincreasing popularity of Javascript frameworks like Vue.js,Angluar and React.js I am not using django anymore.For this i use django rest framework.I know django rest is used for API. So with django it was very easy to render html templates,to do all other things or to make some logics but with django rest framework i am not being able to do so .Everything being new to me with django rest framework.I lost that how i can render html pages and also the logics are different from django. There is no any need of django forms templates anymore. So my question is should i be more focused on django rest framework rather than django with the increasing popularity of frontend frameworks?