Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while getting database values into form
I am trying to get values from database and import them in checklist inside a form. I am getting values with CustomStudent.objects.all().values_list('sname') but values are retrieved as list which gives error when submitting. This is my forms.py class WeeklyForm(forms.Form): sname = forms.ModelMultipleChoiceField(queryset=CustomStudent.objects.all().values_list('sname'), required = False, widget =forms.CheckboxSelectMultiple( attrs ={'class':' form-check-input' ' form-check-inline'})) class_name = forms.CharField(widget= forms.Select(choices= [('1', 'UKG'), ('2', 'Class 1'), ('3', 'LKG'), ('4', 'Montessori') ] ,attrs={'class': 'form-control', 'placeholder' : 'Select Class'})) fdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) tdate = forms.DateField(initial = datetime.date.today() , required=False, widget =forms.DateInput( attrs ={'class': 'form-control' , 'placeholder' : ' Date ', 'name' : 'date'})) objective = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'objective'})) target = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'target'})) how = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'how?'})) material = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'material required'})) support = forms.CharField(widget = forms.Textarea(attrs={'class': 'form-control', 'placeholder' : 'Any Support Required?'})) This is my model class CustomStudent(models.Model): _id = models.AutoField sname = models.CharField(max_length = 50) slname = models.CharField(max_length = 50) password = models.CharField(max_length = 255, default = '') I have tried adding CustomStudent.objects.all().values_list('sname', flat=True) which returns proper name instead … -
Python PIP version
I`m writing a django project, every time When I installed django: pip install "Django==3.0.*" I was encountering a WARNING: WARNING: You are using pip version 19.2.3, however version 20.3.3 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. But the strange thing is when I go to the PIP installations directory on Windows and Check for the pip version, I always got the version upgraded: ...Programs\Python\Python38\Scripts> pip --version pip 20.3.3 from c:\users\... This is very annoying, cause each time I pip install Django I have to upgrade it while it has been already upgraded. Somebody tell me how is this happen? -
how to add a link in django admin app that redirects to a html file
i have an application django admin based, in a specific admin page i have a fieldsets as below: def report(self, obj): return mark_safe(json2html.convert(json=obj.report, table_attributes="class=\"results\" style=\"overflow-x:auto;\"")) fieldsets = ( (None, { 'fields': ('complete',), }), ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), and in the models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, @property def report(self): family_groups = [] for f in self.familygroup_set.all(): family_members = [] for m in f.familymember_set.all(): family_members.append({ 'name': str(m), 'rent_percentage': m.effective_rent_percentage, 'weekly_income': "%.2f" % float(m.weekly_income or 0), 'rent_component': "%.2f" % float(m.income_component or 0) }) report = [ family_groups, 'Household Rent: ' + "%.2f" % float(self.household_rent or 0) ] import json return json.dumps(report, indent=4) what im trying to do is to add a clickable link to the report function, and this link redirect the user to a html file that i will create, instead of the function i made in the models.py. what is the best approach to accomplish this ? -
Django max_length where there should not be a max_length
I do not have a deep understanding of Django, anyway not deep enough to overcome a problem that turns up in my application. In models.py I have a.o. the following definitions: class Relatiedata(models.Model): ... getuigen = models.TextField(blank=True, null=True) ... class Meta: db_table = 'relatiedata' Relatiedata.objects = Relatiedata.objects.using('genealogie') So in the database genealogie, which is not the default database, I have a table relatiedata with a column getuigen that has to contain a text string without a limitation on the length. Further, I have a user form for mutating records of this table. As usual, the form is populated from a Relatiedata.object and the returned form results in another Relatiedata.object which is saved, thereby updating the database. This works (almost) perfect. The problem is that in my form it turns out to be impossible to enter a string of length above 600 in the textarea for getuigen. Longer strings are simply cut off. There seems to be sort of a form validation for the length of that field, despite the fact that there is no such limit in the models, nor in the database, nor in the migration files. This value of 600 comes from earlier, abandoned, implementations of the model, … -
django fieldsets IndentationError: unindent does not match any outer indentation level
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from authentication.forms import UserForm, CustomUserChangeForm # Register your models here. User = get_user_model() class CustomUserAdmin(UserAdmin): add_form = UserForm form = CustomUserChangeForm model = User add_fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture', 'password1', 'password2')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) fieldsets = ( ('Personal Details', {'fields': ('email', 'full_name', 'username', 'picture')}), ('Permissions', {'fields': ('is_staff', 'is_active')}) ) admin.site.register(User, CustomUserAdmin) I am working on web application for this i want to do some customization on my admin panel but it giving Indentation error. I also try it in list but it still showing me same error. What I did wrong! Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "G:\Python\publish\env\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "G:\Python\publish\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "G:\Python\publish\env\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "G:\Python\publish\env\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "G:\Python\publish\env\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in … -
How to add a custom input field into some Model Create form in django Admin
The question is How to add some custom form fields into django model create form and handle their values before create new Model into DB. I'm using django for my site, and there is a simple model Specialist { name, diploma, email, phone } also there is a model Topics { title, description } Each specialist can be experienced in different set of topics. There is a many to many relation via an extra Model TopicsSpecialists { specId, topicId } Standard Django admin allows me to create specialists and topics. Aslo to make it convenient i've provided Inline class TopicsInline(admin.TabularInline): extra = 1 model = Topics and passed it as in admin registration class SpecialistAdmin(admin.ModelAdmin): inlines = [TopicsInline,] Now list of extra fields were added to my Specialist creation form. It works well, but to make it more sense I would like to have a chance to have a set of checkboxes for each user to select topics instead of drop downs (as i have now). But would not add a bunch of bool fields into DB, just convert checkboxes to set of references before save specialist into DB There should be the way to customize model creation form. If … -
ManagementForm data is missing or has been tampered with for nested forms
I have the following Forms defined in my forms.py class MachineryGroupForm(ModelForm): class Meta: model = MachineryGroup fields = '__all__' class MachineryPartForm(ModelForm): class Meta: model = MachineryPart fields= '__all__' The following is the corresponding UpdateView: class MachineryGroupUpdate(UpdateView): model = MachineryGroup template_name = 'procman/machinerygroup_form.html' form_class = MachineryGroupForm success_url = 'machinery_group_list' MachineryPartFormSet = inlineformset_factory(MachineryGroup, MachineryPart, fields='__all__') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['parts'] = self.MachineryPartFormSet(self.request.POST, instance = self.object) else: data['parts'] = self.MachineryPartFormSet(instance = self.object) return data And Below is the template used to render the form: <h1>Machine Group</h1> <form method="post"> {% with named_formsets.MachineryPartFormFormSet as formset %} {{ formset.management_form }} {% csrf_token %} <table> {{ form.as_table }} {% if parts %} <table style="border-collapse: collapse; width: 100%;" border="1"> <br><br> <tbody> <thead> <td style="width: 14.2857%;">Group Code</td> <td style="width: 14.2857%;">Group Name</td> <td style="width: 14.2857%;"></td> <td style="width: 14.2857%;"></td> </thead> {% for part in parts %} <tr> <td style="">{{part.part_name}}</td> <td style="">{{part.part_number}}</td> <td style="width: 14.2857%;"><a href="#"> Edit</a></td> <td style="width: 14.2857%;"><a href="#"> Delete </a></td> </tr> {% endfor %} </tbody> </table> {% endif %}<br><br> </table> <br><br><input type="submit" value="Save"> {% endwith %} </form> I have tried every permutaion using {{formset}}, {{MachineryPartFormSet}} and also the last one using the with tags, but I am still getting the error: ['ManagementForm data is missing … -
Want to share backup file in Django web container with Postgres database container: How to?
I have a Django app on Docker with web container where automatics backups are stored and another postgresql database container. I want to be able to restore postgresql database using \i 'path\to\backup.psql' in a psql shell but it failed because file is not found db_preprod=# \i '/usr/src/app/backup/backup_2021-01-19_1336.psql' /usr/src/app/backup/backup_2021-01-19_1336.psql: No such file or directory I also tryed to copy with docker cp but not works: docker cp web:/usr/src/ap/backup/backup_2021-01-19_1336.psql db:/. copying between containers is not supported docker-compose version: '3.7' services: web: restart: always container_name: web build: context: ./app dockerfile: Dockerfile.preprod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.preprod depends_on: - db - redis healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/"] interval: 30s timeout: 10s retries: 50 db: container_name: db image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.preprod.db nginx: container_name: nginx build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1340:80 depends_on: web: condition: service_healthy volumes: postgres_data: static_volume: media_volume: -
Djano recursive SubQuery
I'm tring to implement a query including a recursive function. I have in one hierarchical structure, i.e. every organisation has a head organisation which has also a head organisation and now I want to get the (head) organisation with level 3 of a given (sub) organisation. The corresponding model looks like this: class OrganisationHierarchy(TimeStampMixin): id = models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID') level = models.ForeignKey(OrgaLevel, on_delete=models.PROTECT, null=True, blank=True) name = models.CharField(max_length=60, blank=True) zip_code = models.ForeignKey(ZipCode, on_delete=models.PROTECT, null=True, blank=True) parent = models.ForeignKey('self', null=True, on_delete=models.PROTECT, related_name='organisationhierarchy', blank=True) The query below works except getting the head organisation. I have written a separate method for this, but I don't know how to get the current organisation into this value, i.e when doing head_organisation=get_head_organisation_name(F('organisation')) then the method receives F('organisation') and not the value of organisation class EventGeneralSerializer(serializers.ModelSerializer): locations = serializers.SerializerMethodField('get_locations') class Meta: model = Event fields = ( 'locations', ) def get_head_organisation_name(self, organisation): if organisation.level_id > 3: return self.get_head_organisation_name(organisation.parent) elif organisation.level_id < 3: raise Exception("To low value") else: return organisation.name def get_locations(self, obj): result = obj.registration_set.values('organisation__name').annotate( participants=Coalesce(Sum('participantgroup__number_of_persons'), 0) + Coalesce(Count('participantpersonal'), 0), head_organisation=F('organisation__parent__parent__name')) \ <-- Insert recursive method here .values('organisation__name', 'participants', 'head_organisation', lon=F('organisation__zip_code__lon'), lat=F('organisation__zip_code__lat'), ) return result So thanks for your help in advance! -
Django REST API followers system
I'm trying to make a rest API for a blog app using Django-rest-framework. I'm a beginner and it's hard for me to understand how to implement that system. I made an intermediary model for making connections between followers and followings and serializers for users. But my API showing absolutely wrong following and followers for each user and endpoints for following and unfollowing not working also. Models.py: class UserFollowing(models.Model): class Meta: constraints= [ models.UniqueConstraint(fields=['user_id', 'following_user_id'], name='unique_following') ] ordering = ['-created'] user_id = models.ForeignKey('auth.User', related_name='following', on_delete=models.SET_NULL, null=True,blank=True) following_user_id = models.ForeignKey('auth.User', related_name='followers', on_delete=models.SET_NULL, null=True,blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user_id} is following {self.following_user_id}' serializers.py: class UserSerializer(serializers.HyperlinkedModelSerializer): following = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) followers = serializers.HyperlinkedRelatedField(many=True, view_name='user-detail', read_only=True) posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'posts', 'following', 'followers'] def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data class UserFollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = '__all__' class FollowingSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'following_user_id', 'created'] class FollowersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserFollowing fields = ['id', 'user_id', 'created'] views.py: class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class UserFollowingViewSet(viewsets.ModelViewSet): queryset = UserFollowing.objects.all() serializer_class = UserFollowingSerializer class UserFollow(APIView): """ Retrieve, update … -
Django nested regroup
I use Django 2.2.12 I have three models: RiskRating is pointing to RiskType which is pointing to RiskCategory with ForeignKeys. class RiskCategory(models.Model): name = models.CharField(max_length=400, blank=True) class RiskType(models.Model): riskcategory = models.ForeignKey(RiskCategory, on_delete=models.CASCADE, related_name="risksforcategory") class RiskRating(models.Model): risktype = models.ForeignKey(RiskType, on_delete=models.CASCADE, related_name="ratingsforrisk") In my view: riskratings = Riskrating.objects.all() I would like to display RiskRating grouped by RiskCategories, i.e. I would like to do a nested regroup as following: {% regroup riskratings by risktype.riskcategory as ratingsbycategory %} How can I do that ? Thanks a lot -
django encrypt files before storage
So I want to encrypt files before storage in django and decrypt them upon retireval. I am using a custom storage class for the same and the cryptography module. import hashlib import os import uuid import django.core.files.storage as storage from cryptography.fernet import Fernet from django.conf import settings from django.core.files import File class DefaultStorage(storage.FileSystemStorage): def __init__(self): super(DefaultStorage, self).__init__() self.encryptor = Fernet(settings.ENCRYPTION_KEY) def _save(self, name, content): encrypted = self.encryptor.encrypt(content.file.read()) content.file.write(encrypted) print(content.file.read() == encrypted) return super(DefaultStorage, self)._save(name, content) def _open(self, name, mode='rb'): encrypted = open(self.path(name), mode).read() return File(self.encryptor.decrypt(encrypted)) def get_available_name(self, name, max_length=None): # we return a hash of the file given, # in case we miss out on uniqueness, django calls # the get_alternative_name method dir_name, file_name = os.path.split(name) file_root, file_ext = os.path.splitext(file_name) file_root = hashlib.md5(file_root.encode()).hexdigest() name = os.path.join(dir_name, file_root + file_ext) return super(DefaultStorage, self).get_available_name(name, max_length) def get_alternative_name(self, file_root, file_ext): # we insert a random uuid hex string into the given # file name before returning the same back return '%s%s%s' % (file_root, uuid.uuid4().hex, file_ext) I am overwritting the _save and _open methods here, but the class doesn't work as expected. Under the save method, I want to encrypt the contents of the file, but when I print this print(content.file.read() == encrypted) It … -
Attribute Error in Django,when using IMDbpy
I am trying to use the IMDbpy library in my django projects,but it raises an Attribute Error. I tried all the solutions available on the internet,but none seem to work,could you please help me with this? The Error: moviesDB = imdb.IMDb() AttributeError: module 'imdb' has no attribute 'IMDb' The code: import imdb moviesDB = imdb.IMDb() movies= moviesDB.search_movie('whatever_movie') id = movies[0].getID() movie = moviesDB.get_movie(id) print(movie) title=movie['title'] rating = movie['rating'] cover=movie['cover url'] print(title,rating,cover) I have been scratching my head the entire day,due to this error,I'm kinda new to this,so please help! I tried reinstalling the imdbpy library,pip3 installed it,renamed it but nothing seems to be working. The code is working in external files,but in the views.py in django,it just doesnt seem to work please help! -
Parts of CSS styles are not loaded when routing between React Components until refreshing the page?
I build a Django project, and using Webpack to create the React bundle rendered in Django template body. I tried to load CSS files either in Django template or in App.js but same results. When I switch between React pages parts of the CSS is not loaded, but when I refresh the page all the CSS and JS files are loaded. {% load i18n %} {% load static %} {% load render_bundle from webpack_loader %} <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="OneUIUX HTML website template by Maxartkiller. Bootstrap UI UX, Bootstrap theme, Bootstrap HTML, Bootstrap template, Bootstrap website, multipurpose website template. get bootstrap template, website"> <meta name="author" content="Maxartkiller"> <link rel="stylesheet" href="{% static 'css/swiper.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/newstyle.css' %}"> <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.cookie.js' %}"></script> <script src="{% static 'js/masonry.pkgd.min.js' %}"}></script> <script src="{% static 'js/swiper.min.js' %}"></script> <script src="{% static 'js/main.js' %}"></script> </head> <body> <div id='reactify-django-ui'> {% render_bundle 'main' %} </div> </body> </html> And my Webpack config file const path = require("path"); const host = process.env.HOST || 'localhost'; const devPort = 3000 var webpack = require('webpack'); … -
How to securely store OAuth2 access and refresh tokens in Django
I'm trying to implement the Azure AD OAuth authentication for our Django app and I would be doing that with Azure AD as an OAuth provider. So now I wanted to know how securely we can store the OAuth access/refresh tokens in the DB that we receive from Azure AD or any OAuth provider. I want to store the user's access token in DB because we have a feature in our web app where users can send an email with their email ID and we have a periodic job that runs every half an hour and it's gonna fetch user's mails based on a specific subject line. This we're gonna do with the help of Microsoft's Graph API and in order to call Microsoft Graph API, the web app should store the user's access token may be in the DB. But my concern is once we receive the access and refresh token, it shouldn't be accessed by anyone once we store it in the DB. So how securely or in an encrypted way we can store the OAuth2 access tokens in Django. I have gone through a few articles, QnA, and forums on this concern but wanted to hear from … -
Django field that can be either IntegerField or DecimalField
In one of my Django model, I have a field that can be either an IntegerField or a DecimalField based on the user. When the value of the record is an integer, the form should only display/edit it without trailing digits. When the value of the record has decimals, all decimals should be displayed/edit on the form. I have tried defining this field as a DecimalField and play with the form, but the challenge is that I use django-crispy-forms to render my forms so I cannot use the floatformat filter in my template. As a result, 5 as an integer, for instance, is displayed as 5.00000000 in my form. Is there a way around this? -
Django - models design issue
I'm struggling designing my models on Django (using PostgreSQL). The goal is to create a system of groups where a user can arrange items in them. An item must be unique in my database. I created a user item group (UserItemGroup) that belong to a user (User). Then, I created an item model (UserItem). This model represents an item which the user can arrange into groups. Items can belong to multiple groups at the same time but must be unique! I used 2 ForeignKey in the UserItem model but it seems very weird... See below: class UserItemGroup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(UserItemGroup, on_delete=models.CASCADE) Items can be arranged like so: user_x ------group_a ------------item_1 ------------item_2 ------------item_3 ------group_b ------------item_1 ------------item_4 Hope I'm clear, thanks in advance for help. -
Why does response content change when I write to a file?
I'm trying to work with XML obtained from http://video.google.com/timedtext that contains closed caption data of YouTube videos. As I'm fairly new to both Django and XML, I tried to directly output the XML - i.e. the response's content to the webpage - as the first step, by passing it directly in the context while rendering it as a 'p' element in the template. This worked fine. The XML displayed as a byte string. I then used the Python module 'xmltodict' to convert the XML to a more workable format. This worked too, but I got an error message: [19/Jan/2021 17:48:07] "GET /_hpvE1jjdxY/ HTTP/1.1" 200 2744 [19/Jan/2021 17:48:09] "GET /favicon.ico HTTP/1.1" 301 0 Internal Server Error: /favicon.ico/ Traceback (most recent call last): File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Dev\Project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Dev\Project\src\lt_player\views.py", line 26, in player parsed_cc_data = xmltodict.parse(cc_data)['transcript']['text'] File "D:\Dev\Project\venv\lib\site-packages\xmltodict.py", line 327, in parse parser.Parse(xml_input, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2, column 11 [19/Jan/2021 17:48:10] "GET /favicon.ico/ HTTP/1.1" 500 75167 I looked up why this error could've popped up and I noticed some reasons such as the placing of a misplaced '&' character or some other … -
Django Conflicts Error When use ManyToManyField
I have two model like given in bellow; class userPages(models.Model): page_name=models.CharField(max_length=30) parent_id=models.IntegerField(blank=True, null=True) def __str__(self): return self.page_name class userProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") user_pages=models.ManyToManyField(userPages) def __str__(self): return self.user.username When I want to add data like this; . . . p1 = userPages(page_name='Login') p1.save() user_profile = userProfile(user=new_user) user_profile.save() user_profile.user_pages.add(p1) I got "syntax error at or near "ON"". LINE 1: ... ("userprofile_id", "userpages_id") VALUES (1, 1) ON CONFLIC... -
Django Paginator - all pages objects action
Folks, I'm currently developing a web application using Django and need to replicate a feature that currently exists in the admin section of Django. Namely, there is an option to select objects on all pages and take same action on all these. I have a Paginator on my page, but not sure what would be the best way to tell the server I want to perform an action on all objects, not only these being currently shown. Please advise! Cheers! -
University Appointment Based System: Django (Backend,sqlite), ReactJS(Frontend)
Hi guys im a university student embarking on a project and need some initial guidance as to the appropriate course of action to take. Basically Im creating an appointment based systems which allows students to book appointments with the teacher. The application must be able to consolidate both their timetables and only highlight the days when both the teacher and student are "free" so that the student can book the consultation slot. Im planing to use Django for backend and reactJS for front end. I just seek initial opinion/direction of as to how i can begin by constructing this system and more importantly what algorithm that I can use to consolidate the timetables of both the teacher and the student so that the system only highlights the duration and date where both parties are free Will greatly appreciate any form of feedback you can provide. Thank You -
Django contact e-mail form does not render/show up in home.html
I have a forms.py - file in the "portfolio" - app with the following content: from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = forms.BooleanField(required=False) In my views.py I have the following relevant part: from .forms import ContactForm # import module from same parent folder as this script import General.Misc.general_tools as tools # custom module to import special-print function def contactView(request, admin_email='blaa@blaaa.com'): if request.method == 'GET': sendemail_form = ContactForm() else: sendemail_form = ContactForm(request.POST) if sendemail_form.is_valid(): # * Retrieve data and set up e-mail (subject, sender, message) subject = sendemail_form.cleaned_data['subject'] from_email = sendemail_form.cleaned_data['from_email'] message = sendemail_form.cleaned_data['message'] # From docs: https://docs.djangoproject.com/en/3.1/topics/forms/#more-on-fields cc_myself = sendemail_form.cleaned_data['cc_myself'] recipients = [admin_email] if cc_myself: recipients.append(from_email) # * Send email try: # General Django docs: https://docs.djangoproject.com/en/3.1/topics/email/#send-mail # NOTE on passed list as 4th parameter: recipient-list ## i) How to set up an email contact form - docs: https://learndjango.com/tutorials/django-email-contact-form send_mail(subject, message, from_email, recipients, fail_silently=False) # * Exceptions * # # NOTE on scope: security except BadHeaderError: return HttpResponse('Invalid header found.') # General exception to be printed out except Exception as e: tools.except_print(f"ERROR:\n{e}") # Return success (if this code is reached) return redirect('success') # Send the completed … -
how to create a multiple database in app? [closed]
We have a research project in school which is a website that store all student informations. And we are currently using django. We would like to make it login by campus location (We need to create an app for many campuses ). What should we do to make the app have a different data inside and will be base by the campus location of the user that login? -
Why is it throwing an Django- Reverse query name SystemCheckError?
I am a newbie to Django, While running the django application using python3 manage.py runserver Because of the way I have created the model I am getting an error like django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: database.LeadsStatus.company_id: (fields.E305) Reverse query name for 'LeadsStatus.company_id' clashes with reverse query name for 'LeadsStatus.companies'. HINT: Add or change a related_name argument to the definition for 'LeadsStatus.company_id' or 'LeadsStatus.companies'. database.Users.id: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. System check identified 2 issues (0 silenced). This is how I've created model. class LeadsStatus(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) company_id = models.ForeignKey('Companies', null=False, db_index=True, on_delete=models.CASCADE) status = models.CharField(max_length=120) users_id = models.IntegerField() assign_date = models.DateTimeField() companies = models.OneToOneField('Companies', on_delete=models.CASCADE) I believe the error might be because of the way I have created a OneToOneField. How do I solve this error. Please help me understand. Thanks -
Unit testing in Django for CreateView
I have a CreateView with which I create new blog posts, I want to test it in order to check if everything is ok but something is wrong with my test and I can't understand what exactly. it gives me 2 errors, for the first method I get this error: Traceback (most recent call last): File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 73, in test_post_create_view_GET self.assertEquals(response.status_code, 200) AssertionError: 302 != 200 and for the second one is this error: File "C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py", line 78, in test_post_create_view_POST_success post = Post.objects.get(title=self.post['title']) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( blog.models.Post.DoesNotExist: Post matching query does not exist. This is my Test class: class TestPostCreateViews(BaseTest): def test_post_create_view_GET(self): response = self.client.get(self.add_post_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'blog/add_post.html') def test_post_create_view_POST_success(self): response = self.client.post(self.add_post_url, self.post, author=self.user, format='text/html') post = Post.objects.get(title=self.post['title']) self.assertEquals(response.status_code, 302) self.assertEquals(post.title, 'test post') my CreateView: class PostCreateView(LoginRequiredMixin, IsSuperuserOrStaffMixin, CreateView): template_name = 'blog/add_post.html' form_class = PostCreateForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) my url path: path('new/post/', PostCreateView.as_view(), name='add-post'), my form: class PostCreateForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(), max_length=200) content = forms.CharField(widget=forms.Textarea(attrs={'rows': 25, 'cols': 50})) class Meta: model = Post exclude = ['author', 'slug', 'published_date', 'updated_date'] and my model: class …