Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unique_for_date parameter for SlugField
First, I am reading a book on django and from it have created the following models.py (entire models.py included at the end, the two fields related to the question are here): slug = models.SlugField(max_length = 250, unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus we can retrieve single posts using date and slug publish = models.DateTimeField(default = timezone.now) Anyway, I have been searching online and have seen that you can use the unique_for_date parameter when creating a DateTimeField() but when it comes to using the parameter in a SlugField() I found one question asked on here almost ten years ago (How to create a unique_for_field slug in Django?) and so figured it wouldn't hurt to ask. If this can be done, can someone explain what that parameter is doing? Is this maybe something that is now obsolete in django? Thanks in advance. models.py: # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Pusblished'), ) title = models.CharField(max_length = 250) slug = models.SlugField(max_length = 250, unique_for_date = 'publish') #unique_for_date ensures that there will be only one post with a slug for a given date, thus … -
django filling a text field based on a button it is redirected from
I am trying to create a project management app each user has multiple projects which he creates my projects app is as follows class projectsmodel(models.Model): added_by = models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True,on_delete=models.SET_NULL) projects=models.CharField(max_length=300) def save_model(self,request,obj,form,change): obj.added_by=request.User super().save_model(request,obj,form,change) def __str__(self): return self.projects I filtered the projects which the user has created now i have my models.py file for boq app as follows Projects html file is as follows <tbody> <tr> <td style="vertical-align: top;">Projects<br> </td> <td>Open</td> <td>Edit</td> <td>Delete</td> </tr> {% for projectsmodel in projects1 %} <tr> <td>{{projectsmodel.projects}}</td> <td><button class="btn btn-warning">Open</button></button> <td><a href="{% url 'projectsedit' pk=projectsmodel.pk %}"<button class="btn btn-warning">Edit</button></a></button> <td><a href="{% url 'projectsdelete' pk=projectsmodel.pk %}"<button class="btn btn-warning">Delete</button></a></button> </td> </tr> {% endfor %} Every project has a home page whose template is as follows {% block content %} Project name : <br> Planned start :<br> Planned finish :<br> Actual start:<br> Actual finish :<br> Planned cost:<br> Expected cost of completion:<br> Percentage completion till date :<br> Cost incurred till date :<br> {% endblock %} When a user goes to the projects list and click a open button corresponding to a project then the homepage should be loaded with project name autofilled from corresponding field of the button he clicked -
Django: return list/tuple of element.id and min(element.price) from chunks of queryset
I've a cart_detail view that will be used to offer 3x2 discounts. So I'm making chunks of 3 elements from every element in my queryset. Using: def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] Queryset and Chunks generated: pack_items = PackItem.objects.filter(cart=cart) pack_items_grouped_by_3 = chunks(pack_items, 3) Now, from every chunk I need to return a list or tuple with the min price of all 3 elements and the ID of the element with the min price. I can return the min price of every chunk, but how to return also the ID of the pack from that chunk that has the min price? for e in pack_items_grouped_by_3: product_with_min_price = min(pack.pack.price for pack in e) #product_id = e.index(min(pack.pack.price for pack in e)) #print(product_id) Error: In the for loop above I've tried: product_id = e.index(min(pack.pack.price for pack in e)) print(product_id) But Erro says: ValueError at /carrito_de_compras/ 10 is not in list 10 is the min value for every chunk, in this case, maybe in the future 2 items can have price of 10 and one price of 8, and 8 would be the min price. -
How to check if a child in firebase database exists using Django?
I tried the following code, but it throws attribute error ''Database' object has no attribute 'exists''. I need to check if the number exists in the database or not since I want the existing users to log in using number and password. from django.shortcuts import render from django.views import View from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect import pyrebase from django.contrib import auth import json import requests from . import services from .models import Product authe = services.firebase_key().auth() database = services.firebase_key().database() def Login(request): return render(request, "Login.html") def postsign(request): data = services.get_products() print(data) context = {'data': data} number = request.POST.get('number') password = request.POST.get("password") if database.child("users").child(number).exists(): user = database.child("users").child(number).get().val() if user['number'] == number: if user['password'] == password: return render(request,"Welcome.html",context) -
Django says SECRET_KEY must not be empty
I imported a Django project from a repo, and when I try to make the migrations with python manage.py makemigrations, I get the following exception: File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. After looking online, I read that adding from base import * to __init__.py could solve it, but it just sends a different error: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) File "C:\Users\Iván\AppData\Local\Programs\Python\Python36\Lib\site-packages\django\conf\urls\static.py", line 22, in static raise ImproperlyConfigured("Empty static prefix not permitted") django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted My 'base.py' settings do have SECRET_KEY = 'my_key_value' , and my 'local.py' settings first line is from.base import *, and it doesn't override the SECRET_KEY, so I don't know why it says the SECRET_KEY is empty. I do not see any other settings through the project, so I don't know where else to look, I'm new to django, so I'm a bit lost here and have been stuck for a few days. -
Run a test on a Python/Django cronjob
I am trying to create some tests for my Django cronjobs. I have a file called cronjob.py: from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() from mailer.send_mail import send_a_mail @sched.scheduled_job('cron', hour=4) def send_test_mail(): send_a_mail( 'email', # email 'password', # password 'recipient', # recipient 'Test Mail', # subject 'test') # message I would like to create a test for this like so: from django.test import TestCase from cronjob import send_test_mail class TestCronjobs(TestCase): def test_send_test_mail(): send_test_mail() But when i run the test it starts, but nothing happens, not even an error. It looks like the code is waiting for "hour 4" to run the send_test_mail() function. Does anyone have an idea on how to by-pass the waiting time? Or how to run these cronjob tests? -
Django loading javascript static files
i am trying to load a javascript static file into my Django template but only the css file loads and not the javascript file. Ive ran through the Django documentation and i cant find any information on this... Has anyone encounter any problems like this before? Thanks, much appreciated settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'dist') STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] index.html {% load static %} <html> <head> <style type="text/javascript" src="{% static 'polls/js/jsfile.js' %}"></style> <link rel="stylesheet" type="text/css" href="{% static 'polls/css/back.css' %}"> </head> <body> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p>. {% endif %} <p id="test"></p> </body> </html> jsfile.js function codeAddress() { document.getElementById("test").innerHTML=Date(); } window.onload = codeAddress; Results1 Results 2 -
Thermal Printing with ExpressJS and Angular
So, I have a client who needs restaurant billing software along with android app for the waiters to take the order. I am all ok with the android app and the related API Backend. I have planned to do the backend in ExpressJS. But what I can't understand is how can I interface with the thermal printer. I am in the liberty of choosing a thermal printer of my choice. But where do I being ? I found this Option 1 and this option 2 and this is from where I can download the drivers for option 2 link. As you could have noticed, my budget for a thermal printer is not that high. But I still don't know how to proceed with printing from ExpressJS. I found these packages but I seriously can't understand anything. package 1 - NPM , package 2 - NPM. Also, I am familiar with Python (Django). So if anybody knows how to tackle this problem in Django, I am comfortable with the solution. -
combine() argument 1 must be datetime.date, not str
When using queryset in Django date range getting error from_date = request.POST.get('from_date') to_date = request.POST.get('to_date') min_dt = datetime.datetime.combine(from_date, datetime.time.min) max_dt = datetime.datetime.combine(to_date, datetime.time.max) daily_en = All_enquiries.objects.filter(enquired_at__range = (min_dt, max_dt)) when using variable manually value its working fine below from_date = datetime.date(2019, 12, 9) to_date = datetime.date(2019, 12, 9) -
Creating hierarchical relationships like REST Api with Django
New to Django. I know there is Django to Swagger generator is there but what I want is other way around. I want to create REST API: GET api/job/{id} POST api/job/{id} GET api/job/{id}/status POST api/job/{id}/status I don't think this project needs relational database, but for now I'm stuck with it. My model file looks like: class Job(models.Model): job_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) some_arg = models.TextField() class ChoicesEnum(Enum): @classmethod def choices(cls): return tuple((i.name, i.value) for i in cls) class Status(models.Model): class JobStatus(ChoicesEnum): NOT_STARTED = 0 IN_PROGRESS = 1 SUCCEEDED = 2 FAILED = 3 job_id = models.OneToOneField( Job, on_delete=models.CASCADE, primary_key=True, ) job_status = models.CharField(max_length=1, choices=JobStatus.choices()) But I'm not sure how am I supposed to create views for those two such a way they will be related. Sounds simple but can't wrap my head around. -
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 …