Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to manually define place for blog post preview using Django and CKEditor?
I have a blog written in Python + Django. Before I started use of WYSIWYG editor, to create a blog post preview I manually added custom html tag <post_cut/> and used python slice to show only a preview. It allowed to avoid issues with fixed length for preview or breaking html tags. Now I added Django-CKEditor and it removes all html tags which "it doesn't understand". I tried to do something with configuration (allowedContentRules, format_tags and etc.) but no success. The questions is how to manage "post-cut" and how to do this using CKEditor. P.S. it would be awesome also to have button for that. -
I got incorrect calculations in save method Django
class Product(models.Model): price = models.DecimalField('Цена', decimal_places=2, max_digits=9) class Discount(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='discount') discount_price = models.DecimalField('Скидочная цена', decimal_places=2, max_digits=9, blank=True, null=True) discount_percent = models.PositiveSmallIntegerField('Процент скидки (число)', blank=True, null=True) def save(self, *args, **kwargs): if not self.discount_percent and not self.discount_price: raise ValueError('Заполните хотя бы одно поле: процент или скидочная цена') if not self.discount_percent: self.discount_percent = (self.discount_price // self.product.price) * 100 elif not self.discount_price: self.discount_price = (self.product.price * self.discount_percent) // 100 super().save(*args, **kwargs) When I write in admin panel discount_percent without discount_price calculation will be correct. I get really a discount price. But when I write discount_price without discount_percent, Discount_percent always has a value of 0 When I added a lot of prints, all input data were correct but calculations not. How i can solve it? -
how to auto import python function in vscode
As in PyCharm if we forgot to import function define in python code. Pycharm get suggest us and import it automatically, on just click the undefined function. So there is any such feature / extension for VS Code for auto import function as PyCharm.??? -
Will using sqlite '3' for building a website with a chat section make any problem? [closed]
I'm building a website for the university this website will contain an open chat section it means without having to register the maximum number of users at one time won't be higher than 400 people will sqlite make any problems ? If yes what do you suggest ? -
How can I use Django variables in my javascript/client-logic?
I am trying to serialize a queryset to use it in javascript to populate a chart. The problem is that it don't let me serialize the object. If I removre queryset it works, but I need the queryset in the context to use it for Django rendering as well. So how may I use the variables both with Django to render the html divs and javascript to render a chart? (in this case it is a canvas why I need the variables on the javascript site). views.py where currency and dynascore are two custom variables and queryset is the Django model query [...] context = { 'queryset': queryset, 'currency': currency, 'dynascore': dynascore, } # Prepare context for javascript json_context = json.dumps(context) context['json_context'] = json_context print(queryset) return render(request, template, context) // Throws: // Object of type StocksPrice is not JSON serializable Javascript console.log(json_context) // Throws: // Uncaught ReferenceError: json_context is not defined at terminal.js:1 So as far as I understood the one and only "bridge" between Django retrieved data and javascript/client-side is JSON? -
I want to add the language code to path so it could be /language_code
I am developing a multi-language website and I managed through internationalization to make the locale files and translating the web pages but my problem is that I want to add the language code to the path. <form action="{% url 'home' %}" method="post" id="languageForm">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language" id="selectLanguage" onchange="this.form.submit()" style="height: 500px;"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <!-- <input type="submit" value="Go">--> </form> I am using this select to choose the languages available and my path pattern is as follow: `path('home', views.home, name='home'),` so some home I want it to be 'home/en' for example so how can I do so? -
Set a field value within form __init__ function
I am trying to find out an efficient way to set a field value within form init method. My models are similar to below class Users(models.Model): firstname = models.CharField() lastname = models.CharField() class profile(models.model): user = models.ForeignKey(Users, on_delete=models.PROTECT) class logindetails(models.model): user = models.ForeignKey(Users, on_delete=models.PROTECT) profile = models.ForeignKey(profile, on_delete=models.PROTECT) login_time = models.DateField(auto_now=True) My form is like as below: class LoginForm(forms.ModelForm): class Meta: model = logindetails fields = [__all__] def __init__(self, *args, **kwargs): self._rowid = kwargs.pop('rowid', None) super(LoginForm, self).__init__(*args, **kwargs) instance = profile.objects.get(id=self._rowid) self.fields['user'] = instance.user <--- Facing difficulties here Any help will be appreciated. -
The best choice for Django and MongoDB integration
I'm creating a Django app from scratch and would like to use MongoDB with it. I've found that there are two popular solutions for integration MongoDB with Django: Djongo MongoEngine I didn't find a lot of info about that. Only: If you already have your models and want to convert them to a MongoDB document, I can’t recommend using Djongo enough. However, if you want to make your models from scratch and want to use MongoDB ObjectID as your models’ id, you could try using Mongoengine. https://medium.com/@9cv9official/django-to-mongodb-djongo-or-mongoengine-d9d56b836a3d The questions: What's the best solution for that? What are pros and cons for each options? -
Add username or any user authentication related field like first name, last name etc in model forms
I am creating a project in django in which I have two diff users i.e. Customers and restaurants. I am creating a model for Menu in which I want add to add restaurant name in models directly(user name in this case) instead of taking input thorough forms every time.Also if possible if can take name from another field like this which is part of login system? Models.py class menu_details(models.Model): restaurant_name = models.CharField(blank=True, max_length=20) dish_name = models.CharField(blank=True, max_length=20) dish_type = models.CharField(max_length=10, choices=food_type, default='veg') price = models.CharField(blank=True, max_length=20) description = models.TextField(blank=True, max_length=5000) image = models.ImageField0(blank=True) class Meta: db_table = "menu_details" -
I cant open a django project
Long time ago i started learning django and as my first project was Poll app from the tutorial. Now, im returning to django, but I cant open the project in my IDE. Why? -
CustomerUserModel and manytomanyfeilds
I currently have a Custom User below which has a one to one model with a model called customer. class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) … -
Why do I get a MultiValueDictKeyError everytime I try to get the data from a POST request?
I'm currently learning in Django, and in this fetch request, I always get the same error. How could I avoid it? topup.html let data = new FormData(); data.append('amount', document.getElementById('amount').value); data.append('csrfmiddlewaretoken', "{{ csrf_token }}"); var response = fetch('{% url "secret" %}', { method: 'POST', body: data, credentials: 'same-origin', }) views.py def secret(request): amount = request.POST["amount"] error: MultiValueDictKeyError at /secret 'amount' Request Method: GET Request URL: http://127.0.0.1:8000/secret Django Version: 3.0.6 Exception Type: MultiValueDictKeyError Exception Value: 'amount' Exception Location: C:\Users\eric3\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\datastructures.py in getitem, line 78 Python Executable: C:\Users\eric3\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Django Error I would really appreciate some help. Thanks! -
Django view for link table
I have three tables in my model: class Recipe(models.Model): title = models.CharField(max_length=200) excerpt = models.TextField(null=True) category = models.CharField(max_length=10, default='FoodGroup') cookTime = models.CharField(max_length=20, default='15Min') prepTime = models.CharField(max_length=20, default='5Min') process = models.TextField(null=True) slug = models.SlugField(max_length=100, unique=True) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('recipe:single', args=[self.slug]) class Meta: ordering = ['-published'] def __str__(self): return self.title class Ingredient(models.Model): IngName = models.CharField(max_length=30) IngType = models.CharField(max_length=20, null=True) def __str__(self): return self.IngName class RecipeIngredients(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey(Core, on_delete=models.CASCADE) And the view looks like this: class RecipeView(ListView): model = RecipeIngredients template_name = 'core/recipes.html' context_object_name = 'recipe' I'm trying to then view this data using a for loop: {% for recipe in recipe %} {{ recipe.title }} {% endfor%} but nothing gets pulled using this method, I've tried looking at the docs but I'm unsure I'm doing this in the best way? I had a look at the many-to-many section of the Docs but I thought a link-table may be more appropriate for my scenario. -
Collectstatic failing - botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found
I'm attempting to run collectstatic on a stage deploy to AWS. I'm getting the following error, and no files are being placed in the bucket: Traceback (most recent call last): File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 523, in _open f = S3Boto3StorageFile(name, mode, self) File "/home/hcc/.local/lib/python3.6/site-packages/storages/backends/s3boto3.py", line 74, in __init__ self.obj.load() File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/factory.py", line 505, in do_action response = action(self, *args, **kwargs) File "/home/hcc/.local/lib/python3.6/site-packages/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(*args, **params) File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call return self._make_api_call(operation_name, kwargs) File "/home/hcc/.local/lib/python3.6/site-packages/botocore/client.py", line 635, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/hcc/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 161, in handle if self.is_local_storage() and self.storage.location: File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 215, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/home/hcc/.local/lib/python3.6/site-packages/django/utils/functional.py", line 224, in inner self._setup() File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 501, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 379, in __init__ self.hashed_files = self.load_manifest() File "/home/hcc/.local/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line … -
Django on Heroku doesn't call collectstatic
Based on this articles https://devcenter.heroku.com/articles/django-assets Heroku supposed to call python manage.py collectstatic after I configure settings with this django_heroku https://devcenter.heroku.com/articles/django-app-configuration my config vars: DEBUG_COLLECTSTATIC: 1 DISABLE_COLLECTSTATIC: 0 my buildpack: heroku/python I put this code on the last line of my settings.py import django_heroku # Activate Django-Heroku. django_heroku.settings(locals()) and my folder looks like this apps |---apps |---settings |---base.py |---settings.py This is my build log -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.7 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Found python-3.7.7, removing -----> No change in requirements detected, installing from cache -----> Installing python-3.7.6 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.2.7 Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.0.6 Downloading Django-3.0.6-py3-none-any.whl (7.5 MB) Collecting django-heroku==0.3.1 Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) Collecting gunicorn==20.0.4 Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) Collecting psycopg2==2.7.5 Downloading psycopg2-2.7.5-cp37-cp37m-manylinux1_x86_64.whl (2.7 MB) Collecting psycopg2-binary==2.8.5 Downloading psycopg2_binary-2.8.5-cp37-cp37m-manylinux1_x86_64.whl (2.9 MB) Collecting pytz==2020.1 Downloading pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse==0.3.1 Downloading sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Collecting whitenoise==5.1.0 Downloading whitenoise-5.1.0-py2.py3-none-any.whl (19 kB) Installing collected packages: asgiref, dj-database-url, sqlparse, pytz, Django, whitenoise, psycopg2, django-heroku, gunicorn, psycopg2-binary Successfully installed Django-3.0.6 asgiref-3.2.7 dj-database-url-0.5.0 django-heroku-0.3.1 gunicorn-20.0.4 psycopg2-2.7.5 psycopg2-binary-2.8.5 pytz-2020.1 sqlparse-0.3.1 whitenoise-5.1.0 -----> Discovering process types Procfile declares … -
Django: Follower List not showing properly in User profile
I have this follower system, I have this follower list and its working fine in our own profile. but if we visit another profile, there its showing our follower list instead of their followers. Can someone help me find the error in the code.? views class FollowerList(ListView): model=Contact template_name = 'accounts/follower_list.html' def get_context_data(self, **kwargs): context = super(FollowerList, self).get_context_data(**kwargs) context['followers'] = Contact.objects.filter(user_to__isnull=False, user_to__username__iexact=self.kwargs.get('username')) return context model class Contact(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) follow_status = models.CharField(choices=FOLLOW_STATUS, max_length=10) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False) #adding the above field to User Model class user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) html {% if not user.followers %} <h6 style="text-align: center;"> No Followers Yet!</h6> <p style="text-align: center;"> Start Posting Now! </p> {% endif %} {% for follow in user.followers.all %} <h5 style="text-align: center;">Followers </h5> <div class="offset-md-3 mt-2"> <a href="{% url 'posts:userprofile' follow.username %}"><h6> {{ follow.username }}</h6></a> </div> {% endfor %} Thanks guys -
Can you have a one-to-one relational database together with a one-to-many relational database in Django as part of the same model?
If that's not possible, how do I include both relational databases in the same Django website? I find a lot of info on linking the two admins of the two apps, but nothing on linking the two apps. I was thinking of putting the one database (one-to-one database) as part of an App, and the other (one-to-many) relational database as part of another App. Would that be possible? I have tried to link two apps together (but failed miserably). -
Django + Vue.js can't display images from database
I am trying to make a simple website that displays a list of fundraisers from a database with a picture for each fundraiser. However, I can't figure out why the images aren't appearing. My fundraiser model is as follows: class Fundraiser(models.Model): fundraiserImage = models.ImageField(upload_to='images/', blank=True) I tried to display each fundraiser in the database as shown in the vue file below. template> <div> <div> <ul> <li v-for="f of fundraisers" v-bind:key="f.id"> <img src="f.fundraiser.fundraiserImage.url" width="500"> </li> </ul> {{fundraisers}} </div> </div> </template> <script> import axios from 'axios' export default { name: 'Fundraiser', data () { return { fundraisers: [] } }, mounted: function () { this.getFundraisers() }, methods: { getFundraisers: function () { // var app = this; axios.get('/api/fundraisers/?format=json') .then(response => (this.fundraisers = response.data)) } } } </script> <style> </style> Here's a snippet of the relevant code from my settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/dist/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mellon/media') and here's a snippet of the relevant code from my urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to produce Kafka Events in Django the right way
I am using django for a project and want to trigger a Kafka event on some request. I know how to produce a kafka event in a view. class TestList(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated] queryset = Test.objects.all() serializer_class = TestSerializer def post(self, request, *args, **kwargs): serializer = TestSerializer(data=request.data) if serializer.is_valid(): serializer.save() producer = KafkaProducer(bootstrap_servers=[f'{settings.SECRETS.kafka.host}:{settings.SECRETS.kafka.port}'], value_serializer=lambda m: json.dumps(m).encode('ascii')) kafka_msg = { 'msg': { 'hello': 'world', }, } producer.send('test', key=serializer.instance.id.bytes, value=kafka_msg) \ .add_callback(on_send_success).add_errback(on_send_error) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) However, I am not sure if this is optimal to create the KafkaProducer every time in the request. Is there a way to create the producer on startup with a persistent connection and how or would it make no difference? -
Issues in uploading image from user without django ModelForm
I am trying to create a form without using ModelForm. I using the input elements in HTML for the purpose (to upload name and image). But I am having trouble uploading images with this process. The name is getting saved but not the image. My code: models.py class Register(models.Model): name = models.CharField(max_length=50, null=True) idCard = models.FileField(upload_to='idCard', null=True) views.py def index(request): if request.method == 'POST': data.name = request.POST.get('name') data.idCard = request.POST.get('idCard') data.save() return redirect('/') return render(request, 'event/index.html') index.html <form class="mform" id="myform" method="POST" id="myform" action="" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend>Registeration</legend> <table cellspacing="0"><tbody> <tr><td> <label for="u_name"> Username :</label></td><td> <input type="text" name="name" id="u_name"> <td> </tr> <tr><td> <label for="u_img"> IDCard :</label></td><td> <input type='file' accept='image/*' onchange='openFile(event)' name="idCard" id="u_img"> </td></tr> The name is getting saved but not the image. -
django populate model field from another model without ForeignKey
I'm working in App using exiting multiple databases (I can't modify them). I connect to all of them and can do queries and serializers without problem, but I want to populate a field form a Model into another Model where they have the same value: class Cuisines(models.Model): name = models.CharField(max_length=255) company_id = models.PositiveIntegerField() ... class Meta: managed = False db_table = 'cuisines' in_db = 'db_2' class Companies(models.Model): company_name = models.CharField(max_length=255) location = models.CharField(max_length=255, blank=True, null=True) .... class Meta: managed = False db_table = 'cuisines' in_db = 'db_1' ... view: def cuisines(request): companies = Companies.objects.all() for company in companies: result = Cuisines.objects.filter(company_id = company.id ) serializer = OrderSerializer(result, many=True) return JSONResponse(serializer.data) the result looks: [{"id":1,"name":"Burger",company_id:"1" ...] and I'm looking for: [{"id":1,"name":"Burger","company_id":"some name", }...] -
javascript link is missing from URL. circle-artifacts.com/0/dist/plotly.js
I have been using a plotly diagram in my django project as a reference from this link below: <head> <script src="https://52345-45646037-gh.circle-artifacts.com/0/dist/plotly.js"></script> </head> However, for some reason this link shows 'Artifact not found'. Any idea how I can have the original code (the plotly.js) so I can integrate it with my project and avoid the reference? -
Django: DRF custom password change view and serializer not working
I have defined a serializer class and a view class to perform password change. As usual, user needs to enter old password, then the new password for two times to confirm. I am using AbstractBaseUser to implement a custom user. I defined the old_password_validator and new_password_validator with suggestions from this thread, though I don't know how to make it work. I am using djangorestframework_simplejwt for all sorts of authentication. My serializer class: class ChangePasswordSerializer(serializers.ModelSerializer): old_password = serializers.CharField(required=True, write_only=True) new_password = serializers.CharField(required=True, write_only=True) re_new_password = serializers.CharField(required=True, write_only=True) def update(self, instance, validated_data): instance.password = validated_data.get('password', instance.password) if not validated_data['new_password']: raise serializers.ValidationError({'new_password': 'not found'}) if not validated_data['old_password']: raise serializers.ValidationError({'old_password': 'not found'}) if not instance.check_password(validated_data['old_password']): raise serializers.ValidationError({'old_password': 'wrong password'}) if validated_data['new_password'] != validated_data['re_new_password']: raise serializers.ValidationError({'passwords': 'passwords do not match'}) if validated_data['new_password'] == validated_data['re_new_password'] and instance.check_password(validated_data['old_password']): instance.set_password(validated_data['new_password']) instance.save() return instance class Meta: model = User fields = ['old_password', 'new_password','re_new_password'] I defined my view class like this: class ChangePasswordView(generics.UpdateAPIView): permission_classes = (permissions.IsAuthenticated,) def update(self, request, *args, **kwargs): serializer = ChangePasswordSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I entered the values, headers and ran in postman I got this error: Got a TypeError when calling User.objects.create(). This may be because you have a … -
how i can fix the errors of migrate command
i'm new in django i want to create a businessplan application i create 3 classes in my models file "models.py" when i run python manage.py migrates it show me this errors: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\hp\PycharmProjects\business\lib\site- packages\django\core\management\commands\migrate.py", line 89, in handle executor.loader.check_consistent_history(connection) File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\db\migrations\loader.py", line 295, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency businessplan.0001_initial on database 'de fault'. this is my models.py : it contain 4 classes Entrepreneur ,Admin , User(abstract) and projet: from django.db import models from django.contrib.auth.models import * #user class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"staff")) user_type=models.CharField(default=1,choices=user_type,max_length=10) # Entrepreneur class Entrepreneur(models.Model): id_models= models.IntegerField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) nom_et_prenom=models.CharField(max_length=50) date_naissance=models.DateField() adresse_entr=models.CharField(max_length=20) telephone=models.IntegerField() statut_social=(('ce','celébataire'), ('ma','marié'), ('di','divorcé'), ('ve','veuf'), ) occupation=models.CharField(max_length=50) niveau_scolaire=( ('pri','primaire'), ('sec','secondaire'), ('cap','certificat aptitude professionel'), ('btp','brevet technicien professionel'), ('bts','brevet technicien superieur'), ('lic','license'), ('mai','maitrise'), ('mas','mastere'), ('doc','doctorat'), ) niveau_scolaire=models.CharField(default='ser',choices=niveau_scolaire,max_length=50) annnee_exp=models.IntegerField() email=models.CharField(max_length=255) password=models.CharField(max_length=255) #Projet class Projet(models.Model): id_models=models.IntegerField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) nom_projet=models.CharField(max_length=30) lieu_implantation=models.CharField(max_length=20) type_projet=( ('ser','service'), ('com','commerce'), … -
How to use django-multiselect field in postman?
I am using pip module MultiSelectField Here is my model SALES_CHANNEL = [ ('retailer', 'Retailer'), ('wholesaler', 'Wholesaler'), ('consumer', 'Consumer'), ('distributor', 'Distributor'), ('online', 'Online') ] class ProductModel(basemodel.BaseModel): name = models.CharField(max_length=200) mrp = models.DecimalField( max_digits=10, decimal_places=2, null=True, blank=True ) selling_price = models.DecimalField( max_digits=10, decimal_places=2, null=True, blank=True ) upc = models.CharField(max_length=30, null=True, blank=True) dimensions = models.CharField(max_length=200, null=True, blank=True) weight = models.CharField(max_length=200, null=True, blank=True) sku = models.CharField(max_length=200, unique=True) product_type = models.CharField( max_length=30, choices=PRODUCT_TYPE, default='goods' ) sales_channel = MultiSelectField( choices=SALES_CHANNEL, null=True, blank=True ) While creating a product with postman, my request body is: { "name": "first unit", "sku": "first sales chann", "sales_channel":["retailer", "wholesaler"] } But on serializer.is_valid(), I get this error: "sales_channel": [ "\"['retailer', 'wholesaler']\" is not a valid choice." ], How can I post data on postman for multiselectfield?