Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading Json to django model database results in Key Error
I have a custom manage.py command which I am using to upload a json file (a list of dictionaries) to my model. It appears to upload two records fine, but then throws a key error: KeyError: 'headline' My code is as follows: class Command(BaseCommand): def handle(self,*args,**options): filename = '/DoJ_Data_01-12-18.json' newpath = str(Path(home))+filename with open(newpath) as json_file: data = json.load(json_file) for d in data: q = doj(headline=d['headline'],topics=d['topics'],text=d['text'],url=d['url'],date=d['date']) q.save() As far as I can tell the json is valid. What am I missing? -
Python: Deserializing an object of type 'str' to OrderedDict
I'm sending my json to Django server but the problem lies when I want to send a list of dictionaries to it. I have a Load namedtuple which has a legs attribute that is a list. I have a Leg namedtuple that takes in strings. def test_upload_load(self): from collections import namedtuple load_attributes = 'reference miles rate legs' leg_attributes = 'ref f_code f_date t_code t_date' Load = namedtuple('Load', load_attributes) Leg = namedtuple('Leg', leg_attributes) f_date, t_date = str(datetime.now()), str(datetime.now()) load = Load(miles=234.3, rate=432.4, reference='112FR3XSR', legs=[]) leg1 = Leg(ref='1112222', f_code='SSS', f_date=f_date, t_code='XXX', t_date=t_date) load.legs.append(leg1._asdict()) res = self.client.post('/post/create_load/', js) Here's the function that receives the data, but legs is of type str. If I do print(type(legs)), it says type str, when it should be OrderedDict. I tried deserializing it by using json.loads but I get the following error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Here's the code that makes the error: @api_view(['POST']) def save_load(request): reference = request.POST.get('reference') miles = request.POST.get('miles') rate = request.POST.get('rate') legs = request.POST.get('legs') print(json.loads(legs)) return Response(status=status.HTTP_200_OK) I pretty much want legs to be turned into an actual dictionary which I can retrieve values from. -
Error while installing mysqlclient in django project
I've been trying to figure this out for a couple days. I am trying to make a django project in a virtual environment and install mysqlclient on it. Process went like this: In my project path: virtualenv pyvenv1 Then I activated it: source /pyvenv1/bin/activate Then I installed django: pip install django Then I made a new project: django-admin startproject djangop1 Then inside that project I try to install mysqlclient pip install mysqlclient I get back this: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /Users/daniel/Documents/Python/DjangoP1/py1/bin/python3.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/1h/dg482p2x2bz7n46_px8nphf40000gn/T/pip-install-xgahev5_/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /private/var/folders/1h/dg482p2x2bz7n46_px8nphf40000gn/T/pip-wheel-4_cp0769 --python-tag cp37: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 copying _mysql_exceptions.py -> build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.9-x86_64-3.7 gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common … -
Django: Get all object and return it to view
im new in python and Django also I was searching for answer but can't find it :( I have 3 class in my app first one class in my app is Exam, Question, Answer. models.py class Egzam(models.Model): name = models.CharField(max_length=200, default='kolokwium ') date = models.DateField('date publish') code = models.CharField(max_length=200) def __str__(self): return str("%s %s" % (self.date, self.name)) class Question(models.Model): egzam = models.ForeignKey(Egzam, on_delete=models.CASCADE) name = models.CharField(max_length=200) # nazwa pytania def __str__(self): return self.name class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer_text = models.CharField(max_length=200) #treść odpowiedzi correct = models.BooleanField(default=False) def __str__(self): return self.answer_text So Egzam class can handle few Question and Question class can handle few Answers. What i want to do is list all exam's on index page and after i clicked on one of them, my app should open new page where I see all Qestion and Answers to this specyfic Exam. Here is rest of my code urls.py app_name = 'kolos' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.EgzamView.as_view(), name='view'), ] views.py class IndexView(generic.ListView): template_name = 'kolos/index.html' context_object_name = 'egzam_list' def get_queryset(self): return Egzam.objects.all() class EgzamView(generic.DetailView): model = Egzam template_name = 'kolos/egzam.html' def get_queryset(self): return Answer.obects.filter() -
Django using NGINX, WSGI and gunicorn give 404 on all pages except root
I'm trying to get a production server running for my Django app, but am having issues with 404 errors on every page except the root webpage. I can access it through the url or the ip address and get the main page to render, but any of the other pages don't work. I had the page working on a sandbox server, and the 404 pages are nginx, not django 404 pages, which makes me think it's something to do with how I've configured my nginx sites-available file. server { listen 80; server_name <url> www.<url> <ip_address>; location = /favicon.ico {access_log off;log_not_found off;} root /home/ubuntu/<directory>/mysite; location = /static/ { root /home/ubuntu/<directory>/mysite/; } location = /media/ { root /home/ubuntu/<directory>/mysite/; } location = / { include proxy_params; proxy_pass http://unix:/home/ubuntu/<directory>/mysite/mysite.sock; } } For the page that returns properly, I get all the static files (css,img) that are expected. I've looked at the nginx error log and get this: 2018/12/02 20:50:11 [error] 11506#11506: *3 open() "/home/ubuntu/<directory>/mysite/about.html" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: <url>, request: "GET /about.html HTTP/1.1", host: "www.<url>.com", referrer: "http://www.<url>.com/" 2018/12/02 20:55:41 [error] 11577#11577: *2 open() "/home/ubuntu/<directory>/mysite/about.html" failed (2: No such file or directory), client: XXX.XXX.XXX.XXX, server: <url>.com, request: "GET /about.html … -
DjangoREST get object from IntegerField
So I'm doing a little project in Django REST, and I'm still getting used to the ORM. I'm dealing with the following Django model: class Session(models.Model): date = models.DateTimeField(default=now, blank=False) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='efforts', on_delete=models.CASCADE) I'm particularly interested in the number of session each owner has, given a specific month. As follows: Session.objects.filter(date__gte=start, date__lt=end).values('owner').annotate(num_sessions=Count('owner')).order_by("owner") This query produces results of the following structure: (owner, count) In the serializer, I'd like to use the owner to retrieve the user name, as to structure the response. I'm having absolutely no luck in doing so. My serializer looks like this at the moment: class SessionAggregateSerializer(serializers.ModelSerializer): num_sessions = serializers.IntegerField(read_only=True) owner = serializers.IntegerField(read_only=True) class Meta: model = Session fields = ('id', 'owner', 'num_sessions') Anyone any suggestions on how to approach this? For regular queries, I'm using the following line to retrieve the users' name, but this is no longer applicable in the current setting: owner = serializers.ReadOnlyField(source='owner.username') -
Keep instance of files when there's validation error on post
I'm having some problems with the instance of these gallery files and other on my project. When I have validation errors, the files uploaded disappear. In this case I wanted to force the user to input at least 3 images to the gallery, but if he only chose one, and sent the form, after the POST the image will appear there, but if he only fill the rest and press send, it will say that he didn't fill the first one he sent last time, because it was only showing, but didn't send that instance again to the form for some reason... The objective is to keep the images uploaded on memory even if the user press the save button again and again with the errors so that he can only fill the ones remaining. attachments.form.html <div class="form-group"> <div class="col-sm-3 control-label"> <label class="">Gallery</label> <br><br> <small>Add photos to your project</small> </div> <div class="col-sm-9"> <div class="row"> {{ gallery.management_form }} {% for form_gallery in gallery %} <div class="col-lg-10 gallery-formset"> <p class="file-description"> {% if form_gallery.file.value %} {% if gallery.non_form_errors %} <span class="filename"> <a class="text" href="#">{{ form_gallery.post_file_name }}</a> <span class="btn-delete glyphicon glyphicon-remove"></span> </span> {% else %} <img width="150" class="media" src="/media/{{ form_gallery.file.value }}"> {% endif %} … -
Issue with images in Django
Have an issue with images form in Django. Upload of images is working correctly and displayed in admin page also right. But if I want to use this image in my templates or go direct by the link from admin console, receiving 404 error, why? Django : 2.1.1 Python : 3.6.6 models.py from art.settings import STATICFILES_DIRS import os def get_image_path(instance, filename): return os.path.join(STATICFILES_DIRS[0], 'collections', filename) class ArtCollections(models.Model): title = models.CharField(max_length=200) content = models.TextField() class ImagesList(models.Model): collection_id = models.ForeignKey(ArtCollections, on_delete=models.CASCADE, default=1) images = models.ImageField(upload_to=get_image_path, blank=True, null=True) From admin console, uploading the file, and its doing in correct folder, exx /static/image.jpg file is exist : -rw-r--r-- 1 www-data www-data 438930 Dec 2 /static/image.jpg but still getting 404 P.S. on folder give full grants and for apache also -
Django: Why are my static files not showing up and always giving me a 404 error when DEBUG=False?
I am working on my Windows Machine, trying to develop multiple apps for a project called "portal". After working on it, I have set DEBUG=False, and now all my static files are giving me a 404 error after loading any page. When running python manage.py runserver in CMD, I get this when loading a page: [02/Dec/2018 14:10:14] "GET /account/sign-in HTTP/1.1" 200 6249 [02/Dec/2018 14:10:14] "GET /static/fonts/fonts.css HTTP/1.1" 404 96 [02/Dec/2018 14:10:14] "GET /static/css/argon.css HTTP/1.1" 404 94 [02/Dec/2018 14:10:14] "GET /static/branding/logo.png HTTP/1.1" 404 98 I have looked at over 20+ posts about this which were mostly the same and I have followed all of their steps, such as: I have set these in my settings.py file: STATIC_URL = '/static/', STATICFILES_DIRS = ['portal/static/'] (I have a static folder in the folder that holds files like settings.py), and STATIC_ROOT = os.path.join(BASE_DIR, "static") I have called python manage.py collectstatic I have even created a new Django test project and did all these steps above, and they ARE working for that new test project. I have even removed all files in __pycache__ and reset my migrations, and database files. Are there any other possible secure (I have seen others use cheats such as --insecure) solutions … -
Creating new object returns field with None value
I'm trying to create a new object of my model, but keep on getting a value of none for one field. My models look like this: class KeyCategory(models.Model): program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE) name = models.CharField('Name', max_length=100) events = models.ManyToManyField('Event', through='EventQuota') class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' ordering = ['name'] unique_together = ("program", "name") permissions = ( ('view_key_category', 'Have access to categories'), ) class EventQuota(models.Model): key_category = models.ForeignKey(KeyCategory, on_delete=models.CASCADE, related_name='key_quota') event = models.ForeignKey('Event', on_delete=models.CASCADE, related_name='key_quota') quota = models.PositiveIntegerField('Quota', default=0) class Meta: verbose_name = 'Quota' verbose_name_plural = 'Quotas' unique_together = ('key_category', 'event') When I try now to create a KeyCategory and my EventQuota, the field "events" for KeyCategory always returns core.Event.None if program.pk == 1: for _ in range(0, 2): access_code_category = AccessKeyCategory( program=program, name=random.choice(self.eventList) ) access_code_category.save() event_quota = AccessKeyEventQuota( access_key_category=access_code_category, event = random.choice(eventList), quota = random.randint(0,100) ) event_quota.save() Note: the eventList in the random.choice is a queryset list of objects. I tried to follow Djangos Extra fields on Many-to-Many relationships example, but somehow it seems that I'm missing something here or doing something not the right way? Would appreciate any help! Thanks in regard. -
Phantom style in django project
I'm working on my first real django project, and was fiddling around with the css, but the changes I made did not have any effect on the site. I tried changing things on all 3 of the css files but nothing changed. I then deleted the files (from the project I still have them), and still nothing changed. My site is getting styled, I checked all of my html to make sure there was no inline style in there. All the html files are working, when I change them the site changes. Is this some weird caching thing? I've tried rerunning the server several times and still my site is getting style, seemingly from nowhere. Anyone have any ideas? -
File splitting and writing to database
How can I write the data in several tables at once? I have 9 fields in Excel file, the format is as follows: 05/16/2015 8:00 | KG6418.040 | M153 | 400600052850 | EXC | 106 | 43 429 | Changierung_Ein / Aus | 1 But 2,3,4 fields are always the same made connection 1 to many. I tried to break the data like this: wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) data = [] for row in ws.iter_rows(row_offset=1): parameter = Parameter() And my models: class Line (models.Model): id_line = models.IntegerField(primary_key=True) par_machine = models.CharField(max_length=200) class Order (models.Model): id_order = models.IntegerField(primary_key=True) par_fa = models.CharField(max_length=200) class Recipe (models.Model): id_recipe = models.IntegerField(primary_key=True) par_recipe = models.CharField(max_length=200) class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.IntegerField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) parameter = models.OneToOneField(Parameter, on_delete=models.CASCADE) Where in Measurements line,order,recipe,params this is just one entry in the respective tables. For example, if you break the given string, you should get: Line: 1 M153 Order: 1 400600052850 Recipe: 1 KG6418.040 Parameter: 1 106 43429 Changierung_Ein / Aus Measurements: 1 1 1 1 1 … -
Django select_related queryset in template not rendering
I have a simple view like so: def classticker(request): tickermodel = Tickers.objects.all().select_related('subsector_fk') form = TickerForm() return render(request, 'feeds/main.html', {'v': 10, 'form': form, 'tickermodel': tickermodel}) tickermodel is successfully returning a queryset with all of the fields in the Tickers table and the Subsector table (through the subsector_fk field). This includes the fields 'ticker', 'company_name' and 'subsector' that I'm using in the template below. When I render my template and iterate through the tickermodel queryset I cannot seem to access fields that are coming from the Subsector table. Below tic.ticker and tic.company_name are rendering as expected but tic.subsector is not. I have no idea why?? My template looks like this: <table class="tbllist"> <tr><th>Current Tickers</th></tr> {% for tic in tickermodel %} <tr> <td><input type="checkbox" name="myclass" value="{{tic.ticker}}"/></td> <td class="selectable" data-tik="{{tic.ticker}}"><span class="uppercase">{{ tic.ticker }}</span> - {{ tic.company_name }}</td> <td>{{ tic.subsector }}</td> /*<<<< this will not display >>>>>*/ </tr> {% endfor %} </table> -
how to make a circular level meter django
I am trying to implement a level circular that looks like this circular level meter I rotate the meter by -90deg - works fine I adjust color to red - works fine I use border radius to clip it circular, just like photos - it doesn't work. The background gets clipped, but the foreground (the red level) remains rectangular, no clipping. The CSS definitive guide book mentions that the object continues to be rectangular, no matter how it is rendered or how it looks to you. An example shows that text inside a square container whose corners are rounded, sticks out of the circle, because it lives in the square. Any clues on how to do this? Any help will be greatly appreciated. Best, Juan -
How to change datetime value via functions in django?
I have code within a context processor that displays the date in a navbar via the {{date}} tag using the function I created: import datetime def date(request): nav_date = datetime.date.today() return { "date" : nav_date } However, I would like to create a function to change the date so that whenever a button is clicked in the html code, the function would push the date from the nav_date variable 1 day forward. -
Django static files templatetags.static
I am trying to open a json file in python. It is in a directory called json in static directory of my app. I configured the static files as per the given documentation. But I get this error on opening files in python using open() function def send(request): file = static('accounts/json/credentials.json') f = open(file, "r") return HttpResponse("click here <a href='" + file + "'> asd</a>") The above code generates a FileNotFoundError No such file or directory: '/static/accounts/json/sample.json' I also used this code def send(request): file = static('accounts/json/credentials.json') return HttpResponse("click here <a href='" + file + "'> asd</a>") The above code successfully gave me the response. And On clicking the link asd it is working fine and opens the JSON file. I have googled a bit and also went through few stackoverflow questions but not sure what the actual error is, Can anyone help me in finding out. Thanks -
django-tables2 Adding template column, which content depends on condition
Working with Django framework django-tables2 I have a table for which I add 2 additional template columns (buttons). I want to display only these buttons depending on the condition on other column. Lets say grade is G2 then edit/delete buttons are visible or active. Else they are not displayed or disabled. Here it how it looks now: Is it possible to do that in table class? Or do I need to write some fancy jquery code? Here is my tables.py import django_tables2 as tables from .models import Person from django.urls import reverse_lazy class PersonTable(tables.Table): T1 = '<button type="button" class="btn js-update" update-link="{{ record.get_absolute_url_update }}">update</button>' T2 = '<button type="button" class="btn js-delete" delete-link="{{ record.get_absolute_url_delete }}">delete</button>' edit = tables.TemplateColumn(T1) delete = tables.TemplateColumn(T2) class Meta: model = Person fields = ('name','surname','city','grade',) template_name = 'django_tables2/bootstrap4.html' -
Get first and last item in one query
I want to get the first item and the last item in Django. My current code looks like this: first = Article.objects.first() last = Article.objects.last() However, these are two queries. Is there a way to make one query out of it? -
Django: creating a dynamic number of forms
im new to Django so any kind of help would be appreciated. Is there a way to create a dynamic number of forms depending on the elements of a list in Django? For Example I have a list of 15 string elements and I want to create a view which displays the first elements of the list and then at every third element it creates a form for user Input right after the strings. I also dont really know if I have to edit it in my views.py or forms.py to create many forms. -
MultiValueDictKeyError at /files/ in Django file upload
I am facing issue uploading file using Django rest framework. I am testing using postman and adding Content-Type header as multipart/form-data, but I get MultiValueDictKeyError at /files/ error, here is my code. class FileUploadView(APIView): parser_classes = (MultiPartParser,) def put(self,request, format = None): file_obj = request.FILES['file'] file_obj.seek(0) data = file_obj.read() return Response(data,status=204) I am using multipart form data so that I access post data along with uploading files. -
Django filter - filter by Avg of a field in related model
I'm using django-filter to filter through Festival model. There is another model - Review which contains reviews about festivals and related to Festival model by Foreignkey. My goal is to be able to filter festivals by friendly average > 3 (friendly is a one field for example in Review model). Any idea how to do it? Many thanks =] Models.py class Review(models.Model): ... festival = models.ForeignKey( Festival, related_name='Festival_Reviews', on_delete=models.CASCADE, null=True, blank = True, default = '', ) score_choices = ( (1, 'Bad'), (2, 'Okay'), (3, 'Good'), (4, 'Great'), (5, 'Superb'), ) friendly = models.IntegerField( choices=score_choices, default='', null=True, blank = True, ) class Festival(models.Model): ... created_at = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200) Filter.py (this was my idea, I'm pretty new to Django so seem not in the direction..) class FestivalFilter(django_filters.FilterSet): ... Festival_Reviews_friendly = django_filters.BooleanFilter(field_name='Festival_Reviews',method='avg_above3') def avg_above3(self, queryset, name, value): return queryset.aggregate(friendly_avg=Avg('friendly')).filter(friendly_avg__gt=3) Views.py class HomePage(ListFilteredMixin, AjaxListView): template_name = 'index.html' page_template = 'index_page.html' model = models.Festival paginate_by = 12 context_object_name = 'festivals' filter_set = FestivalFilter -
Wagtail admin - playing with urls
I created in wagtail a model called Regbox in model.py and also RegboxModelAdmin in wagtail_hooks.py. Wagtail admin includes item Regbox in wagtail side bar menu. Then I programmatically created a new collection, a new group with permissions add, edit, delete Regbox and this group is assigned to new user after registration. New user can add (edit and delete) new Regbox (model Regbox has forein key User) and this new user can see in wagtail admin only his own regboxes (I used queryset filter so that superuser could see all regboxes in wagtail admin and the current user only his own regboxes). But if this new user plays with urls he can see also other regboxes (not only his own regboxes). Could someone please advice me how can I do it in wagtail admin ? Thanks -
Ember JSONAPI Adapter with Django REST framwork json API
I am using EmberJS with django. For my API do I want to use JSONAPI. For this I installed Django rest framework json api. And in Ember do I use the JSONAPIAdapter. When my Ember app tries to get /appointments/ everything is fine and "type": "Appointment" but when my Ember Store tries to save an appointment it goes to the correct URL but "type": "appointments" after some testing I concluded that the only type that works is "Appointment", not "appointment" and neither "appointments" or "Appointments". I don't know why the Ember JSONAPIAdapter does this, but is there a way to fix this problem? -
Django 2.1.3/SQLite : UNIQUE constraint failed: users_profile.user_id || while trying to access my superuser account
i am working on a website that has a social appeal and i have to create an AbstractUser Model to store extra info about the users; while doing so, i ran into this error while trying to log into django admin page with my superuser account. UNIQUE constraint failed: users_profile.user_id. i have rebuilt the project 3 times and the issue still occurs. here's my models/forms/signals/admin.py files models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from PIL import Image # Create your models here. class UserModel(AbstractUser): bio = models.TextField(max_length=500, blank=True, null=True) location = models.CharField(max_length=35, blank=True, null=True) birthday = models.DateField(blank=True, null=True) url = models.URLField(blank=True, null=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) image = models.ImageField(default='default.png', upload_to="profile_pics") def __str__(self): return self.user.username def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) path = self.image.path img = Image.open(path) if img.height > 500 and img.width > 500: output_size = (500, 500) img.thumbnail(output_size) img.save(path) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UserModel, Profile class UserModelCreationForm(UserCreationForm): email = forms.EmailField() class Meta: model = UserModel fields = [ 'username', 'password1', 'password2', 'email', ] class UserModelChangeForm(UserChangeForm): email = forms.EmailField() class Meta: model = UserModel fields = [ 'username', 'email', ] class … -
Migration Issue Django, No Migrations To Apply to New DB
I feel like I understand how migrations work, but I am running into what seems to be a strange issue with migrations today. I created a DB in my settings file (and obviously on the server), but when I run the migrations to sync the Models with the DB I am being told there are no migrations to apply. I had 2 DBs on my server: test_universal and test_client. Now I have a new one, which is a 'real' client titled _6_. When I created test_client I ran the same migrations you see below and they worked. I have read that the migration table may be causing this but I am moving to a new DB so that can't be right. What is going on? py manage.py migrate objects_client --database=_6_ Operations to perform: Apply all migrations: objects_client Running migrations: No migrations to apply. py manage.py migrate objects_client 0001_initial.py --database=_6_ CommandError: Cannot find a migration matching '0001_initial.py' from app 'objects_client'. py manage.py showmigrations objects_client objects_client [X] 0001_initial [X] 0002_auto_20181119_2025 # there is nothing in the default db either py manage.py migrate objects_client Operations to perform: Apply all migrations: objects_client Running migrations: No migrations to apply.