Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot deploy django app - ImportError: No module named django.core.wsgi
So basically, I want to deploy django (wagtail) application on hosting in my country. Here's what I have done: I copied files of my project using FTP, to /home/ketohubp/KetoHub.pl. I created and entered venv (source venv/bin/activate). I tried to deploy app using following command: uwsgi --http 127.0.0.1:8054 --chdir /home/ketohubp/KetoHub.pl --wsgi-file /home/ketohubp/KetoHub.pl/wsgi.py --master --processes 1 --workers 1 --threads 1 --daemonize=/home/ketohubp/KetoHub.pl/log.txt I checked if django is installed: (venv) ketohubp@hs7:~$ django-admin version 2.2.8 I tried killing, and respawning uwsgi process using fuser -k 8054/tcp I checked what does log.txt contains: *** Starting uWSGI 2.0.18 (64bit) on [Mon Dec 9 17:37:19 2019] *** compiled with version: 6.3.0 20170516 on 21 November 2019 19:38:29 os: Linux-4.9.0-8-amd64 #1 SMP Debian 4.9.144-3.1 (2019-02-19) nodename: hs7.linux.pl machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /home/ketohubp/KetoHub.pl detected binary path: /home/ketohubp/venv/bin/uwsgi chdir() to /home/ketohubp/KetoHub.pl your processes number limit is 256771 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on 127.0.0.1:8054 fd 4 uwsgi socket 0 bound to TCP address 127.0.0.1:37743 (port auto-assigned) fd 3 Python version: 3.5.3 (default, Sep … -
Is it possible to create a single table for each model instance in Django?
I have a model called Schedule. A single schedule is a big table with 3 columns and maybe 500 rows. So, whenever a user saves an instance of a schedule, it needs to create a new table for that schedule only. This is not just specific to Django, how do you handle this in a database ? -
HIGHCHARTS POINTSTART TODAYS DATE
Hi I am using a line chart from HIGHCHARTS, can you please help me get the x-axis to show present month LAST on the x-axis - and the X-axis to automatically populate going back however many numbers of months it requires for the date. The date is monthly, so for example below installation has 8 points of data i would like it to show December as the 8th point on the X-axis and April as the first. I don't, however, want it to be limited to 8 months, and ideally would like for it to go to 18 months. Many Thanks for reading the long essay.. :)! ``Highcharts.chart('container', { title: { text: 'Solar Employment Growth by Sector, 2010-2016' }, subtitle: { text: 'Source: thesolarfoundation.com' }, yAxis: { title: { text: 'Number of Employees' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { label: { connectorAllowed: false }, pointStart: 2010 } }, series: [{ name: 'Installation', data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }, { name: 'Manufacturing', data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434] }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: … -
How can to load sccs styles from database?
I have field css_styles in Article model, in which writes scss styles for amp page. I try to include this styles as: <style> {{ object.css_styles }} </style> In the source code I see, that styles inclued, they're applicable, but incorrectly. -
Plain structure from OneToOne-related models (Django Rest Framework)
Models: class Person(models.Model): name = models.CharField(max_length=100) age = models.PositiveSmallIntegerField() # More Person fields class Student(models.Model): person = models.OneToOneField( Person, on_delete=models.PROTECT, primary_key=True) year_of_study = models.PositiveSmallIntegerField() # More Student fields Serializers: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' class StudentSerializer(serializers.ModelSerializer): person = PersonSerializer() class Meta: model = Student fields = '__all__' Views: class StudentView(viewsets.ReadOnlyModelViewSet): renderer_classes = [JSONRenderer] parser_classes = [JSONParser] queryset = Student.objects.all() serializer_class = StudentSerializer Requesting single Student: { "person": { "id": 1, "name": "Example Name", "age": 20 }, "year_of_study": 3 } But I need to work with plain structure like: { "id": 1, "name": "Example Name", "age": 20, "year_of_study": 3 } Where (in serializer or in view or somewhere else) and how should I do it? I only need GET requests (using ReadOnlyModelViewSet because of it). But if would also be nice to know how to create/update/delete such structure as well. -
django - data preset in DB, but can't see through Model.objects.all()/Admin
I'm trying to save the Profile details for a user, who is already registered with email, phone number etc. My form submits successfully and redirect to profile page as desired. The profile data is visible in template like {{request.user.profile.dob}} However when I access the /admin page and browse through /admin/profiles/profile/, it says 0 profiles. When I run Profile.objects.all() through shell, it gives <QuerySet []>. However, when I access the profile through one of the User objects, I get the data. The profile data is present when I check through sqlite console with the query select * from profiles_profile; I'm getting mad, but I think it must be an obvious mistake at my end. Please help. Thanks Here's my models /users class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True, help_text="A verification link will be sent to this email-id") is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) mobile = models.CharField(db_index=True,max_length=10,null=True, verbose_name="mobile number",) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' /profiles class Profile(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, related_name="profile") name=models.CharField(max_length=70, null=True) dob=models.DateField(blank=False,null=True, verbose_name="Date of birth",); settings.py AUTH_USER_MODEL = 'users.User' Here's my ModelForm class PersonalDetailsForm(forms.ModelForm): class Meta: model=Profile fields=('name', 'dob', ) and CreateView class AddPersonalDetails(CreateView, ): model=Profile form_class=PersonalDetailsForm def form_valid(self, form): profile = form.save(commit=False) profile.user = self.request.user … -
Django Need to autofill a field in one model based on data in another model with help of mutual foriegn key fields in both table
i am tryingto create a project management app in django wherin the user enters a boq of works to be done in one model and in another model he lists out the works progress . i have two models BOQ and DPR boq model choicestype=(('start','start'),('finish','finish')) class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300,null=True,blank=True) linktype = models.CharField(choices=choicestype,max_length=300,null=True,blank=True) linkduration = models.IntegerField(default=0) plannedstart = models.DateField(null=True,blank=True) plannedfinish = models.DateField(null=True,blank=True) actualstart = models.DateField(null=True,blank=True) actualfinish = models.DateField(null=True,blank=True) DPR class dprmodel(models.Model): Date=models.DateField() Contractor=models.CharField(max_length=300) Building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) Level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) Activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) Subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) Status=models.CharField(choices=choicestype,max_length=300) Labor=models.IntegerField() Both the models have Building,Level,Activity,Sub Activity as common fields. My entry in BOQ code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) MY DPR Entry Date :10-1-2019 contractor :A building=A-1 Level=L-1 Activity=Activity-A Subactivity=Subactivity-A Status =Start Labor=2 I need to populate the Actual start date in boqmodel such that if boqmodel.building = dprmodel.building and boqmodel.level = dprmodel.level and boqmodel.activity = dprmodel.activity and boqmodel.subactivity = dprmodel.subactivity and dpr.status=start. If the above condition exists then boq.actualstart=dpr.date I … -
Django not rendering view
I'm making a messaging system which has a message model and some views for things like inbox and conversation. Inbox view and template works and is linked to the conversation through the id of the sender. However, when I click on the senders name (The senders name is the link (template link is <a href="{% url 'conversation' sender.id %}">{{ sender }}</a>) that is meant to trigger the conversation view which is supposed to render the template convo.html ( the project level url for that is url(r'^messaging/inbox/conversation/(?P<id>[\w-]+)/$', message_views.Conversation.as_view(), name="conversation"),) ), Django changes the url but stays on the same page(So it triggers the inbox view and stays on inbox.html and changes the url but doesn't trigger the conversation view and doesn't render the convo.html template). I've tried changing from a function based view to a class based view and it did nothing. What am I doing wrong? Note: I'm still new to django so forgive me for any bad practices; I'm attempting to teach myself. views.py (inbox and conversation views) def inbox(request): messages = Message.objects.filter(receiver=request.user.id) senders = {} for message in messages: if message.sender not in senders: senders[message.sender] = message return render(request, 'inbox.html', {'senders': senders}) # There is only ever one … -
Django Rest Framework: specify a callback method when defining an endpoint?
I was asking myself if there is a simple way of defining a callback method when defining a DRF endpoint. For example, let's say I want to reproduce this workflow: app1 sends data to app2, calling a DRF endpoint living in app2 app2 immediately sends the HTTP 200/201 response to app1 app2 makes a "heavy" work then. Of course, I'm aware there are cleaner alternative: I know heavy work loads should live in a Celery task, or Django channel I know it would make more sense in my case that app2 is the one that makes the request, and app1 sends the response. I found ideas here but it's very related to Django itself, not Django Rest Framework. -
Django i18n: how to translate None when rendering a model field in template?
I have this code: # models.py class MyModel(models.Model): end_date = models.DateField(verbose_name=_('end_date_field'), null=True, blank=True) notes = models.TextField(verbose_name=_('notes_field')), null=True, blank=True) # template <span>{{ object.end_date }}</span> <span>{{ object.notes }}</span> # settings.py USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'pl' If end_date or notes is NULL in the database, it displays as "None" in the template. How do I provide one-off, "global" translation for a None value? I don't want to manually wrap every occurence of every nullable field across all templates. -
Django: unpack tuple in for loop
I've a queryset of items. And I've used itertools grouper to group them by 3. However, when the list contains more than a mutiple of 3, for example 7 elemenets, the last tuple is completed with None. I need to go through all groups (that contain 3 elements) and for each element: - Test if it is not None. - Compare the prices of each element inside the group, and return the id of the element with the lowers price and it's price. views.py: Queryset: pack_items = PackItem.objects.filter(cart=cart) Grouping by 3: pack_items_grouped_by_3 = list(grouper(pack_items, 3)) for p_item in pack_items_grouped_by_3: print(type(p_item)) #prints <class 'tuple'> print(p_item) #prints (<PackItem: PackItem object (65)>, <PackItem: PackItem object (66)>, <PackItem: PackItem object (67)>) for a, b, c in p_item: if a is not None: print(a) #print(a.pack.price) elif b is not None: print(b) #print(b.pack.price) elif c is not None: print(c) #print(c.pack.price) Error: for a, b, c in p_item: TypeError: cannot unpack non-iterable PackItem object -
Django does not Override Settings in Template Tag Testing
I have a custom template tag as below: # other imports from django.conf import settings DPS_TEMPLATE_TRUE_DEFAULT = getattr(settings, "DPS_TEMPLATE_TRUE_DEFAULT", "True") @register.simple_tag(name="var") def get_var(name, rit=DPS_TEMPLATE_TRUE_DEFAULT, rif="False", rin=""): """ A template tag to render value of a variable. """ _LOGGER.debug("Rendering value for `%s`...", name) variable = models.Variable.objects.get(name=name) value = variable.value if value is None: return rin if isinstance(value, bool): if value: return rit else: return rif return variable.value As you can see, I would like to set rit by DPS_TEMPLATE_TRUE_DEFAULT. I test this behavior as below: # `template_factory` and `context_factory` creates Template and Context instances accordingly. # i use them in other tests. they work. @pytest.mark.it("Render if True by settings") def test_render_if_true_settings( self, template_factory, context_factory, variable_factory, settings ): settings.DPS_TEMPLATE_TRUE_DEFAULT = "this is true by settings" variable_factory(True) template = template_factory("FOO", tag_name=self.tag_name).render( context_factory() ) assert "<p>this is true by settings</p>" in template I use pytest-django and, as the docs put, I can kinda mock the settings. However, when I run the test, it does not see DPS_TEMPLATE_TRUE_DEFAULT and uses "True". I debugged this behavior by removing "True" on getattr. Why does it not see DPS_TEMPLATE_TRUE_DEFAULT even if I set it in tests? Troubleshooting Using Standard Solutions The odd thing is I have also tried … -
Update custom user password using UpdateWithInlinesView from django-extra-views app
I have a model 'Admin' related to a (custom) user within a one to one field. To update all the fields I'm using django-extra-views app that basically use Django formset. It works well but for updating the password. Models class Users(AbstractUser): # common fields for all the users class Admins(models.Model): # Custom fields for the admins Forms: class AdminProfileForm(forms.ModelForm): class Meta: model = Users fields = ['first_name', 'last_name'] password1 = forms.CharField(widget=forms.PasswordInput, label='New Password') password2 = forms.CharField(widget=forms.PasswordInput, label='Confirm Password') Views: class AdminInline(InlineFormSet): model = Admins fields = ['admins_fiels_here'] class AdminProfile(BaseContext, UpdateWithInlinesView): .... inlines = [AdminInline] form_class = AdminProfileForm def get_object(self): return Users.objects.get(pk=self.request.user.id) def forms_valid(self, formset, inlines): password1 = formset.cleaned_data['password1'] password2 = formset.cleaned_data['password2'] if password2 and password1: if password1 != password2: # raise a ValidationError message user = self.request.user # at this point password is 'old_passord' user.set_password(password1) # now is 'password1' user.save() # 'password1' is correctly saved in db return super(AdminProfile, self).forms_valid(formset, inlines) As I describe above, the new password is saved but when super(AdminProfile, self).forms_valid(formset, inlines) ends its works the password results to be the old one. -
Django formset with crispy - submit buttons not submitting
I'm using a FormSet with crispy, and have but a submit button on each row, however hitting submit does not update records currently. I've searched and found some similar answers which suggest the submit isn't inside the form, but mine are. Also that a form action is missing, but none of my other crispy forms have actions and they work without issue. Are there any other reasons seen from the code below that would cause the records to not save? forms.py class ChangeGroupForm(FormHelper): def __init__(self, *args, **kwargs): super(ChangeGroupForm, self).__init__(*args, **kwargs) self.form_method = 'post' self.css_class = 'form-inline' self.form_id = 'changegroup_form' self.form_show_labels = False self.layout = Layout( Div( Div( Div( Field('group', placeholder='Group', css_class="form-control mb-2 mr-sm-2"), css_class='col-lg-3' ), Div( Field('gps', placeholder='gps coords', css_class="form-control mb-2 mr-sm-2"), css_class='col-lg-8' ), Div( HTML("""<input type="submit" name="submit" value="Save" class="btn btn-primary mt-1"/>"""), css_class='col-lg-1' ), css_class='row' ), ) ) self.render_required_fields = True views.py @login_required def db_change_groups(request): change_form = modelformset_factory(ChangeGroup, fields=('group','gps')) change_form_helper = ChangeGroupForm() return render(request, 'home/db_change_groups.html', { "change_form": change_form, "change_form_helper": change_form_helper, }) template.html {% crispy change_form change_form_helper %} rendered html <form id="changegroup_form" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="7v0000CPl3G70M6HLfF2FAiwefdfsdgdfwewdf7Gp4nay1hFqZ1Y34SBUA000mHBZQ54"> <div> <input type="hidden" name="form-TOTAL_FORMS" value="10" id="id_form-TOTAL_FORMS"> <input type="hidden" name="form-INITIAL_FORMS" value="9" id="id_form-INITIAL_FORMS"> <input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS"> <input type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"> </div> <div> <div … -
Firebase Authentication and Database with Django
I'm using firebase authentication with email and password to sign up users, but want them to be able to sign in using Phone number and password. Their phone number,email and password is stored in the RealTime Database. I used the 'sign_in_with_email_and_password' because I don't know how else to sign in authenticated users, since I'm new to Django. Any help would be appreciated. services.py from . import views from .models import Product import pyrebase def firebase_key(): #configuring firebase config = { 'apiKey' : "AIzaSyBd31FZCtpdRuxmkY0uiitJap1Mcet1iDA", 'authDomain' : "registration-c3373.firebaseapp.com", 'databaseURL' : "https://registration-c3373.firebaseio.com", 'projectId' : "registration-c3373", 'storageBucket' : "registration-c3373.appspot.com", 'messagingSenderId' : "123962731629", 'appId' : "1:123962731629:web:c4cc2ed965b1031daa2364" } firebase = pyrebase.initialize_app(config) return firebase views.py from django.shortcuts import render import requests from . import services import pyrebase from django.contrib import auth from .models import Product authe = services.firebase_key().auth() database = services.firebase_key().database() def postsign(request): number = request.POST.get('number') password = request.POST.get("password") try: #allowing only authorised users to log in to the site user = authe.sign_in_with_email_and_password(email,password) except: msg = "Invalid Credentials" return render(request, "Login.html", {"msg":msg}) print(user['idToken']) session_id = user['idToken'] request.session['uid'] = str(session_id) return render(request,"Welcome.html") def postSignUp(request): email = request.POST.get('email') password = request.POST.get("password") number = request.POST.get('number') #authenticating users try: user = authe.create_user_with_email_and_password(email,password) except: message = "Unable to create account, please try … -
Get all items with all properties using django multi-table inheritance and django rest framework
I'm using Django multi-table inheritance: class Parent(): common_property = ... class Child1(Parent): child1_specific_property = ... class Child2(Parent): child2_specific_property = ... And want to expose the list of all items on the same endpoint. If I make a basic serializer and view for the Parent model, I would just get the common properties (the ones living on that model), but in this case I want to get all child-specific properties for every item. Ideally something like this: items { type_1: { common_property child1_specific_property } type_2: { common_property child2_specific_property } } Am I missing any trivial way to do this? -
How To Get Rid Of "Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)" in Pychar+Django
When I run my test suite using pycharm for a django app in my local machine, at certain test I got: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) If I run that test in isolation using pycharm, it succeeds, which means there's not a problem in the app or test. If I disable that particular test, down the line I get the same error, in a different test, this one a dummy test! This seems to indicate that it's a problem with pycharm itself. The full test suite succeeds in the CI environment. I tried some suggestion from other stackoverflow questions, which didn't solve the issue: Unticking the Qt box in PyCharm Settings (Build, Ex... -> Python Debugger) Uninstalling python3-pyqt5 (same link as above): Pyqt is not installed in my local machine. Ticking gevent compatible in Pycharm Settings My Environment: python 3.7.3, djando 2.2.8, Pycharm 2019.2.4 (professional edition) -
django.core.exceptions.ImproperlyConfigured: i get this erro after i include path('", include('calc.urls'))
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] -
How to perform full text search in django?
For example i have a title How to use User Model in Django and I search with keyword only django then it returns all the titles which has django which is fine but when i enter a keyword like django user model then it returns none.How can I solve this Any help would be appreciated views.py def search_blogs(request): q = request.GET.get('q') if q: blogs = Blog.objects.filter(title__icontains=q).order_by('-created') return render(request,'blog/search_blogs.html',{"blogs":blogs,'q':q}) else: messages.error(request,'Please enter some keyword to search') return redirect('blog:blogs') template <form action="{% url 'blog:search_blog' %}" class="search-form"> <input type="text" name="q" placeholder="Search blogs" align="center" > <input type="submit" value="Search" class="btn-sm btn-info > </form> -
gunicorn + django - https requests get stuck
I use gunicorn as HTTP server and Django as the app behind. I didn't set up SSL at all. When I make a https request to my app the process seems to be waiting for something and the request is stucked. Since the app runs in a single thread and single worker other requests get blocked until I cancel my https request. How can I forbid https at all in gunicorn? I don't/can't use nginx at all to filter incoming requests. -
How to get a user to register only after admin accepts it in django?
I want to make a user, when registering in my application, have to choose a group (if it does not already exist, that he can create one and become admin automatically) and, when choosing a particular group, wait for admin accept it. How can I do this using django? Thanks in advance! -
TypeError: expected string or bytes-like object although datetime field not used Django
I'm trying to migrate my datas, but django returns me TypeError: expected string or bytes-like object error, although I just tried using datetime once, then deleted it, but still it returns an error. Here are my codes: models.py class Applicant(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=30) phone = models.CharField(max_length=15) email = models.EmailField(max_length=40) motivation_letter = models.TextField(max_length=200) is_accepted = models.BooleanField(default=False) photo = models.FileField(upload_to='static/applicant_photos') def __str__(self): return self.name an error: Operations to perform: Apply all migrations: admin, auth, ccapp, contenttypes, sessions Running migrations: Applying ccapp.0003_applicant_birth_date...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 "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards … -
Django gettext and gettext_lazy both imported with same name
In Django source code, gettext() and gettext_lazy() are both imported as _: from django.utils.translation import gettext, gettext_lazy as _ How does that import method work, and which kind of function benefits from it? -
Django creating database entries without model defined
I am writing a small application. I will have two endpoints: /generate - Accepts only POST /exercise - It has GET, and PUT I have the following model: class Exercise(models.Model): created = models.DateTimeField(auto_now_add=True) question = models.TextField(default='') answered = models.BooleanField(default=False) answer = models.TextField(default='',blank=True) class Meta: ordering = ['created'] def __str__(self): return self.question Here are the simple things I want to do on each endpoints. On /generate I want to generate 10 exercises. On /exercise - GET I want to return unanswered question/s On /exercise - PUT I want to update "only the answer" and set "answered" field. Here's my serialiser # snippets/serializers from rest_framework import serializers from .models import Exercise class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = Exercise fields = ('id', 'question', 'answer') class GenerateSerializer(serializers.ModelSerializer): class Meta: pass model = None model = Exercise exercise = Exercise() fields = ('id', 'question', 'answer') Finally the view: from django.shortcuts import render # Create your views here. # snippets/views.py from rest_framework import generics from .models import Exercise from .serializers import ExerciseSerializer, GenerateSerializer class ExerciseList(generics.ListAPIView): queryset = Exercise.objects.all() serializer_class = ExerciseSerializer class ExerciseDetail(generics.RetrieveUpdateAPIView): queryset = Exercise.objects.all() serializer_class = ExerciseSerializer class GenerateExercise(generics.CreateAPIView): # TODO: check if I need query set for create only method # queryset = … -
HTML Checkbox just returns None as value to my Django views
I have a very basic question. I created a checkbox form in HTML and I want to pass the Checkbox data to my Django views. Now I have the problem, that i just get returned None as a value and i don't know why. HTML code: <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="checkbox" name="checkbox" id="bb1"> <label class="form-check-label" for="bb1"> </label> </div> </div> checkbox_input = request.GET.get("bb1") print(checkbox_input) should't the output be something like "True", "False" or "on"? If I render my homepage and submit something, the link looks like this: 127.0.0.1:8000/?value=Hous&checkbox=on Why can't I grab the value "on"? I'm sorry I'm so sloppy about the way I phrase things here. I hope you guys can still help me :)