Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to access radio button selected value in Django
I am trying to access radio button selected value in my django view but it returns on instead of selected value. Template form <form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group" id="div_id_sample" > <label for="id_sample" class="col-form-label requiredField">Select File</label><br> <div class="btn btn-primary"> <input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe"> </div> </div> <div class="form-group"> <label for="radiogroup">Enforce Timeout</label><br> <div class="btn-group" data-toggle="buttons" id="radiogroup"> <label class="btn btn-secondary"> <input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds </label> <label class="btn btn-secondary"> <input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds </label> <label class="btn btn-secondary active"> <input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds </label> </div> </div> <div class="form-group"> <label for="radiogroup2">Select Machine:</label><br> <div class="btn-group" data-toggle="buttons" id="radiogroup2"> <label class="btn btn-secondary"> <input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP </label> <label class="btn btn-secondary active"> <input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7 </label> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> views.py in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why. def upload(request): if request.user.is_authenticated: if request.method == … -
Data not being saved to database with django forms
I am working on a django application, which contains a form. I defined the model and made the migrations. But the data is not being saved into the database. And the URL for the application gets messed up when I use submit the form. This is my code so far models.py class modelPost(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=70) phone = models.CharField(max_length=12) def publish(self): self.save() def __str__(self): return self.name forms.py from .models import modelPost class testForm(forms.ModelForm): class Meta: model = modelPost fields = ('name', 'email', 'phone') views.py from .forms import testForm # Create your views here. def index(request): if request.method == "POST": testForm = testForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('home') else: testForm = testForm() return render(request, 'index.html', {'testForm': testForm}) index.html <form> {% csrf_token %} {{ testForm.name|as_crispy_field }} {{ testForm.email|as_crispy_field }} {{ testForm.phone|as_crispy_field }} <input type="submit" value="check" class="save btn submit_button"> </form> when I try to submit the form, this happens to the url http://127.0.0.1:8000/?csrfmiddlewaretoken=BG2i7fSbwG1d1cOlLWcEzy5ZQgsNYzMrhDJRarXkR3JyhetpWvqNV48ExY7xM9EW&name=randomPerson&email=test%40test.com&phone=12345678 These are some links that I checked, but the answers dont work link1 link2 -
How to force pip to install last version of django?
There are have many versions of python on my ubuntu. I have set the default version for python command to 3.7 using alias. I have created a virtual env using virtualenvwrapper and want to install django on this virtual. After activating this virtual if I type python command, version 3.7 runs. But if I type 'pip install Django' the old version 1.13 which is related to python 2.7 is installed. I have tried to use 'pip install Django==2.2.6' but no success. It says: DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support How can I force pip to install version related to python 3.7? -
How can I create a python console in VS Code that includes django app settings?
I got a little bit used to how PyCharm Professional works but I like Visual Studio Code way more, I like the Python console of PyCharm, which automatically includes things like DJANGO_SETTINGS_MODULE. Is there a way to achieve something similar in Visual Studio Code? -
Bootstrap_form inherit the types from the model
I’m new to Django and bootstrap, so apologies if this is a very basic issue. I’ve defined my model, created my (CreateView) view and am using {% bootstrap_form form %}. It displays nicely, but the field are all the same length on screen and don’t size to the definition in the model (I.e, a date field is much longer than defined in the model). How can I get my form to inherit the size/ width defined in the model? -
Django temporary fields only upon creation
Consider two models: Contract class Contract(models.Model): employee = models.OneToOneField(Employee, on_delete=models.CASCADE) contract_type = models.ForeignKey(ContractType, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() and Employee class Employee(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) contract = models.OneToOneField(Contract, on_delete=models.CASCADE, null=True, blank=True) I was wondering if there's a way to add temporary fields in a model form that are only shown upon creation in the Employee model so I can add all those fields while I create a new Employee then when saving, I first create an Employee object, then automatically generate a Contract object and edit the original Employee object and link the now generated Contract object. I really hope this makes sense, and if it does, can someone guide me in the right direction? Thank you, for your time reading this. -
Creating professional user registration with Django rest framework
I am trying to create a good professional user registration and authentication for a personal project I am building, that sends emails to authenticate users’ email. Because it’s a REST API I am building, I searched for solutions and I found out about Django-rest-auth which depends on Django-all auth. For some reason, it still hasn’t been able to work out for me. -
Creating unique identifiers for urls
I'm currently trying to develop an application. I am using Django framework for my backend. Now in my app I will show stuff like posts or pictures. Initially I just used the primary key to display inside the urls. I was told that this wasn't so good because it reveals too much information to a potential attacker. Instead I should use uuid. I read into uuid and now realised that they are very handy. Also I read in some posts also here on SO that uuid may not have enough randomness and could be guessable. A solid alternative would be to use the secrets module from python. Since I'm not experienced enough to make a good assessement I'm reaching out to more experienced developers. Would you just stick with uuid and maybe shorten it or go with the secrets module of python. Please note that as of now I won't be using the id for anything else than uniquely identifying an object. Is it okay to use uuids of 32 characters length? The url will get kind of long. -
changing from address on send_mail
I've hooked in Gsuite as my SMTP server. It sends out emails and it works very well. However, when using the send_mail function in django, I want to indicate a from address other than the email address that I have hooked into Gsuite, which is admin@mywebsite.com. subject = 'Order Confirmation' from_email = "jim@gmail.com" to_email = ("james@gmail.com",) txt_message = "some text" html_message = "some other text" send_mail(subject, txt_message, from_email, to_email, html_message=html_message, fail_silently=False, auth_user="admin@mywebsite.com", auth_password="PASSWORD" ) When an email is sent out with this code, when I look at the resulting email email in the email client of james@gmail.com, the "from" address is admin@mywebsite.com rather than jim@gmail.com. Is there a way that I can change this so that the 'from' is jim@gmail.com or at least the 'reply-to' is jim@gmail.com? Thanks for your help! -
How can I create object of the extended model of User on Django
I'm writing the API for my project. There I have model of user extended by the Profile model. I don't know how to make registration. I should get email, login, password and judge_id by json and create user and profile using this data. I wrote Profile model and serialisers for User and Profile(I'm not really sure how should transfer User to the user field). But how should I write registration in my views (as I understand there I should use serialisers)? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) judge_id = models.CharField(max_length=30) completed_tasks = models.ManyToManyField(Task, related_name="compl+") wa_tasks = models.ManyToManyField(Task, related_name="wa+") todo_tasks = models.ManyToManyField(Task, related_name="todo+") notes = models.ManyToManyField(Note) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' def create(self, validated_data): profile = User( judge_id=validated_data['judge_id'], user=validated_data['user']) profile.set_password(validated_data['password']) profile.save() return profile -
Cannot resolve keyword 'name' into field. Choices are: ab_price, amazon_price, desc, fk_price, id, is_avl, launch_date,
I am getting this error but, I don't have name in my ORM class, i was expecting it to be fine. before this, I had changed the name field to p_model and now name is nowhere in the code models.py class Product(models.Model): p_model = models.CharField(max_length=200, verbose_name='Model') desc = models.CharField(max_length=200, verbose_name='Description') launch_date = models.DateField(verbose_name='Launch Date') amazon_price = models.FloatField(verbose_name='Amazon Price') fk_price = models.FloatField(verbose_name='Flipkart Price') sd_price = models.FloatField(verbose_name='SnapDeal Price') ab_price = models.FloatField(verbose_name='Alibaba Price') is_avl = models.BooleanField(default=False, verbose_name='In Stock') views.py def addproduct(request): if request.method == 'POST': form = Addproduct(request.POST) if form.is_valid(): form.save() usrn = request.user.username wall = wallet.objects.get(username=usrn) bal = wall.Balance wallet.objects.update(username=usrn, Balance=bal + 5) newbal = get_bal(request) messages.success(request, f'Product has been added successfully, Your current wallet Balance is {newbal} try ' f'adding more') return redirect('addproduct') else: return HttpResponse("Invalid Data") else: form = Addproduct() bal = get_bal(request) usrn = request.user.username return render(request, 'register/addproduct.html', {'form': form, 'bal': bal, 'usr': usrn}) forms.py class Addproduct(forms.ModelForm): class Meta: model = Product fields = ('__all__') ''' -
Django: How to use views&forms of an app in main templates?
I'm using edge repo for quick starting a django project. The repo has an app called "accounts" which handles signin up, logging in, etc with crispy forms. However i'd like to allow users to sign up from the home.html which isn't located in accounts/templates. I have tried adding the following code to home.html: {% if not user.is_authenticated %} {% include "signup.html" %} {% include "auth_base.html" %} {% block form %} {% crispy form %} <div class="form-message"> <p> Already signed up? <a href="{% url 'accounts:login' %}">Log in</a>. </p> </div> {% endblock form %} {% endif %} However since the main views.py can't locate views/forms in account app i'm faced with the following error: django.template.base.VariableDoesNotExist: Failed lookup for key [form] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <my_env.views.HomePage object at 0x7f0ed11cec88>}] My project files are the same as here with only "project_name" being different. I expected to be able to use the signup form in home.html. Can anyone point me the right way? -
how can I automatically generate slug for user OneToOneField url
I am building a django application that requires users to sign in and have profiles that other users should be able to view but I am stuck at generating unique slug urls for each user. I want a user to be redirected to myexample.com/elon-musk instead of my-example.com/profile so that every user profile page can be unique.Any ideas on how I can go about it? Thanks In advance. class ContractorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name= 'profile',) image = models.ImageField(default='default.jpg', upload_to='profile_pics') first_name = models.CharField(max_length=20, blank=True) last_name = models.CharField(max_length=20, blank=True) slug = models.SlugField(null=True, blank=True) def save(self, *args, **kwargs): if slug is None: slug = slugify(self.user) while self.__class__.objects.filter(slug=slug).exists(): slug = "%s-%s" % (slug,str(uuid.uuid4())[:5]) self.slug = slug super(ContractorProfile, self).save(*args, **kwargs) @login_required def dynamic_lookup_view(request, user): obj = ContractorProfile.objects.get(user=user) return render (request, "CsignTest/profile.html", {"obj": obj}) ```urls.py re_path(r'^profile/(?P<user>\w+)/$', CsignTest_views.dynamic_lookup_view, name='user-prof'), -
Convert djongo EmbeddedModelField
Hi I am new to Python's Django framework and ORM. I have this problem that I can not solve. I have collection in mongo called users Looks something like this: { _id: username: email: password: user_type: } I want to have 2 types of user (1 = customer, 2= supplier), both able to log into application. After some research I found that all users should be stored in one collection. So i decided to use user_type and two additional fields: { customer_data: // object that will be filled if user is customer supplier_data: // object that will be filled if user is supplier } I followed tutorial at: Djongo docs page, but I still get same error: Don't know how to convert the Django field user.User.supplier_data (<class 'djongo.models.fields.EmbeddedModelField'>) My User model: class User(AbstractBaseUser): _id = models.ObjectIdField() password = models.CharField(max_length=128) # Other fields supplier_data = models.EmbeddedModelField(model_container=SupplierData, default={}, null=True) SupplierData model: class SupplierData(models.Model): phone = models.CharField(max_length=100) website = models.URLField() description = models.TextField() rating = models.DecimalField(default=0.0, decimal_places=1, max_digits=5) class Meta: abstract = True models is from djongo library (from djongo import models) I could use another collections with customer and supplier data with relation to users collection, but supplier will have more nested … -
Why is Django converting aware timestamp received from API request
My Django app receives POST API request with one of fields in body containing aware timestamp. If I log it's value right after deserialization I'm seeing the same time stamp but in different timezone. Here's example of submitted request body: { "event_timestamp": "2019-11-08T15:00:00+02:00", ... } Yet if I try to log the value of this field right after it passes deserialization I'm seeing 2019-11-08 14:00:00+01:00 TZ is enabled and configurred to CEST time zone: USE_TZ = True TIME_ZONE = 'Europe/Vienna' I could make an assumption that Django is automatically converting received timestamp into defined timezone for entire project, but the result of such a conversion would have given me the same result: 2019-11-08T15:00:00+02:00 represented as CEST timezone is 2019-11-08T15:00:00+02:00 I understand that such conversions are normal process of Django handling aware datetime objects, but why does it convert a value to a timezone which is neither set as default for the project itself nor has any relation to received timestamp? Is there a way of managing default way of such convertions to timezone I manually define in settings.py or disable them all together? -
django form error didn't return an HttpResponse object when entering an error in the sign up form
Everything works perfect except if you fill in the form incorrectly. For example 2 different passwords. Before you all start going this is a duplicate to this: didn't return an HttpResponse object. Please do not. My view does not have this issue. I have tried everything I have seen in every other post and it does not work. Also I'm pretty sure that this code used to work and for some reason now It doesn't. Any help, very much appreciated. This is the error.. raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) ValueError: The view main.views.home didn't return an HttpResponse object. This is the view if request.method =='POST': form = MyRegistrationForm(request.POST) if form.is_valid(): form.save() username= request.POST.get('username','') email= request.POST.get('email','') subject = 'Hi {0} Welcome to blabla'.format(username) msg="Hi {0},".format(username) msg=msg+settings.WELCOME_EMAIL message = msg recipients = ['info@blabla.com'] if email: recipients.append(email) send_mail(subject, message, 'info@blabla.com', recipients, fail_silently=False) return HttpResponseRedirect('thank-you') else: form = MyRegistrationForm() return render(request, 'reg.html', {'form': form}) The template is very big with lots of other stuff going on so I am not including it all here except what I think is relevant. <div>{{ form.non_field_errors }}<br/> <div class="myerr"><h4><strong>{{ form.username.errors }}<br/> {{ form.email.errors }}<br/> {{ form.password1.errors }}<br/> {{ form.password2.errors }}<br/></strong></h4> </div> … -
My Django formset isn't saving object images
I created an upload form for users allowing them to create a model object. Everything else works, but the image field doesn't store the loaded images. I use the Crispy FormHelper in the views.py, but HTML source code shows that the elements (enctype, layout_class, field_class etc...) aren't loading. I think this is where the problem is. Here's what the rendered form looks like: For context, the form should look like this: <form class="form-horizontal" method="post" > ... </form> I've walked through the code and the tutorial I used line by line, but I can't find where the problem lies. views.py class CarCreate(generic.CreateView): model = Car slug_field = 'id' slug_url_kwarg = 'car_create' template_name = 'showroom/car_create.html' form_class = CreateCarForm success_url = None def get_context_data(self, **kwargs): data = super(CarCreate, self).get_context_data(**kwargs) self.request.POST: data['images'] = CarImageFormSet(self.request.POST, self.request.FILES) else: data['images'] = CarImageFormSet() return data def form_valid(self, form): context = self.get_context_data() images = context['images'] with transaction.atomic(): form.instance.seller = self.request.user self.object = form.save() if images.is_valid(): images.instance = self.object images.save() return super(CarCreate, self).form_valid(form) def get_success_url(self): # return reverse_lazy('showroom:cars', kwargs={'slug': self.object.id}) # Throws an error return reverse_lazy('showroom:cars') forms.py class CreateCarForm(ModelForm): class Meta: model = Car exclude = ['seller', 'id'] def __init__(self, *args, **kwargs): super(CreateCarForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = … -
Search multiple fields with django
/api/customer/list?search=john When I search for "john" in the "customerName" field, all records come. /api/customer/list?customerName=john When I search this way, only John's record comes. But when I search in the "customerName and customerSurname" fields, there are no records or missing records. How do I search for two fields using "search"? class CustomerListAPIView(ListAPIView): serializer_class = CustomerCreateSerializer permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ['customerName'] def get_queryset(self): queryset = Customer.objects.filter(user=self.request.user) print(queryset) return queryset HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 10, "customerName": "john", "customerSurname": "down", "customerIdentityNo": "2261", "customerGender": "M", "customerPhone": "34", "customerBirth": "2019-10-11", "customerDescription": "description", "customerStatus": false, "createdDate": "2019-10-01T08:33:15.769174Z", "modifiedDate": "2019-10-18T09:09:01.547840Z", "modifiedByUser": 1, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "ea83b54e-8352-47c8-b26e-7ce747275cfe" }, { "id": 27, "customerName": "warren", "customerSurname": "buffet", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "888888", "customerBirth": "2019-10-10", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:06:28.353817Z", "modifiedDate": "2019-10-20T07:06:28.353831Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "a049714c-da11-4608-8ceb-eaf4ba030c6b" }, { "id": 28, "customerName": "bill", "customerSurname": "gates", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "745444", "customerBirth": "2019-10-17", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:12:53.066400Z", "modifiedDate": "2019-10-20T07:12:53.066458Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", "customerKey": "c9194b03-6b1a-42d6-b38a-ed5a7bf40df8" }, { "id": 29, "customerName": "john", "customerSurname": "snowden", "customerIdentityNo": "22611611650", "customerGender": "M", "customerPhone": "24455", "customerBirth": "2019-10-16", "customerDescription": "", "customerStatus": false, "createdDate": "2019-10-20T07:14:26.048885Z", "modifiedDate": "2019-10-20T07:14:26.048899Z", "modifiedByUser": null, "created_userKey": "0245abb9-2837-4f37-ae02-9be1b88887ef", … -
Django rest Framework - Expected a list of items but got type "QuerySet"
I try to serialize query set. But Im getting {'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]} error. How to solve this error. def post(self, request): data = request.data user_name = data.get('username') signup_filtered_data = Signup.objects.filter(username= user_name).values() print(signup_filtered_data) serializer = SignupSerializer(data= signup_filtered_data, many=True) serializer.is_valid() print(serializer.errors) signup_jason_data = json.dumps(serializer.data) return HttpResponse(signup_jason_data) models.py class Signup(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, unique= True) phone_number = models.CharField(max_length=12, unique= True) username = models.CharField(max_length=50, unique= True) password = models.CharField(max_length=50, blank=True, null=True) serializers.py class SignupSerializer(serializers.ModelSerializer): class Meta: model = Signup fields = '__all__' -
KeyError at /log_data "None of [Index(['abc' , 'qwe' ], dtype='object')] are in the [columns]"
Getting KeyError at/log With this code, I want to Check Username entered by user In HTML with Username in CSV. Am Working On Django. def log_data(request): if 'uname' in request.POST: username=request.POST['uname'] else: username = False if 'pass' in request.POST: pw=request.POST['pass'] else: pw=False data = pd.read_csv('login.csv') for i in data: if ((data[data.USERNAME])==username ): #if((data['USERNAME']==username) and (int(data['PASSWORD'])==int(pw))): f=1 Error is at if ((data[data.USERNAME])==username ): #if((data['USERNAME']==username) and (int(data['PASSWORD'])==int(pw))): etc.. -
Django Images In Media Not Displaying Despite Correct Settings
I'm trying to upload an image from a form and display it on another template, however the images in media cannot be found. Model class Upload(models.Model): image = models.ImageField(upload_to='images/') View class HomePageView(CreateView): model = Upload form_class = UploadForm template_name = 'home.html' success_url = reverse_lazy('rank') class RankView(ListView): model = Rank template_name = 'rank.html' Settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' Urls urlpatterns = [ path('', include('avatars.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Templates <img src="{{upload.image.url}}"> Inspecting the code in browser, the img url is 'unknown' -
Unable to Access Other Apps in Django
I am writing a beginner Django app. I am currently able to the first app that I created. However, I am not able to figure out how to access the other two apps. swiss (project) |_ app_picker (default app) |_ eft |_ servermon I am currently able to access the app_picker by typing 127.0.0.1:8000/app_picker/. But when I type in 127.0.0.1:8000/eft or 172.0.0.1:8000/servermon the page is not found. What am I failing to understand with my Django config? Installed Apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_picker', 'etf', 'servermon', ] Project URLS from django.contrib import admin from django.urls import path from django.views.generic import RedirectView from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('app_picker/', include('app_picker.urls')), path('etf/', include('etf.urls')), path('servermon/', include('servermon.urls')), path('', RedirectView.as_view(url='app_picker/', permanent=True)), ] #Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] app_picker URLs from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] eft URLs from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('eft/', views.base, name='eft_base'), ] eft Views from django.shortcuts import render # Create your … -
How to access django models from a scheduled script?
TL;DR: I have an app that I want to run a routine every day at midnight (for that I'm using APScheduler). In the middle of this routine it's supposed to access data from a few django models. The logic is Django is running > run apps.py > run scheduler.py > run routine.py > access models.py. Exceptions raised at the bottom of the post. - Here comes the details: My directory is this: myproject/ - manage.py + myproject/ -- settings.py -- wsgi.py -- ... + myapp/ -+ static/ -+ templates/ -- admin.py -- apps.py -- models.py -- views.py -- scheduler.py #<<<<<<<<<< -- routine.py #<<<<<<<<<< -- ... myapp/models.py class MyModel(models.Model): field1 = models.DateField(auto_now=True) field2 = models.DecimalField(max_digits=19, decimal_places=16) ... myapp/apps.py from django.apps import AppConfig from .scheduler import ScheduledRoutine class MyAppConfig(AppConfig): name = 'myapp' def ready(self): routine = ScheduledRoutine() routine.start() myapp/scheduler.py from .routine import MyRoutine #from ..routine import MyRoutine # See error nr3 <<<<<<<<< from apscheduler.schedulers.background import BackgroundScheduler class ScheduledRoutine(object): def start(self): self.scheduler = BackgroundScheduler() startdate = datetime.now() #For brevity assume datetime object self.scheduler.add_job(self.routine, 'interval', days=1, start_date=startdate) self.scheduler.start() def routine(self): data = MyRoutine() myapp/routine.py import os os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" import django django.setup() from .models import MyModel #from myapp.models import MyModel # See error nr3 … -
Django - Taking values from POST
I'm passing some data to my template ("appointments.html") which looks like this: Appointments today Appointment ID : 84218332 Scheduled Time: 2019-10-18T01:00:00 Arrived Appointment ID : 84218332 Scheduled Time: 2019-10-18T22:05:00 Arrived <h1>Appointments today</h1> {% for p in appointment %} <tr> <td>Appointment ID : {{ p.patient }} Scheduled Time: {{p.scheduled_time}}</td> <td> <form action="arrived" method="post"> {% csrf_token %} <input type="hidden" name="appid" value="{{ p.id }}"> <input type="submit" value="Arrived" class="btn btn-primary"> </form> </td> </tr> {% endfor %} I want to call another view in views.py by clicking on "Arrived" button which gets back the p.id which is passed as a value to further use it for other purposes. urls.py : url(r'^appointment/arrived/$', views.arrived, name='arrived') views.py def arrived(request): if request.method == 'POST': appointment_id = request.POST.get("appid", "") print(appointment_id) ERROR : You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/appointment/arrived/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. How do I fix this and what am I missing exactly? -
How to load template that it has own css like bs3 to another page?
I have a form that it has Bootstrap 4 CSS classes. I want add jquery image upload code in my form but this codes have Bootstrap 3 CSS classes. I put my jquery block to image_block.html with {% load 'image_block.html %} tag. But I load image_block.html to my form.html file BS3 classes squash my BS4 classes and page is destroyed! image_block.html: <!DOCTYPE HTML> {% load upload_tags %} <head> <!-- Force latest IE rendering engine or ChromeFrame if installed --> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap styles --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <!-- Generic page styles --> <link rel="stylesheet" href="/static/jquery-upload/css/style.css"> <!-- blueimp Gallery styles --> <link rel="stylesheet" href="/static/jquery-upload/css/blueimp-gallery.min.css"> <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars --> <link rel="stylesheet" href="/static/jquery-upload/css/jquery.fileupload-ui.css"> <!-- CSS adjustments for browsers with JavaScript disabled --> <noscript><link rel="stylesheet" href="/staticjquery-upload//css/jquery.fileupload-ui-noscript.css"></noscript> <!-- Shim to make HTML5 elements usable in older Internet Explorer versions --> <!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]--> </head> {% block upload %} <div class="container"> <!-- The file upload form used as target for the file upload widget --> <form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %} <!-- Redirect browsers with JavaScript disabled to the …