Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to replace LocaleRegexURLResolver from django 1.11
I am currently upgrading Django from 1.11 to 2.0 (to 2.2 in the long run). But recently I bumped into a problem which a can't solve for quiet some time. LocaleRegexURLResolver has been removed in 2.0 without any warning and the whole code has been refactored. Sadly we were using LocaleRegexURLResolver and I am not sure how to replicate it's functionality in the current version of Django. Any ideas? class SiteLocaleRegexURLResolver(LocaleRegexURLResolver): """ Overrides LocaleRegexURLResolver to use specified default language by site instead of global default language """ def __init__( self, urlconf_name, site, default_kwargs=None, app_name=None, namespace=None, prefix_default_language=True ): super(LocaleRegexURLResolver, self).__init__( None, urlconf_name, default_kwargs, app_name, namespace, ) self.prefix_default_language = prefix_default_language self.default_language = site.language_code @property def regex(self): language_code = get_language() or self.default_language if language_code not in self._regex_dict: if language_code == self.default_language and not self.prefix_default_language: regex_string = '' else: regex_string = '^%s/' % language_code self._regex_dict[language_code] = re.compile(regex_string, re.UNICODE) return self._regex_dict[language_code] Basically it changes the default language. In UK, site /docs/ would be in english and /fr/docs/ in french. In FR on the other hand, /docs/ would be in french and /uk/docs/ in english -
Django in line advertising
I want to put an ad in the article by dividing the article, like this bla bla bla bla bla bla bla bla bla bla ADS bla bla bla bla bla I searched but couldn't find anything. Do you have any suggestions? getting content with this code <p class="content"> {{ post.content|safe }} </p> -
Set Authorization Token in request header of GET route in django
I'm trying to access the below URL using HTTPResponseRedirect which is protected by Django_restframework_simplejwt. I would like to redirect to below URL after the signup success, for the email and mobile verification. http://base_url/acc_verification Assuming, I do have an access token, Now, How do I set the Authorization token in the request header to load the above page. Authorization: Token Python - 3.6.8 Django - 2.2.3 djangorestframework_simplejwt - Latest -
How to return images from restfulapi in django
i wanted to retrieve images in django from db. But as path of image will be stored in db i am not able to fetch the image from the retrieved path.is there any way to solve this in django -
How to return the processed form data to the template without saving it to the database?
I am making an English grammar checker. I have two models Sentence and Error. The user will input a sentence in the form and the errors (if any) will be generated and attached to the sentence programatically. Now I have two types of users: free and paid. I don't want to save the results to the database for the free accounts. How can I display the results in the template without saving them to the database? # noting gets displayed in the template with this code ... if request.method == 'POST': form = SentenceForm(request.POST) if form.is_valid(): cd = form.cleaned_data form.save(commit=False) sent_str = cd['sent'] s = Sentence(sent=sent_str, sent_correct=sent_str) s.author = user # s.save(commit=False) --- This line throws an error if user.is_basic or user.is_standard or user.is_premium: s.save() sent = nlp(sent_str) sents = [] subjs = [t for t in sent if t.dep_ in subj_ls] two_subj = False if len(subjs) >= 2: two_subj = True if not subjs: has_imp_patt = imp_patt(sent) if has_imp_patt: pass else: print('Line 60') msg = '<span style="color:#be0000">Subject\\verb not found</span>' m = Message(msg=msg, sent=s) if user.is_basic or user.is_standard or user.is_premium: m.save() form = SentenceForm() return render(request, 'home.html', {'sentences': sentences, 'form': form}) ... -
app.yaml configuration for websocket django app
WebSocket works in the development server but not in the Google cloud. the official docs provide WebSocket example in flask. did not get in django? think the cause of the error is "entrypoint:" variable in app.yaml? app.yaml # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT myproject.wsgi:application beta_settings: cloud_sql_instances: project-id:region:instance-name runtime_config: python_version: 3 # [END runtime] settings.py ASGI_APPLICATION = "myproject.routing.application" # channels CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { # "hosts": [("localhost", 6379)], "hosts": [("redis-ip", port)] }, "ROUTING": "myproject.routing.application", }, } routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from app.consumers import NoseyConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("path/", NoseyConsumer), ]) }) in google cloud it rise an error "failed: Error during WebSocket handshake: Unexpected response code: 404". -
In Django REST Framework, how to initialize a field value for a createAPIView based on the GET query parameter?
I know how to get the query parameter in View or Serializer by: request.GET.get(query_param_key). I also know we can use it to do sorts of things like filtering the query set for a ListView, but, I just couldn't figure out how it can be used to initialise a field in a CreateView, or any legit place to just keep or hold this information so that it could be used later when POSTing to set the default value for a field. For example, if the url of the page to create a "product" is: http://localhost:8000/myapp/create_product/?item_id=1 The serializer of the "product" has a foreign field "item", which would like to be initialised with item's id = 1 when the above creation page is called with this parameter. Obviously, there isn't any place other than this query parameter that has the information "item_id=1", so either needs a way to initialise the "item" field, or there is a suitable place to hold this information to use it when POSTing. But I don't know how this can be achieved. The html template for the "create_product" page is a very basic one using render_form: {% extends "base_generic.html" %} {% load rest_framework %} {% block content %} … -
Django urls giving me different direction
I am working on Django project where I am implementing the in-build authentication framework. I created urls directly to in-build views. I am supposed to visit the following url http://127.0.0.1:8000/account/login/ which redirects me to the following urls and supposed to choose 'LoginView' and it's corresponding template urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), ] Here is the template code {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. please try again. </p> {% else %} <p>Please, use the following form to log-in: </p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{form.as_p}} {% csrf_token %} <input type="hidden" name="next" value="{{next}}"> <p><input type="submit" value="Log-in"></p> </form> </div> {% endblock %} when I submitted the credentials I am getting the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ Using the URLconf defined in xxxxxxxxxx.urls, Django tried these URL patterns, in this order: admin/ account/ The current path, accounts/profile/, didn't match any of these. Please help me with this. -
Queryset which returns only objects with a foreign key assigned.Django
I'm trying to find a simple way to return objects which have a foreign key assigned to each other. For example, I have such models.py file: class Parent(models.Model): name = models.CharField(max_length=100) class Children(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=10) For my parent I create objects family1, family2, family3. And for my children I create the object John and Stefani which is related with a foreign key from family1. How easiest to create queryset which returns only family1(only once, even though it has many related objects) Any help will be appreciated. Sorry for my bad English. If the question is not understood, I will write additional explanations.