Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show balance of each user in html page when it is login?
I have a very simple question. I am struggling to show the balance of each user in html page. Whenever a person login, his/her balance should be shown in browser. The result I am getting is just Your Balance is. After that nothing is showing. I want to show each user his/her own balance which I have stored in database. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py @login_required def balance(request): total_amount = Balance.objects.all() for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'users/balance.html', context) Html page <h2>Your Balance is: {{total_amount.amount}}</h2> -
convert csv file to xls & pdf in django
I have a CSV file stored in my server. I created this view which let the user download the CSV file. But I want to convert this CSV to xls and pdf and let users download it instead( either one of it, according to some conditions which I will add later). views.py class Download_csv_View(View): def get(self,request): file_path = #path of .csv file if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 -
How to check form field value before posting form - Django
I have a form that currently works great with the exception that a user can input any value they want into one of the form fields. I would like to first check the field value when the user presses the submit button, before the form is actually submitted. Where is the best place to do this, I am assuming in the views.py? My objective is to check the customerTag value that the user inputs, and ensure the value they enter exists in the CustomerTag model field. for my views.py I currently have: def usersignup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': '127.0.0.1:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') send_mail(email_subject, message, 'example@example.com', [to_email,], fail_silently=False) return render(request, 'confirm.html',) else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) forms.py I have: class CustomUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs):# for ensuring fields are not left empty super(CustomUserCreationForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['first_name'].required = True self.fields['customerTag'].required = True class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'first_name', 'last_name', 'email', 'customerTag',) labels = { 'customerTag': ('Customer ID'), } help_texts = … -
How to enforce certain settings (of another app) for a Django Reusable App
I am writing a Django Reusable App. Parts of this app require certain other Django Reusable Apps, and critically require certain settings for those apps. For example, suppose that in order to use my_reusable_app you have to also use rest_framework and set: REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema", } (This is a silly example, but you get the idea.) How can I enforce this? My first thought is to use Django's built-in checks framwork. Any better ideas? -
Why am I getting this error in django: ModuleNotFoundError: No module named 'unicodedata'
I'm following a tutorial on how to populate django models using the Faker library, but when running the python file I get an error, can someone please help me understand why. I'm new to django, thanks Here's my code import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','PlzWorkApp.settings') import django django.setup() ## FAKE POP SCRIPT import random from PlzWorkApp.models import AccessRecord,Wepage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # create the fake data for thet entry fake_url = fakegen.ulr() fake_date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake access AccessRecord for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("Populating complete!") Here's the message I get when I run the file: Traceback (most recent call last): File "populate_PlzWorkApp.py", line 5, in django.setup() File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django__init__.py", line 16, in setup from django.urls import set_script_prefix File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls__init__.py", line 1, in from .base import ( File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "C:\Users\FiercePC\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\http__init__.py", line 2, in … -
Django: Hiding specific ForeignKey Objects
I've got these two models: class User(AbstractBaseUser, PermissionsMixin): club = models.ForeignKey('schedule.club', on_delete=models.CASCADE, null=True, blank=True) archived = models.DateTimeField('Archived at', blank=True, null=True) class Club(models.Model): archived = models.DateTimeField('Archived at', blank=True, null=True) some fields more fields Now when creating a new User for the field club I can always pick from a list of all my club objects. But for my Clubs I've got a archive function which is inside my models.py and does the following: def archive(self, user): self.name = 'Archived Club' self.archived = now() So they are not getting deleted. Only their data get anonymised and they basically still exist in the DB. And exactly those Clubs I don't want to see anymore when creating a new User and setting his/her club. Is there a way to do that without changing the club field in my form? Thanks for anyone who can help! :) -
No module named 'config' while uploading image on gcloud -django
I am trying to upload an image to gcloud server through admin area but it shows error No module named 'config' I am using gcloud proxy to use gcloud database here is the error trail- Traceback (most recent call last): File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "F:\duit\duit_backend_env\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "F:\duit\duit_backend_env\lib\site- packages\django\contrib\admin\options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "F:\duit\duit_backend_env\lib\site- packages\django\utils\decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) ... File "F:\duit\duit_backend_env\lib\importlib\__init__.py", line 126, i n import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _ find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _ call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' -
How to create custom filter using graphene-django and Relay that use multiple fields of different types?
Problem Hello, I'm using Graphene Django and Graphene Relay with Python 3.7. I'm trying to make a custom filter for the requests in GraphQL using Django filters. My table looks like this: | id(type: int) | flow(type: varchar) | datetime(type: datetime) | duration(type: int) | |---------------|---------------------|--------------------------|---------------------| | 1 | aaa | 2019-07-06 08:59:00 | 113095465 | | 2 | xxx | 2019-07-06 08:59:00 | 113095465 | | 3 | bbb | 2019-07-06 08:59:00 | 113095465 | I want to be able to execute this kind of SQL request using GraphQL: SELECT * FROM tablename WHERE datetime <= "2019-07-06 08:59:00" AND DATE_ADD(datetime, INTERVAL duration * 1000 SECOND) >= "2019-07-06 09:00:00"; Using a graphql query like : (of course the dates would be in Python DateTime Format) { allTable(startDate: "2019-07-06 08:59:00", endDate: "2019-07-06 09:00:00") { edges { node { id name } } } } Code models.py from django.db import models class TableName(models.Model): name = models.CharField() datetime = models.DateTimeField() duration = models.BigIntegerField() class Meta: managed = False db_table = 'tablename' schema.py from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField import django_filters from .models import TableName from .fieldList import fields_table class TableFilter(django_filters.FilterSet): class Meta: model = TableName fields … -
Django class with an attribute with different values
I'm trying to understand how django relationships work. I basically have an Attribute class that should have many Option instances. For example, the attribute could be color = Attribute(name='color') with loads of options such as blue = Option(name='blue', attribute=color), or green = Option(name='green', attribute=color). So the models.py file would look something like this: from django.db import models class Option(models.Model): name = models.CharField(max_length=200) attribute = models.ForeignKey(ProductAttribute, on_delete=models.CASCADE) class Attribute(models.Model): name = models.CharField(max_length=200) options = models.ForeignKey(ProductOption, on_delete=models.CASCADE) How's best to achieve this please? -
Django display content based on dropdown select
I am new in Django. I want to display content based on dropdown selection. In this example i want to show all the workshops data from the location selected in the dropdown. Is it possible to achieve that without reloading the page? or if it must reload the page, is it possible to stay on current view after reloading the page? Thank you. I have tried to use post method and use onChange attribute on my forms. It successfully reload the page but the workshops content is not shown, the dropdown selection go back to default '--- Choose your location ---' and the page go back to the top. Below is the code of the forms class LocationForm(forms.Form): location = forms.ModelChoiceField(label='', queryset=Location.objects.all(), empty_label="--- Choose your location ---", widget=forms.Select( attrs={'id': 'ddlLocation', 'name':'ddlLocation', 'class':'selectpicker', 'data-live-search':'true', 'data-size':'5', 'onChange':'frLocation.submit();' } ) ) Below is the code of the class class HomeView2(ListView): template_name = 'myapp/index.html' def get(self, request): form_location = LocationForm() location_id = request.GET.get('location_id') workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name') args = {'form_location':form_location, 'workshops':workshops} return render(request, self.template_name, args) def post(self,request): form_location = LocationForm() location_id = request.GET.get('location_id') workshops = Workshop.objects.filter(location_id=location_id).order_by('workshop_name') args = {'form_location':form_location, 'workshops':workshops} return render(request, self.template_name, args) and in index.html <section class="page-section" id="services"> <div class="container"> <h2 class="text-center mt-0">At … -
How to deal with manually rendered form fields?
I have around 40 form fields (mostly drop-downs, some checkboxes, and 2 textfields) that are manually rendered to a template where I use Bootstrap to customize the layout and look to my liking. Is there an elegant solution to dealing with validation and cleaning that will allow me to maintain my overall css design? Thank you. -
Django form ChoiceField allow dynamic choices through jquery
I have a django form with the field - section = forms.ChoiceField(choices=(('', '---'),), required=False) The choices are dynamically generated in jquery, the relevant code being - var html = '<option value="">---</option>'; for (var i=0; i < sections.length; i++) { section = sections[i]; html += '<option value="'+section+'">'+section+'</option>' } $("#id_section").html(html) Everything works fine. However, when I try to submit the form it says Select a valid choice. (selected_option) is not one of the choices. Is there any way to circumvent this error apart from removing form.is_valid()? I thought required=False would be enough. I know there are other ways to code this part but a direct solution to this problem would be appreciated. -
Django Rest Framework call filter method from client
I have a user filter class: class UserFilterSet(filters.FilterSet): class Meta: model = User fields = { 'email': ['exact', 'contains'], 'first_name': ['iexact', 'icontains', 'in'], 'last_name': ['iexact', 'icontains', 'in'] } def dashboard_lookup(self, queryset, name, value): search_args = [] for term in value.split(): for query in ('first_name__icontains', 'last_name__icontains', 'email__icontains'): search_args.append(Q(**{query: term})) return queryset.filter(reduce(operator.or_, search_args)) My question is - how do I actually use this from my client? Right now I'm making requests to either first_name or last_name or email, but I need to filter by any of the three in the same request. Hence the method approach above. Is there a way to add this method to the querystring? Maybe something like https://mypage.com/api/user/?method=dashboard_lookup&value=string? -
django-rest returning http 301 status code when calling http delete without trailing slash
I recently experienced that on django rest framework a http 301 status code is returned when making a delete request, without including the trailing slash in the url when trailing_slash=True. While missing the trailing slash on a post request would return a runtime error. So my question is, is this a bug or is it expected behavior? -
Django: Test session key before redirection
I create a session key after a post to a view and then I redirect to the same view clearing that key. I want to test for the creation of the key in request.session but I can't because after the redirection the key is removed. View def my_view(request): if request.method == 'POST': # ... request.session['my_key'] = 'my_value' # ... if request.session.get('my_key', None): del request.session['my_key'] return render(request) Test def my_test(self): response = self.client.post('my_view') self.assertEqual(self.client.get('my_key'), 'my_value') As self.client.post goes to redirect chain, the key is removed and the test fails. Is it a way to self.client.post and stop after the redirection so the test pass? -
python: How to start and stop a logger whenever i want
I am trying to log sql statements in a code in my Django Application Currently i am using the following logger config in my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'sql': { '()': SQLFormatter, 'format': '[%(duration).3f] %(statement)s', }, 'verbose': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, 'sql': { 'class': 'logging.StreamHandler', 'formatter': 'sql', 'level': 'DEBUG', } } } In genereal to log sql in django we can add the django.db.backends to the logger.config in the settings.py 'loggers': { 'django.db.backends': { 'handlers': ['sql'], 'level': 'DEBUG', 'propagate': False, }, But the problem is it will log every sql statement. So how can we start and stop logging for django.db.backends in between code. I have the following code in my views.py def someview(request) # start logging from here user_set = User.objects.all() for user in user_set: print(user.last_name) # stop logging from here Also i want to use the sql handler which i defined in the logging config. What code will go in start and stop logging place in the above view function. -
How to Make Subquery's Value Change According to Parent Query's Conditions?
I am making a messenger app and tracking unread messages per chat room and per user. My models are like these: class Room(models.Model): id = models.BigAutoField(primary_key=True) slug = models.SlugField(unique=True, max_length=255, allow_unicode=True) name = models.CharField(max_length=100) participants = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='participants') def unread_messages_count(self, user): last_checked_message_id = Subquery(models.Message.objects.filter( room_listeners__receiver=user, room_listeners__room=self).values('id')[:1]) return self.messages.filter(id__gt=last_checked_message_id).count() class Message(models.Model): id = models.BigAutoField(primary_key=True) slug = models.SlugField(unique=True, max_length=255, allow_unicode=True) room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="messages") sender = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) text = models.TextField(blank=True) created_date = models.DateTimeField(auto_now_add=True, db_index=True) class RoomListener(models.Model): id = models.BigAutoField(primary_key=True) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='room_listeners') room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='room_listeners') last_checked_message = models.ForeignKey(Message, default=Message.objects.first, on_delete=models.PROTECT, related_name='room_listeners') I could get a number of unread messages by writing unread_messages_count() in Room model. In addition, I want to get a number of unread messages per user. But I am confused with the way Subquery works. I want to do something like this: class User(AbstractUser, RelationshipStatus): id = models.BigAutoField(primary_key=True) def unread_messages_count last_checked_message_id = Subquery(models.Message.objects.filter( room_listeners__receiver=self).values('id')) return self.room_listeners.room.messages.filter(id__gt=last_checked_message_id).count() But I know this is wrong... because last_checked_message_id does not change depending on parent query's status. It is a fixed value. How can I make a subquery's value change according to parent query's conditions? -
Saving all user input data in Django simply?
This is may be an obvious question to a Django expert, but is there a way that I can save all user inputs (clicks and text-based in a web app simply without having to explicitly save every entry in a table). If this is possible, then how do I access it later? If I have to create models, like this I can: #(within a view function) UserInputs.objects.get_or_create(user=request.user, selection1=request.POST.get('selection1'), id=request.POST.get('id')), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) Is there an easier way to get it done? Because I have lots and lots of different user click inputs and specifying every one like this will really slow down my application. Is this data by change saved in one of the sessions tables? Or can we create a custom sessions table to do this? -
Retrieving the value of the field when the FK target doesn't exist
In my project I have two models: ModelA(models.Model): seq = models.ForeignKey(ModelB) foo = models.CharField() ModelB(models.Model): seq = models.ForeignKey(ModelA) bar = models.CharField() In the project flow ModelB are created after ModelA, but the seq value in ModelA is already set. The problem is that before the creation of ModelB objects I need to access ModelA.seq, and even the column having values I can't because Django tries to fetch ModelB instead of seq value. There is a way to access se value when the corresponding FK object doesn't exists? -
How to add extra fields to registration end point of rest-auth
Iam using rest-auth registration api for user registration. I have some extra fields in the UserProfile model. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) org_id = models.CharField(max_length=100, default='') is_teacher = models.BooleanField(blank=True, default=False) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) The Userprofile model is shown above. How can I add these fields to rest-auth regestration api endpoint and save the data to database. -
uWSGI doesn't find Django in Venv
I'm trying to setup a simple Django project with Nginx, uWSGI on my Centos7-Server with this Tutorial: How to Serve Django Applications with uWSGI and Nginx on CentOS 7 Everything worked pretty well, till creating firstsite.ini file. 1 [uwsgi] 2 project = firstsite 3 username = user 4 base = /home/%(username) 5 6 7 virtualenv = %(base)/Env/%(project) 8 chdir = %(base)/%(project) 9 home = %(base)/Env/%(project) 10 module = %(project).wsgi:application 11 12 master = true 13 processes = 5 14 15 uid = %(username) 16 socket = /run/uwsgi/%(project).sock 17 chown-socket = %(username):nginx 18 chmod-socket = 660 19 vacuum = true There I got stuck into. While setting up and trying to reach the Django Site I got an Internal Server Error. After checking error-log files and messages, I've implemented logto into my .ini file:: 21 #Error Logs 22 logto = %(base)/%(project)/error.log after checking this file it tells me this Error-Message:: *** Starting uWSGI 2.0.18 (64bit) on [Wed Aug 14 13:27:24 2019] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-36) on 23 July 2019 10:27:56 os: Linux-3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019 nodename: ip-172-31-34-37.eu-central-1.compute.internal machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 1 … -
How to run TensorBoard + Django + Apache + 2 TensorFlow log folders
I have: TensorFlow. Django website Apache many users. = many TF instances How to run 1 TensorBoard + 1 Django + 1 Apache + for many TensorFlow log folders ? -
I can't see images uploaded with summer notes on a deployed site. how should I setting?
Deployed a Django-based project http://terecal-hyun.co.kr/wm/myshortcut/ but The image uploaded using summer note(drag & drop) is printed on the development server. but There is no output after uploading to the site. Please let me know if you know how to set it up. Thank you -
How to run OpenEDX on Centos 7 with cPanel
There are so many documentation about running OpenEDX on Ubuntu, but there is not any clear documentation how to run OpenEDX on CentOS specially with cPanel. Anyone can help me regarding this case? -
How I can show output in multi line in django? '\n' does not work
I'm writing a simple django view in VSCode and I want write my HttpRespose in multi line, but it does not work? what is wrong? none of Escape Codes works! def index(request): return HttpResponse("firstline. \nanother line!!!!") I expect the output of firstline. another line!!! but it output is firstline. another line