Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to create a new company and link it to the existing user
Good day all :) I am new in Django world, Basically I have a three apps: CustomUsers , Company and Team with the following: First a user creates an 'account' , then user create a new 'Company' and then a new'Team', my question is how to link the user to the new team and company when they are created? CustomUSer App: class CustomUser(AbstractUser): bio = models.CharField(max_length=300, null=True, blank=True) image = models.ImageField(upload_to="userimages/", null=True, blank=True) job_title = models.CharField(max_length=300, null=True, blank=True) member_of_company = models.ForeignKey("company.Company", null=True, blank=True, on_delete=models.SET_NULL) and Company App class Company(models.Model): title = models.CharField(max_length=200) logo = models.ImageField(null=True, blank=True,upload_to="logos/") website= models.CharField(null=True, blank=True, max_length=200) and finally team app: class Team(models.Model): title = models.CharField(max_length=150) members = models.ManyToManyField("accounts.CustomUser", blank=True, related_name='team_members') company = models.ForeignKey("company.Company", null=True, blank=True, on_delete=models.SET_NULL, related_name='teams') my questions are 1) how to link the new company with the current user and 2) how to link the new "team" with the existing company and user. Thanks in advance. -
How to pass python string to javascript as string in Django?
I have a python string which is javascript code and I want to pass this string to javascript as string too. My idea is to pass python string to javascript string and then use eval() function in javascript to turn that string to actual code and execute it. def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' return render(request, "app/login.html", {'success': success}) var code = "{{success}}" console.log(code) // return Uncaught SyntaxError: Invalid or unexpected token I have also tried pass the string as json like this def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' success = json.dumps(success) return render(request, "app/login.html", {'success': success}) var code = JSON.parse("{{success|safe}}"); console.log(code) //return Uncaught SyntaxError: missing ) after argument list Last thing that I have tried is def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' return render(request, "app/login.html", {'success': success}) <h3 id="success_id" hidden>{{success}}</h3> <script> var code = $("#success_id").text(); console.log(code) //return window.location = "{% url 'home' %}" // if i do this var code = "window.location = '{% url 'home' %}'"; console.log(code) // return window.location = /app/home/ // I want it to return … -
Django sessions doesn't allow me to add items in my cart
I am creating an eCommerce store and I use Django sessions to store the cart information. However, for some reason, only 2 items get stored in the cart and no more. Once I add the first item, it stays there as it is. Then I add the 2nd item. However, when I add the 3rd item, the 2nd item is overwritten by the 3rd one, still keeping only 2 products in the cart. I feel it would be a simple logic error but I can't seem to figure it out. My views.py... def shop(request): if not request.session.get('order1'): request.session['order1'] = [] if request.method == "POST": quantity = int(request.POST.get('quantity')) name = request.POST.get('name') if quantity >= 1: request.session.get('order1').append({"quantity":quantity, "name":name}) context = { "check":request.session.get('order1'), } else: messages.warning(request, "You have entered an invalid quantity") context={} else: context={} return render(request, "store/shop.html", context) And the output of the context = {"check":request.session.get('order1')} is something like this [{'quantity': 1, 'name': 'Tissot Watch for men - black star striped'}, {'quantity': 2, 'name': 'Jewelry Bangles Stripes for Girls'}] and always stays with only 2 items. Is there any error in the code that I have done? Any help would be greatly appreciated. Thanks! -
Check if user is in the group before posting
I have a project called Star Social this project you can only post if you are in group in this case i can still post even if i am not in a group and i can't see that post. What i want is when user tried to post even out of the group they will receive an error and redirect them to group page so that they can join a group and they can now post.I tried to search on google but i get no result and btw i am new in this field and i am currently learning django. models.py ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( 'posts:single', kwargs={ 'username': self.user.username, 'pk': self.pk } ) class Meta: ordering = ['-created_at'] views.py ######################### ## POSTS VIEWS.PY FILE ## ######################### from braces.views import SelectRelatedMixin from django.contrib.auth import get_user_model … -
Why heroku is keep saying to me "No web processes running?"
I'm trying to deploy my django project at heroku, but it keep saying the error like below. According to that error, I did heroku logs --tail, and the error was like this. 2020-12-28T03:44:38.472162+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=nbnb-clone.herokuapp.com request_id=1e862587-ebc8-4dbb-85be- 12487ff9ae16 fwd="1.250.241.55" dyno= connect= service= status=503 bytes= protocol=https I've tried heroku ps:scale web=1, and the return was like below. Scaling dynos... ! ! Couldn't find that process type (web). Currently I'm using github as my deployment method in heroku. I've tried heroku buildpacks:clear and heroku buildpacks:add heroku/python, but it didn't work for me. Also I've tried git git push heroku main, return was like below. error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/nbnb-clone.git' My Procfile is like this web: gunicorn config.wsgi --log-file - My requirements.txt certifi==2020.12.5 chardet==4.0.0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' django-countries==7.0 django-dotenv==1.4.2 django-seed==0.2.2 django==2.2.5 faker==5.0.2 ; python_version >= '3.6' idna==2.10 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' pillow==8.0.1 python-dateutil==2.8.1 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' pytz==2020.5 requests==2.25.1 six==1.15.0 ; python_version >= '2.7' and python_version not in '3.0, … -
Searching and Sorting in Jquery DataTable for my Django app, PostgreSQL DB is not working
I am using Jquery DataTable and in my Django app where I am getting data from the PostgreSQL DB. I am able to get the data into the table but I cannot get the table to sort and search. datatables.js: // Call the dataTables jQuery plugin $(document).ready(function() { $('#dataTable').DataTable(); }); index.html: <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Testing Type</th> <th>Question</th> <th>Difficulty Level</th> </tr> </thead> {% for qiq in qa_interview_questions %} <tbody> <tr> <td>{{ qiq.testingtype }}</td> <td>{{ qiq.question }}</td> <td>{{ qiq.difficultylevel }}</td> </tr> </tbody> {% endfor %} </table> </div> </div> Somehow the Search and Sorting in the DataTable does not work at all. It works if I hardcore the data. What am I doing wrong here? -
NoReverseMatch: Urlpatterns path name for route with int:pk
I am trying to create a dashboard with multiple customers rendered in the template, and a link to their individual profile. I was wondering if there is a way to pass in the url name and object pk id using django url in my template. This is my code so far and I am getting a NoReverseMatch error. urlpatterns = [ path('', views.index, name='home'), path('dashboard/', views.dashboard, name='dashboard'), path('about/', views.about, name='about'), path('product/', views.product, name='product'), path('customer/<int:pk>', views.customer, name='customer'), ] <th><a href="{% url 'customer' %}">{{ customer.first_name }} {{ customer.last_name }}</a></th> I understand that this is wrong but I cannot find the right way to do it. I am relatively new to django programming. -
Unable to figure out the cause of a Django KeyError
I am trying to make an eCommerce site and I am using Django sessions to store items in the cart, initially, it was all working perfectly fine until I decided to do something stupid and changed the session token in the inspection in chrome. And from then onwards I am thrown with a KeyError. Django Version: 3.0.8 Exception Type: KeyError Exception Value: 'order1' I then ran the following code in my terminal... from django.contrib.sessions.models import Session Session.objects.all().delete() That cleared out my table but still didn't seem to sort out this error. I even tried to host it in Heroku and access the website from a different device and a still thrown with this error. Is there anything I can do about this? And just in case here is my views.py... def shop(request): if not request.session['order1']: request.session['order1'] = [] if request.method == "POST": quantity = int(request.POST.get('quantity')) name = request.POST.get('name') if quantity >= 1: new_order = {"quantity":quantity, "name":name} request.session['order1'].append(new_order) # request.session['order'] = order context = { "check":request.session['order1'], } else: messages.warning(request, "You have entered an invalid quantity") context={} else: context={} return render(request, "store/shop.html", context) Any help would be greatly appreciated. Thanks! -
Automatically join the user who created the group
I have a project called social clone project in this project you can only post if you are in a group. What i want to happen is if the user created a group the user should automatically in the group, in this case if i created a group i still need to join the group to join my own group. I tried to search this on google but i get no result and i hope someone will help me and btw i'm just new here in programming and i'm currently learning django. models.py ########################## ## GROUPS VIEWS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django import template from django.db import models from django.utils.text import slugify from misaka import html from django.urls import reverse User = get_user_model() register = template.Library() class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default="") description_html = models.TextField(editable=False, blank=True, default="") members = models.ManyToManyField(User, through='GroupMember') def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('groups:single', kwargs={'slug': self.slug}) class Meta: ordering = ['name'] class GroupMember(models.Model): user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = … -
How to shrink flexbox when downsizing image
I am using flexbox to center items on a page and also to center items within a row. I have to handle potentially large images within the row, so I am using max-width=40% to downsize the image. However, when I do this the flexbox for the applicable row does not shrink to fit the new image size, but retains the size as if the image is still max-width=100%. How can I make the flexbox row smaller to account for the 40% max width property? Here current html code: <div style="display: flex; flex-direction: column; align-items: center;> <label>This is my header.</label> <div style="display: flex; flex-direction: row; align-items: center; border: 1px solid black;"> <img style="max-width: 40%; padding: 5%;" src="path_to_my_image" alt="(!)"/> <div style="border: 1px solid black"> <label>Here is my label</label><br> <label>Here is another label</label> </div> </div> </div> This is an image of what the current display looks like with a border around the flexbox row: Here is what it looks like without setting max-width (bottom cropped to fit): -
Ajax post requests seem to not work for some users?
I've been testing my site by having friends try it, and some friends have an issue where some of my javascript functions don't work, and some functions do. After figuring out it's not their browsers or devices, I noticed the functions that weren't working for them were the ones with Ajax post requests, so I think that's the issue here. Does anyone know why Ajax post requests work for only some users? Also, FYI, I'm using Django as a framework. Example of one of my functions using ajax: $('#button').click(function(){ $.ajax({ url: '/get_url/', type: "POST", data: { data_name: data_to_send }, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function (data) { //change some html text using data }, error: function (error) { console.log(error); } }); }); -
How to capture selected values, in Django, from two separate select fields and pass it to the view upon form submission?
I am trying to create a filtered list from model class "Animal" based off of two separate select field drop down values. If user selects "baby" and "dog" then a list of puppies would be generated from the Animal model. I cannot seem to figure out how to capture the value pks for both the "age_group" and "type" fields so that I can use them to filter the queryset. Any suggestions or guidance is appreciated. I am very new to Django. models.py class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) type = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True) ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True) age = models.PositiveIntegerField(blank=False, null=False) sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA') breedGroup = models.ManyToManyField(BreedGroup, blank=False) breed = models.ManyToManyField(Breed, blank=False) tagLine = models.CharField(max_length=300, blank=False, null=False) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') forms.py class AnimalSearchForm(ModelForm): chooseType = ModelChoiceField(queryset=Animal.objects.values_list('type', flat=True).distinct(),empty_label=None) chooseAge = ModelChoiceField(queryset=Animal.objects.values_list('ageGroup', flat=True).distinct(), empty_label=None) class Meta: model = Animal exclude = '__all__' views.py class VisitorSearchView(View): def get(self, request): animalList = AnimalSearchForm(self.request.GET) context = {'animal_list': animalList} return render(request, "animals/landing.html", context) templates {% extends 'base.html' %} {% block content %} <h1>Animal Search</h1> <form class="form-inline" action="." method="POST"> {% … -
POST 500 error django react site, POST /api/create-room
I have created a component for a Django React Rest Framework site and I keep getting an error when I click on the Create Room button on my site. The error seems to be located at the fetch portion of the component for the CreateRoom.js file I created. Any help in identifying the issue is much appreciated. Here is the error and the code that seems to be triggering the error. Please take a look at what I've got and let me know if I can provide any more information to help figure out what the issue is. Usually I try and figure it out myself but I've spent hours doing so and haven't been able to figure it out. Error: CreateRoomPage.js:67 POST http://localhost:8000/api/create-room 500 (Internal Server Error) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 Yb @ react-dom.production.min.js:53 Ze @ react-dom.production.min.js:100 se @ react-dom.production.min.js:101 eval @ react-dom.production.min.js:113 Jb @ react-dom.production.min.js:292 Nb @ react-dom.production.min.js:50 jd @ react-dom.production.min.js:105 yc @ react-dom.production.min.js:75 hd @ react-dom.production.min.js:74 exports.unstable_runWithPriority @ scheduler.production.min.js:18 gg @ react-dom.production.min.js:122 Hb @ react-dom.production.min.js:292 gd @ react-dom.production.min.js:73 create:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 … -
My images is lost it, after to send from reactjs, in my backend django
I have problem with send images from reactjs to django, before to send images, my images is present, but after the send that images to django, lost it, why?, please help me, my code is bellow. file send images import React from 'react' import {userForm} from 'react-hook-form' import {MyClass} from '../../somewhere' type uploadType = { imagen_main: any more_data: string } const SendImages:React.FC = () =>{ const [showImg, SetShowImg] = React.useState() let SendData = new Myclass() const {register, handleSubmit, errors} = userForm<uploadType>({ mode: 'onChange' }) const onSubmit = handleSubmit({imagen_main, more_data}) => { let send_data = { imagen_main: imagen_main[0], // HERE I TRY REMOVE [0], BUT NOT WORKING more_data: more_data } // HERE SHOW ME MY IMAGES BEFORE THE SEND AND MY ANOTHER DATA console.info(send_data) SendData.saveData().then(resp => { console.info(resp.data) }).catch(err => { console.error(err) // ALWAYS IN HERE }) } // THIS FUNCTION IS LIKE A PREVIEW THE IMAGES const onChange = (event: React.ChangeEvent<HTMLInputElement>) => { let file: any = event.currentTarget.files let reader = new FileReader() reader.onloadeend = () => { SetShowImg(reader.result) } reader.readAsDataURL(file[0]) } return( <form onSubmit={onSubmit} encType="multipart/form-data"> <input type='file' name="imagen_main" ref={register({required: true})} accept="image/png, image/jpeg" onChange={_onChange} /> {/* A PREVIEW IMAGES */} <img src={showImg ? showImg: '' } /> <input type="text" name="more_data" … -
How to create model/view/serializer with multiple rows in django?
I am a newbie in django and am trying to create a social media type app. So, I have created this models: Post (to create a post) Comment (to comment on post) And so far I have views like /api/post /api/post/1 (to fetch post with id 1) /api/post/1/comment (to comment on post) /api/post/1/comment/1 (to fetch comment with id 1 on post 1) Now, I am trying to make an API /api/feed (that gives the home feed of posts for a given user) (and also, a user unable to see other user feed.. i.e. they can only see their feed) I am at lost of how to define a model, serializer and view here. Basically, what I want to send to user is something like this [ { 'id': 'some unique id', 'user' :foo, 'post_id': some_post_id}, {'id': 'some unique id','user' :bar, 'post_id': some_post_id}, {'id': 'some unique id','user' :baz, 'post_id': some_post_id}, {'id': 'some unique id','user' :foobar, 'post_id': some_post_id} ] What I don't particularly understand is how to generate same unique id for all the posts in the feed.. Also, bonus points on how to implement infinite scroll? -
Is there a way to generate an "infinite" amount of charts using chart.js in Django?
I am relatively new to Django and HTML. I need to display many charts on one page in Django. I know that I need to give each of these charts a different id value in the tag, but haven't been able to. Here's what I'm working with. <script>var count = 0;</script> <ul> forloop open here of the different elements on the page <li> <script> count = count + 1; ... eval('var chart_id = "myChart' + count + '"'); eval('var ctx' + count + ' = document.getElementById(chart_id)'); eval('var myChart = new Chart(ctx' + count + ', graph_data)');` </script> <canvas id= myChart1 width="400" height="400"></canvas> </li> for loop close here I haven't been able to pass in variables to the id of the tag or find an equivalent to the eval() function that could work in HTML. The real maximum number of charts I could need is roughly 100, but I am trying to treat it as if it's an infinite number. Worst case, I could use brute force and make 100 if statements that say if the count is a certain number, display the corresponding chart, but I am trying to find a cleaner solution. If there isn't a way to do … -
Passing bunch of data/list in Django ajax
I'm having a trouble to filter all data in my looping. In the first place in my views.py I tried to print my for loop and it works fine and it filter the list under paid_by. The problem is when I pass the data to my ajax it only returns one data, and I think it should be done by using looping, how can I implement it?.Is there any way or idea that can solve this problem? Thanks in advance for p in Person.objects.raw('SELECT id, paid_by, IF(paid = "Yes" || paid = "YES", "paid", "unpaid") as id,paid, category, category_status, count(paid) FROM app_person WHERE paid_by != "" GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid'): print(p.paid_by) # I tried to print it works fine it filter the list under paid_by list_sample= p.paid_by totals = {'list_report':list_sample} return JsonResponse(totals) ajax success: function(response){ console.log(response.list_report) # When I tried to view my console it retrieve only one data instead bunch of data $("#rports").modal('show'); $("#rports").val(null).trigger("change"); } -
How to use post and get with django and react
I would like to know how can I recieve data from React and using Django what I'm trying to do right know is to send coordinates from react to django but I don't know what I should do. There are some things I don¿t understand like how I'm suposed to connect both parts? do they have to be in the same folder first? I'm asking because I deployed my app on heroku but only the backend side -
Django Error - NoReverseMatch at /listings/1. Reverse for 'addcomment' with arguments '('',)' not found. (Creating a comment section)
I'm new to Django and I think I'm having issues setting up a dynamic url. I'm creating a way to add comments to a page, called a listing. The listing page loaded fine before I added anything about comments. When I try to go to that particular listing, I get the error: "NoReverseMatch at /listings/1. Reverse for 'addcomment' with arguments '('',)' not found. 1 pattern(s) tried: ['addcomment/(?P[0-9]+)$']" Any help is appreciated because even after looking at the documentation I am having trouble understanding how dynamic urls work/how to create them. I think my html page might also have problems, in terms of pulling in the correct info with the url etc. views.py urls.py models.py html for the listing page -
Dealing with nested serializer validation in Django Rest Framework
What would be a good way to handle creating an object that has a ManyToMany field? class PersonSerializerForScene(serializers.ModelSerializer): class Meta: model = Person fields = ['id', 'name'] class MovieSerializer(serializers.ModelSerializer): people = PersonSerializerForScene(many=True) class Meta: model = Scene fields = ['id', 'title', 'description', 'people', 'pub_date'] I thought of posting data to the people field in a list of ids format, for example [ 198, 87, 52 ] iterate over these values in the create method of the MovieSerializer filter people with the submitted ids and add them to the newly created object, but this approach doesn't seem to work since the nested serializer expects an array of dictionaries. -
How do I structure YAML data for a many-to-many field (Python 3.9, Django 3)?
I'm using Python 3.9 and Django 3.0. I have defined the following models. The second has a many-to-many relationship with the first ... class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: # Creates a new unique constraint with the `name` field constraints = [models.UniqueConstraint(fields=['name'], name='coop_type_unq')] ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() For the child entity, I have defined this "get_by_natural_key" method (the name field) ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] How do I structure my YAML so that I can create a Coop with multiple types? This YAML works fine when there is only one type pk: 243 fields: name: "Dill Pickle Food Co-op" types: - ['food coop'] but when I try and add more than one type, like so ... pk: 243 fields: name: "Dill Pickle Food Co-op" types: - ['store', 'food coop'] I get this error ... django.core.serializers.base.DeserializationError: Problem installing fixture '/tmp/seed_data.yaml': get_by_natural_key() takes 2 positional arguments but 3 were given: (directory.coop:pk=243) field_value was '['store', 'food coop']' -
Django ou PHP WordPress [closed]
Boa Noite Pessoal, tudo bem? Tenho a seguinte dúvida estou estudando desenvolvimento web e de início já estou aprendendo a fazer alguns sites e gostaria de fazer a parte administrativa, é aí que entra minha dúvida a hospedagem em Django é do mesmo preço do q a de PHP, é melhor WordPress ou Django pra sites institucionais por exemplo? -
Access Django admin from Firebase
I have a website which has a React frontend hosted on Firebase and a Django backend which is hosted on Google Cloud Run. I have a Firebase rewrite rule which points all my API calls to the Cloud Run instance. However, I am unable to use the Django admin panel from my custom domain which points to Firebase. I have tried two different versions of rewrite rules - "rewrites": [ { "source": "/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "**", "destination": "/index.html" } ] --- AND --- "rewrites": [ { "source": "/api/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "/admin/**", "run": { "serviceId": "serviceId", "region": "europe-west1" } }, { "source": "**", "destination": "/index.html" } ] I am able to see the log in page when I go to url.com/admin/, however I am unable to go any further. Just as an FYI, it is not to do with my username and password as I have tested the admin panel and it works fine when accessing it directly using the Cloud Run url. Any help will be much appreciated. -
Re-create django migrations without migrations folder
I have a bit of an issue. I tried to re-create my sqlite db of my project. Only problem is that by uploading my project on a git, I ignore the "migrations" folder of each app so my client wouldn't be bothered by it (wrong practice?). But today, I would like to take that db from scratch (column order, recreate full install from csv data, ...) but when i execute my migrations commands, they detect no changes and only migrate django table. Django version : 2.0.13 Python : 3.7.3 -
Passing data through from form submission depending on value
I am trying to pass data through from a form depending on different calculations from the form submission Model class Price(models.Model): name = models.CharField(max_length=100) contract = models.CharField(max_length=5, choices=year_choice) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime(2021,3,31)) epoch_year = date.today().year year_start = date(epoch_year, 1, 4) year_end = date(epoch_year, 3 , 31) def __str__(self): return self.name @property def pricing(self): price_days = self.start_date - self.year_end return price_days Views def price_detail(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = PriceForm(request.POST) # check whether it's valid: if form.is_valid(): form.save() return render(request,'confirmation.html',{'form_data': form.cleaned_data}) else: form = PriceForm() return render(request, 'main.html', {'form': form}) So the idea is to change show details on the confirmation.html page depending on the contract type and start date, a basic but most like incorrect example is below: def pricingcalc(request): if PriceForm.contract == 'year1' return Price.pricing * AdminData.day_rate_year1 else return Price.pricing * AdminData.day_rate_year3 To summarise: List output of values on confirmation page Output based on number of days x price depending on a one year contract or a three year contract. Hope this makes sense. Thanks for the help.