Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom QuerySet returns empty
I want to create a custom QuerySet where it contains filters with model instances being filtered by date durations. Upon attempting to test DateRangeQuerySet.week_long(), no models are being returned. Upon debugging, a TypeError is being raised in Django's BaseManager class: TypeError: isinstance() arg 2 must be a type or tuple of types. https://github.com/django/django/blob/e4430f22c8e3d29ce5d9d0263fba57121938d06d/django/db/models/manager.py#L81 What is causing this TypeError to be raised and why is this causing an empty QuerySet to be returned? class TestQuestionDateRangeQuerySet(TestCase): '''Verify that each queryset method filters all questions in the database by a prescribed date time delta''' @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="tag1") user = User.objects.create_user("User") user_account = UserAccount.objects.create(user=user) for q in mock_questions_submitted: q.update({'user_account': user_account}) question = Question.objects.create(**q) question.tags.add(tag1) q1, q2, q3, q4 = Question.objects.all() def test_questions_posted_week_ago(self): with patch('datetime.date') as mock_today: mock_today.today = Mock(return_value=datetime.date(2021, 3, 13)) week_old_questions = Question.dateranges.weeklong() mock_today.assert_called_once() self.assertEqual(week_old_questions.count(), 2) self.assertQuerysetEqual( week_old_questions, map(repr, [q1, q2]) ) class DateRangeQuerySet(models.QuerySet): def week_long(self): today = datetime.date.today() week_ago = today - datetime.timedelta(days=7) return self.filter(dated__range=(week_ago, today)) def month_long(self) pass class Question(models.Model): title = models.CharField(unique=True, max_length=50) body = models.TextField() dated = models.DateField(default=datetime.date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() class Meta: ordering = ['dated'] default_manager_name … -
how to ignore FileField data if its empty in django
i am new in django and tryng to learn more but cannt find solution i want to make django ignore form if form is empty and only change other txt input it is editor to edit info and when it opens it fills info automaticly and if you want u can add word or leave as it is problem is to i have to select image every time how can i make django ignore that input ? here is code forms.py picture = forms.ImageField(widget=forms.TextInput(attrs={'class':'file-input'}), required=False ), profile_info = forms.CharField(widget=forms.TextInput(attrs={'class':'textarea'}), max_length=260, required=False) class Meta: model = Profile fields = ('picture','profile_info') views.py def EditProfile(request): user = request.user.id profile = Profile.objects.get(user__id=user) BASE_WIDTH = 400 # self.objects.exclude(file__isnull=True) i am tryng to put this code but dont works? if request.method == 'POST': form = EditProfileForm(request.POST, request.FILES) if form.is_valid(): profile.picture = form.cleaned_data.get('picture') profile.profile_info = form.cleaned_data.get('profile_info') profile.save() return redirect('index') else: form = EditProfileForm() context = { 'form':form, } return render(request, 'edit_profile.html', context) please someone guide me how to fix this -
Django widget for Array of Points
I have a model with field myfield = ArrayField(geo_models.PointField(null=False, blank=False), null=False) And I can't find a way to represent it in Django Admin. I tried to use django_better_admin: from .widget import PointWidget from django_better_admin_arrayfield.admin.mixins import DynamicArrayMixin @admin.register(myModel) class MyModelAdmin(admin.ModelAdmin, DynamicArrayMixin): formfield_overrides = { DynamicArrayField: {'widget': PointWidget}, } And PoinWidget: class PointWidget(forms.MultiWidget): """ A Widget that splits Point input into latitude/longitude text inputs. """ def __init__(self, attrs=None, date_format=None, time_format=None): widgets = (forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs)) super(PointWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return tuple(value.coords) return (None, None) def value_from_datadict(self, data, files, name): mylat = data[name + '_0'] mylong = data[name + '_1'] try: point = Point(float(mylat), float(mylong)) except ValueError: return '' return point But still there's only one TextField in the form and no way to fill it -
Django makemigrations error on many to many relationship
What i want: Store information about running of group of people. What i did: from django.db import models from django.contrib.auth.models import User from datetime import timedelta class Route(models.Model): name = models.CharField(max_length=50) class Run(models.Model): date = models.DateField() type = models.ForeignKey(Route, on_delete=models.PROTECT) runners = models.ManyToManyField(User, through='RunnerResult', through_fields=["user", "run"]) class RunnerResult(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) run = models.ForeignKey('Run', on_delete=models.PROTECT) result = models.DurationField(default=timedelta()) Problem: When i do makemigrations i have the following error: SystemCheckError: System check identified some issues: ERRORS: run.Run.runners: (fields.E339) 'RunnerResult.run' is not a foreign key to 'User'. HINT: Did you mean one of the following foreign keys to 'User': user? run.Run.runners: (fields.E339) 'RunnerResult.user' is not a foreign key to 'Run'. HINT: Did you mean one of the following foreign keys to 'Run': run? Tried to swap through_fields and models between each other and some other actions. I'm starting to think of my misunderstanding of M2M relationship. -
Logging requests and responses sent from django heroku app
I'm wanting to capture all http requests made from my django app hosted on heroku. I'm wanting all of the information regarding the request that was made and the response of that request (including the body for both GETs and POSTs). I currently have sentry attached to my app and it looks like it captures all requests made when there is an error in the app (although it doesn't include the body). I'm wondering if there is an easy way to use sentry or some other heroku add on the capture all outgoing http traffic from my app. Or do I have to tap into the python logging module to achieve this? -
Spacing between bootstrap 5 cards
i already made a question like this, but people didn't give good enough answers, so I'm just going to paste the link of that post here. Please answer on that post. How to space bootstrap 5 cards? Thanks! -
Database not displayed on admin, gives template error "model" has no attribute user
So i created a new modelform that is functioning perfectly, interesting enough i receive an template error when i try to see the base model on admin. And it shows this weird line as the causer. <a href="{% url 'admin:password_change' %}">{% translate 'Change password' %}</a> / This problem is probably caused by auth_views, specially one involving password changes, so here it is my project urlpatterns code that migth help. urlpatterns = [ path('admin/', admin.site.urls), #Essas views sao relacionadas o usuario path('Cadastro/', usuarios_views.Cadastro, name= 'Cadastro'), path('Empresa/', usuarios_views.Empresa, name= 'Empresa'), path('Login/', auth_views.LoginView.as_view(template_name='usuarios/login.html'), name= 'Login'), path('Logout/', auth_views.LogoutView.as_view(template_name='usuarios/logout.html'), name= 'Logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='usuarios/password_reset.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='usuarios/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='usuarios/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='usuarios/password_reset_complete.html' ), name='password_reset_complete'), path('', include('APP_IVG.urls')), path('Dado/', include('dado.urls')), ] Any extra info just ask and i shall give it. -
Django Rest Framework UnicodeDecodeError
Model available: photo = models.ImageField(verbose_name='Фото', upload_to='images/human/%Y/%m/%d/', default='default/user.png', blank=True) photo_200 = ImageSpecField( source='photo', processors=[ResizeToFill(200, 200)], format='JPEG', options={'quality': 80}, ) photo_272 = ImageSpecField( source='photo', processors=[ResizeToFill(272, 250)], format='JPEG', options={'quality': 80}, ) serializer: class HumanListSerializer(serializers.ModelSerializer): class Meta: model = Human fields = ( 'name', 'surname', 'middle_name', 'description', 'photo_272', 'slug' ) I get an error on photo_272 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte with picture photo everything is in order, since it is not used django rest framework -
Django MEDIA_URL and MEDIA_ROOT create a new folder /static/
I'm trying to upload an image via the Django admin, but the django admins creates a new folder static/images instead of save to existing folder static/images ''' STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') ''' -
How to return values in django-import-export ManyToManyFields
I have had headache over why my import does not include the manytomany fields with it, instead it shows none upon import .Here is my resources.py class ImportStudentsResource(resources.ModelResource): klass = fields.Field(widget= ManyToManyWidget(Klass)) stream = fields.Field(widget=ManyToManyWidget(Stream)) gender__name = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name')) school__name = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) class Meta: model = Students fields = ('school__name','adm','name','kcpe','klass','stream','gender__name','notes') import_id_fields = ('adm',) import_order = ('school__name','adm','name','kcpe','klass','stream','gender__name','notes') The view class UploadStudentsView(View): context = {} def get(self,request): form = NewStudentsForm() self.context['form'] = form return render(request,'upload_student.html',self.context) def post(self, request): form = NewStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=False, raise_errors=True) print(result) if result.has_validation_errors() or result.has_errors(): print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_students') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None else: self.context['form'] = NewStudentsForm() return render(request, 'upload_student.html', self.context) The models. class Klass(models.Model): name = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(4),], help_text='E.g 1,2,3, 4') school = models.ForeignKey(School,on_delete=models.CASCADE) class Stream(models.Model): name = models.CharField(max_length=50,help_text='Name of the stream') klass = models.ForeignKey(Klass,on_delete=models.CASCADE,help_text='Choose a class the stream belongs to') school = models.ForeignKey(School,on_delete=models.CASCADE) And a sample of the files I'm trying to upload. It gives None in klass and … -
What is self.instance in django?
What self.instance means in the code below? Class ProfileForm(forms.ModelForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) interest_0 = forms.CharField(required=True) interest_1 = forms.CharField(required=True) interest_2 = forms.CharField(required=True) def save(self): Profile = self.instance Profile.first_name = self.cleaned_data[“first_name”] Profile.last_name = self.cleaned_data[“last_name”] profile.interest_set.all().delete() For i in range(3): interest = self.cleaned_data[“interest_{}”.format(i] ProfileInterest.objects.create( profile=profile, interest=interest) Here is a complete code. I already read this post, but still, I can't understand their explanation. Can you explain in the easiest way possible? -
Heroku's Django is not loading any css file
I'm practicing on django project and when I run the code in localhost everything goes well, although on heroku app deployment none of the css files are loaded even the google font. boards_app/config/settings.py INSTALLED_APPS = [ 'django.contrib.staticfiles', ] DEBUG = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] boards_app/static/css/app.css .navbar-brand { font-family: 'Train One', cursive; } boards_app/templates/base.html {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django Boards{% endblock %}</title> <link href="https://fonts.googleapis.com/css2?family=Train+One&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}">Django Boards</a> </div> </nav> <div class="container"> <ol class="breadcrumb my-4"> {% block breadcrumb %} {% endblock %} </ol> {% block content %} {% endblock %} </div> </body> </html> localhost style loading preview live style not loaded Code on github Live preview on Heroku -
Heroku how to see logs of clock process
I recently implemented a clock process in my heroku app (Python) to scrape data into a database for me every X hours. In the script, I have a line that is supposed to send me an email when the scraping begins and again when it ends. Today was the first day that it was supposed to run at 8AM UTC, and it seems to have ran perfectly fine as the data on my site has been updated. However, I didn't receive any emails from the scraper, so I was trying to find the logs for that specific dyno to see if it hinted at why the email wasn't sent. However I am unable to see anything that even shows the process ran this morning. With the below command all I see is that the dyno process is up as of my last Heroku deploy. But there is nothing that seems to suggest it ran successfully today... even though I know it did. heroku logs --tail --dyno clock yields the following output, which corresponds to the last time I deployed my app to heroku. 2021-04-10T19:25:54.411972+00:00 heroku[clock.1]: State changed from up to starting 2021-04-10T19:25:55.283661+00:00 heroku[clock.1]: Stopping all processes with SIGTERM 2021-04-10T19:25:55.402083+00:00 heroku[clock.1]: … -
I can't find the GitHub API for extract the code of a repository
I am working with GitHub API. But I don't find any API that will help me to see and extract the different version of code. Please help me. -
How to use LIKE %a% when passing a parameter in raw sql django
I have a parameter search_query and I want to get all the objects that consist search_query using only raw sql(I know that Django has built-in functions for that) Here is my code: def search(request): cursor = connection.cursor() cursor.execute("SELECT (Lastname + ' ' + Firstname + ' ' + Patronymic) as n from Person") data = dictfetchall(cursor) search_query = request.GET.get('search','') cursor.execute("SELECT (Lastname + ' ' + Firstname + ' ' + Patronymic) as n from Person WHERE Lastname LIKE %s",[search_query]) data = dictfetchall(cursor) return render(request,'other.html',{'data':data,'search_q':search_query}) Tried to do like this WHERE Lastname LIKE %%s%, but it didn't work. Couldn't find anything in the internet(( -
values methods in django
Instead of using method all(), I want to use method values() to do an optimal search within the database, and I only want to get two fields from my model. One of my fields is related to price, which is obtained by subtracting the original price from the discount. How can I access this field inside method values. The error the project gives me: Cannot resolve keyword 'total_price' into field my model : class Product(models.Model): title = models.CharField(max_length=100) unit_price = models.IntegerField() discount = models.IntegerField() total_price = models.IntegerField() @property def total_price(self): if not self.discount: return self.unit_price elif self.discount: total = (self.discount * self.unit_price) / 100 return int(self.unit_price - total) return self.total_price my view : products = Product.objects.values('name','total_price') -
my cookie-navbar combo isn't working, even though I don't get errors
I have this in my view for when someone registers for an acccount: response = redirect ("/register/success") response.set_cookie('register', 'True') return response This creates a cookie so I know they are registered. Then, I have this in my navbar: <ul> <li class="all"><a href="/">All videos</a></li> <li class="stam"><a href="/stam">Stam videos</a></li> <li class="music"><a href="/music">Music videos</a></li> <li class="news"><a href="/news">News videos</a></li> <li class="contact"><a href="/contact">Contact</a></li> {% if user.is_authenticated %} <li class="logout"><a href="/logout">Logout</a></li> {% elif request.COOKIE.register == 'True' and user.is_authenticated == 'False' %} <li class="login"><a href="/login">Login</a></li> {% else %} <li class="register"><a href="/register">Register</a></li> {% endif %} </ul> Basically, if the user is logged in shows 'logout' in the navbar (this works), if they are logged out it shows 'register', and if they are logged out and have the 'register' cookie it says 'login'. However, this last one doesn't work, and I don't know why, because I don't get any errors in relation to making a cookie when I make an account, but eveen after I make an account and logout it doesn't show 'login'. Here is my full register view: from django import forms from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.core.mail import send_mail from django.contrib.auth import authenticate, login CARRIER_CHOICES =( ('@txt.freedommobile.ca', … -
It gives an error when I try to update multiple images in django
I get an error editing product models when I want to edit photos related to each product. please help. I'm sorry my English is not good :) this error msg: AttributeError at /account/villa/update/13 'PhotoVillaForm' object has no attribute 'cleaned_data' Update View: def VillaEdit(request, pk): villa = get_object_or_404(Villa, id=pk) ImageFormset = modelformset_factory(PhotoVilla, fields=('photo',), extra=4) if request.method == "POST": form = VillaEditForm(request.POST or None, instance=villa) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() or formset.is_valid(): form.save() data = PhotoVilla.objects.filter(id_villa=pk) for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: photo = PhotoVilla(villa=villa, photo=f.cleaned_data.get('photo')) photo.save() elif f.cleaned_data['photo'] is False: photo = PhotoVilla.objects.get(id=request.POST.get('form-' + str(index) + '-id')) photo.delete() else: photo = PhotoVilla(id_villa=villa, photo=f.cleaned_data.get('photo')) d = PhotoVilla.objects.get(id=data[index].id) d.photo = photo.photo d.save() return HttpResponseRedirect(villa.get_absolute_url()) else: form = VillaEditForm(instance=villa) formset = ImageFormset(queryset=PhotoVilla.objects.filter(id_villa=pk)) content = { 'form': form, 'villa': villa, 'formset': formset, } return render(request, 'registration/villa-update.html', content) forms.py file: class VillaEditForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.filter(typeWodden='v')) class Meta: model = Villa fields = ["category", "code", "title", "duration", "thumbnail", "status", "service", "bed", "area"] template file html : <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="card-body"> <div class="form-group"> {{ form.title|as_crispy_field }} </div> {{ formset.management_form }} {% for f in formset %} <div style="background-color: #f2f4f4; margin: 5px; padding: 5px; width: … -
No posts on my Blog page on Heroku, problem with database(?)
At the start i must say that i'm complete beginner. I use django. I pushed my blog page on heroku, but its completly empty, there are no posts. It should look somehow like on the picture. Right now there is only Banner with quote, title "Lastest Post" and button to add new posts. I made a mistake before, because i changed an appname on heroku settings page, and migrated database to an old appname in cmd. I changed appname in cmd right after this, and tried to reset database. Then migrated database again but nothing changed. Tried also to restart dynos etc. I don't know what else kind of information should i tell you guys. There are also no posts when i login to admin page -
memcache on django not working when deploy project
my project memcache works properly in development state but not work when deploy project. What is the reason for this? What location should I put? What code should I change to solve this problem? also did pip install python-memcached What am I doing wrong? Any help will be appreciated. ---------- # settings for memcache: when development : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '127.0.0.1:11211', ] } } when deploy project: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '185.208.182.254:11211', ] } } ------------- my view: @cache_page(60 * 15) def my_view(request): ... -
Django - How to decode a base64url and render it in Django template
In my view function, I am sending a form to an endpoint then I receive a response in JSON. The response is then displayed on the template after the form has been submitted. The problem is that a key in the response is a photo that is encoded in base64url. e.g: {"photo": "a very long base64url"} What I want to achieve is to decode that base64url and render the image on the webpage. Here's my view function: def post_nin(request): if request.method == 'POST': form = NINPostForm(request.POST) if form.is_valid(): nin = form.cleaned_data['nin'] url = request.build_absolute_uri(reverse_lazy('nin_verification', kwargs={'nin': nin}, )) r = requests.get(url=url) resp = r.text resp_json = json.loads(resp) resp_list = resp_json['data'] # [{'tracking_id':12345, 'photo':'base64url'}] return render(request, 'ninsuccess.html', {'response': resp_list}) else: form = NINPostForm() context = {'form': form, } return render(request, 'ninform.html', context) Here is my template: <table class=""> <thead> <tr> <th>Tracking ID</th> <th>Picture</th> </tr> </thead> <tbody> {% for val in response %} <tr> <td>{{ val.tracking_id }}</td> <td>{{ val.photo }}</td> # a long base64url is displayed which is not what I want </tr> {% endfor %} -
Caching - Django rest framework
Use Case For example, an applicaton is data intensive, it has to show lot of data on frontend like feed, trending things, profiles etc. And all these data depend upon location Suppose, I have GetMyFeed API, the way I am Doing caching is :- I am caching the queryset I am taking cache key as API payload, because depending on it queryset will be formed. Cache key is API payload. Cache value is queryset ISSUE , I AM FACING IS:- Changes on Database will be in Large amount per second, so to invalidate the cache, I have to clear the whole cache. But I don't think it is the right way of doing cache invalidation. How can I update a single instance in list of objects which is cache value? And the main problem is single instance can be present in multiple queryset. So How will I update each copy of instance, which is present in different queryset, in cache? -
Modelform not saving data even tho it is being executed
The other posts that have this same question didnt actually help me so i decided to ask, problem is a little weird. Bcs the form.save command is being executed, at least i think but when i take a look at my db by the admin page, it doesnt work, and i dont know y, interesting enough the data is displayed in the print and the sucess message is displayed, if any extra information is needed i will gladly give it. Here it is the base model class DadoDB(models.Model): marca=models.CharField(max_length = 30, default ="ACURA") modelo=models.CharField(max_length = 30, default="XWZ") ano=models.IntegerField(default= 2021) status=models.CharField(max_length= 10,default= "BOM") cor=models.CharField(max_length= 10, default= "VERMELHO") combustivel=models.CharField(max_length= 10,default= "FLEX") quilometragem=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) lucro=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) preco=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) margem_de_lucro=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) data_postada = models.DateTimeField(default=timezone.now) autor= models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Empresa' Here it is the base form from django import forms from .models import DadoDB class InsiraDadosForm(forms.ModelForm): class Meta: model = DadoDB ['marca','modelo','ano','status','cor','combustivel'.... Here is the view @login_required def InserirDado(request): if request.method == 'POST': form = InsiraDadosForm(request.POST,instance= request.user) if form.is_valid(): form.save() print(request.POST) messages.success(request, f'Seus dados foram inseridos com sucesso!') return redirect('dado-InserirDado') else: form = InsiraDadosForm() return render(request, 'dado/inserirdado.html', {'form': form}) -
Django db foreign keys return 2 diffirent types
In MySQL I have 3 tables: Client, Room and ClientRoom,which points on two previous tables. -- ----------------------------------------------------- -- Table `client` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `client` ( `id` INT NOT NULL, `name` VARCHAR(255) NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; -- ----------------------------------------------------- -- Table `room` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `room` ( `id` INT NOT NULL, `price` DECIMAL(18,2) NOT NULL, `apart_num` INT NOT NULL, `free` BOOL default TRUE, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; -- ----------------------------------------------------- -- Table `client-room` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `client_room` ( `id` INT PRIMARY KEY AUTO_INCREMENT, `client_id` INT NOT NULL, `room_id` INT NOT NULL, `date_in` DATETIME NOT NULL, `date_out` DATETIME NOT NULL, INDEX `fk_client_room_idx` (`client_id` ASC), CONSTRAINT `fk_client_room_id` FOREIGN KEY (`client_id`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `fk_room_idx` (`room_id` ASC), CONSTRAINT `fk_room_id` FOREIGN KEY (`room_id`) REFERENCES `room` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; Using python manage.py inspectdb i got class Client(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) class … -
django migrations does not update database
I have django app already online and running. I created new model and if I do the makemigrations, it is working fine, but if I want to migrate it, then I receive Running migrations:No migrations to apply. Even though that I made a change. The change is also in the migration file. I am using postgresql with it. I tried to delete the migration file and create it once more, but it did not help. Any idea what might be wrong?