Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RecursionError when uploading certain images
I am attempting to create a model with an image input that is to be resized and hashed along with a thumbnail on save. However, I appear to to have created an infinite recursive call. Some images upload, create thumbnails, and generate hashes without issues, but one image causes the program to call self.thumbnail.save(new_name, img_file) (the last line of generate_thumbnail) endlessly. How can I save the image and avoid the recursive call? Any help is appreciated. This is a slightly different issue than my last question, RecursionError when trying to save image. Below are some properties of the image files I used which may or may not be relevant. Successful image properties: 3888x2592 JPEG RGB 1920x1280 PNG RGB Unsuccessful image properties: 360x720 PNG RGBA models.py import hashlib import os import re from base64 import b16encode from functools import partial from io import BytesIO from PIL import Image from django.db import models from mtm.settings import MEDIA_ROOT class Person(models.Model): prefix = models.CharField(blank=True, null=True, max_length=5) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) suffix = models.CharField(blank=True, null=True, max_length=5) image = models.ImageField(default=None, upload_to='people/') _image_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) thumbnail = models.ImageField(editable=False, null=True, default=None, upload_to='people/') _thumbnail_hash = models.BinaryField(blank=True, null=True, default=None, max_length=16) bio = models.TextField() phone = … -
image Not upload in Django and not created media folder
this is my code I am try to upload image to in media folder. all other field have been uploaded but image is not move to media folder and endly when i make migration do not create media folder url.py from django.contrib import admin from django.urls import path,include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static # for media from django.conf import settings # for media file install pillow package urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('AdminDashboard.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() Model.py from django.db import models from django.core import validators # this library is used for form validation from django.core.validators import ValidationError # Create your models here. class movie(models.Model): def min_length_check(self): if len(self)> 10: raise validators.ValidationError("value must be greater than 10") title = models.CharField(max_length=255) description = models.TextField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) # this will add at one time updated_at = models.DateTimeField(auto_now=True) # created and updated every image = models.ImageField(upload_to='images',default='default.png') View.py from django.shortcuts import render, redirect from django.http import HttpResponse ,HttpResponseRedirect # this include for model for http request from .forms import movieForm #from .models import movie # Create your views here. def index(request): return render(request,"index.html") def userRegister(request): return render(request,"userReg.html") def adminRegister(request): return render(request,"admin/adminReg.html") def movieRegister(request, id=0): if … -
How can I get a response of from view model?
How can I get a response of an (object post) from View model. I have tried the code below I hashed to be sure that code has worked and thanks for god it succeeded. How can I get a response and make all objects showed in the View model case views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from django.views.generic import View from .forms import PostForm from .models import Post class PostView(View): all_objects = Post.objects.all() post_form = PostForm template_name = 'myapp/index.html' def get(self, request): post_form = self.post_form(None) return render(request, self.template_name, {'form': post_form}) def post(self, request): post_form = self.post_form(request.POST) if post_form.is_valid(): post_form.save() return redirect('myapp:index') return render(request, self.template_name, {'form': post_form, 'all_objects': self.all_objects}) ''' def index(request): all_objects = Post.objects.all() post_form = PostForm if request.method == "POST": post_form = PostForm(request.POST) if post_form.is_valid(): post_form.save() return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects}) return render(request, 'myapp/index.html', {'form': post_form, 'all_objects': all_objects}) ''' -
Angular 8 datatables with django rest framework
I have to use angular 8 datatables with django rest framework. I have written the serverside code which return a restful api. Any help in writing the server side angular code will be of great help. I have tried using the documentation it is not working. Here is the rest framework code class DataTableListCreateAPIView(ListCreateAPIView): pagination_class = DataTablePagination search_parameters = () default_order_by = '' unfiltered_query_set = None def get_queryset(self): self.unfiltered_query_set = query_set = super(DataTableListCreateAPIView, self).get_queryset() order_by_index = int(self.request.query_params.get('order[0][column]',0)) orderable = bool(self.request.query_params.get('columns[{}][orderable]'.format(order_by_index), self.default_order_by).replace('.','__')) if order_by_index == 0 or not orderable: order_by_index = 1 order_by = self.request.query_params.get('columns[{}][data]'.format(order_by_index), self.default_order_by).replace('.','__') order_by_dir = self.request.query_params.get('order[0][dir]','asc') if order_by_dir == 'desc': order_by = '-{}'.format(order_by) search_queries = self.request.query_params.get('search[value]','').strip().split(' ') q = Q() if len(search_queries) > 0 and search_queries[0] != u'': for params in self.search_parameters: for query in search_queries: temp = { '{}__contains'.format(params):query, } q |= Q(**temp) query_set = query_set.filter(q) if order_by == '': return query_set return query_set.order_by(order_by) def get(self,request,*args,**kwargs): result = super(DataTableListCreateAPIView, self).get(request,*args,*kwargs) result.data['draw'] = int(request.query_params.get('draw',0)) result.data['recordsFiltered'] = result.data['count'] result.data['recordsTotal'] = self.unfiltered_query_set.count() del result.data['count'] result.data['data'] = result.data['results'] del result.data['results'] return result class ReligionDataTableView(DataTableListCreateAPIView): serializer_class = ReligionSerializer search_parameters = ('name',) default_order_by = 'name' queryset = Religion.objects.all() Which return the following result {"next":null,"previous":null,"draw":0,"recordsFiltered":10,"recordsTotal":10,"data":[{"id":5,"name":"Christian","created_date":"2020-02-09T03:13:11.892478Z","staff":null},{"id":1,"name":"Christian union","created_date":"2019-12-14T01:36:35.384599Z","staff":null},{"id":6,"name":"Jewish","created_date":"2020-02-09T03:13:29.611206Z","staff":null},{"id":4,"name":"Seventh Day Adventist","created_date":"2019-12-18T05:58:31.359246Z","staff":null},{"id":3,"name":"Seventh Day Adventist","created_date":"2019-12-14T01:52:52.485440Z","staff":null},{"id":8,"name":"Seventh day","created_date":"2020-03-08T01:45:57.534001Z","staff":null},{"id":7,"name":"YCS","created_date":"2020-03-08T01:44:46.555526Z","staff":null},{"id":2,"name":"Young Christian Association","created_date":"2019-12-14T01:36:54.039418Z","staff":null},{"id":12,"name":"ghdsghdsghsd","created_date":"2020-03-08T13:45:09.238152Z","staff":3},{"id":10,"name":"hhdhshjds","created_date":"2020-03-08T13:44:57.133368Z","staff":3}]} I … -
Django Annotated Query to Count all entities used in a Reverse Relationship
This question is a follow up question for this SO question : Django Annotated Query to Count Only Latest from Reverse Relationship Given these models: class Candidate(BaseModel): name = models.CharField(max_length=128) class Status(BaseModel): name = models.CharField(max_length=128) class StatusChange(BaseModel): candidate = models.ForeignKey("Candidate", related_name="status_changes") status = models.ForeignKey("Status", related_name="status_changes") created_at = models.DateTimeField(auto_now_add=True, blank=True) Represented by these tables: candidates +----+--------------+ | id | name | +----+--------------+ | 1 | Beth | | 2 | Mark | | 3 | Mike | | 4 | Ryan | +----+--------------+ status +----+--------------+ | id | name | +----+--------------+ | 1 | Review | | 2 | Accepted | | 3 | Rejected | +----+--------------+ status_change +----+--------------+-----------+------------+ | id | candidate_id | status_id | created_at | +----+--------------+-----------+------------+ | 1 | 1 | 1 | 03-01-2019 | | 2 | 1 | 2 | 05-01-2019 | | 4 | 2 | 1 | 01-01-2019 | | 5 | 3 | 1 | 01-01-2019 | | 6 | 4 | 3 | 01-01-2019 | +----+--------------+-----------+------------+ I wanted to get a count of each status type, but only include the last status for each candidate: last_status_count +-----------+-------------+--------+ | status_id | status_name | count | +-----------+-------------+--------+ | 1 | Review | 2 | … -
Change between muiltiple databases with Django
I have software that centralizes a database to group users, group permission and other things in common, such as the companies that each one can manage. Together, I have an area where I can switch between companies I manage. Each company has its database, but the users are the same. Is there a possibility to integrate something like this with the django admin? All companies manage the same tables on different bases, are companies in the same industry, but the data is separate. -
Django templates won't load but HttpResponse will
I recently began learning django and have been running into some trouble and I can't figure out why. My problem is quite simple: whenever I try to run my homepage with a template, it throws up a 404 error. My file hierarchy is as such: crm accounts templates accounts dashboard.html urls.py views.py crm urls.py In crm/urls, I have from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')) Then in accounts/urls, there is, from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] And in views, I have from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'dashboard.html') My dashboard.html is just a basic html file with a title and h1, that's it. Also, whenever I change return render(request, 'dashboard.html') to return HttpResponse('home') in my home function, it decides to show. -
Custom Field Validation Message Django
I have a field 'Reference_Number' in both my form and my model. The form should not be saved if this field is blank, and if it is blank, a customer error message should appear by the field. I have this set up currently as you see it below, but still I just get the django standard message 'Please Fill Out This Field'. What change do I need to make to show the error message that I defined in the forms.py? models.py class PackingList(models.Model): Reference_Number = models.CharField(max_length=100, null=True) .... forms.py class PackingListForm(forms.ModelForm): class Meta: model = PackingList fields = ['Reference_Number'] def Clean_Reference_Value(self): Ref = self.cleaned_data.get('Reference_Number') if not Ref: raise forms.ValidationError('This field is required') #this is the message that should show packlist.html (template) ... <td colspan="1">Reference: {{ form.Reference_Number }} {% for error in form.Reference_Number.errors %}<p>{{ error }}</p> {% endfor %}</td> ... views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: request.session['data'] = form.cleaned_data return redirect('myview') elif 'save' in request.POST: form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Why doesn't my dynamically generated stylesheet (Django) get applied by my html pages?
I am using Django and have set up a view that returns a dynamically generated stylesheet to allow for user themes. I link the stylesheet in the head section of my pages with, <link href="/theme.css" rel="stylesheet"> I can see the request for /theme.css at the server and a successful response. I can also view the source of the page in the browser and it shows the correct contents for the stylesheet. However, for some reason the styles in theme.css are not applied to the page. If I place the contents of the dynamically created stylesheet into a static file and change the link like so, <link href="/static/rml/css/theme.css" rel="stylesheet"> the styles are correctly applied. I can't see why there is a difference. I have looked for answers and can't find anything relevant. -
How make local http request in flutter?
I'm making an app, and i already have a server running in my local. I can acess trought my navigator the url: Request URL: http://localhost:4444/categorie?page_size=15&page=1 Request Method: GET Status Code: 200 OK Remote Address: 127.0.0.1:4444 Referrer Policy: no-referrer-when-downgrade Preview: { "count": 4, "next": null, "previous": null, "results": [ { "uid": "_b656062d3754", "name": "Pinga" }, { "uid": "_0c644473c244", "name": "Cerveja" }, { "uid": "_75df557ccbaa", "name": "Vinhos" }, { "uid": "_8e32ce3baded", "name": "Refrigerantes" } ] } But when i try in flutter, the request never respond: getCategories() async { String url = 'http://localhost:4444/categorie?page_size=15&page=1'; var response = await http.get(url); if (response.statusCode == 200) { // If the call to the server was successful, parse the JSON return response.body; } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } } I'm running the server in my Windows10 using Django. And my flutter app is in the Android Studio using a Virtual Machine as device. I tryed to change the ip to 127.0.0.1 and 10.0.0.1 but still not working. Have i change the host of Django or enable any configuration in my flutter or inside VirutalBox? My dependencies: environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter … -
class mixing with MRO
I want to override a method of django.db.backend class and calling super() but leaving other method states untouched. These are bult-in classes in utils.py class CursorWrapper(object): def execute(self, sql, params=None): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) class CursorDebugWrapper(CursorWrapper): # XXX callproc isn't instrumented at this time. def execute(self, sql, params=None): start = time() try: return super(CursorDebugWrapper, self).execute(sql, params) finally: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.debug('(%.3f) %s; args=%s' % (duration, sql, params), extra={'duration': duration, 'sql': sql, 'params': params} ) def executemany(self, sql, param_list): ... Now i created make own implementation of execute method to log. class Mixin(object): def execute(self, sql, params=None): start = time() try: temp = super(Mixin, self).execute(sql, params) stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.debug('(%.3f) %s; args=%s' % (duration, sql, params), extra={'duration': duration, 'sql': sql, 'params': params} ) return temp except Error as e: stop = time() duration = stop - start sql = self.db.ops.last_executed_query(self.cursor, sql, params) self.db.queries_log.append({ 'sql': sql, 'time': "%.3f" % duration, }) logger.error('(%.3f) %s; args=%s' % (duration, sql, … -
Multiple audio players are not working - only the first one (Javascript)
I have product cards that each have a player. What is expected: Each player should play its own track when clicked on the play button. What is happening right now: When I click on any of the play buttons it plays the first track only. Here is my code: let isPlaying = false let playBtn = document.querySelectorAll('.playerButton'); for (var i = 0; i < player.length; i++) { if (playBtn != null) { playBtn[i].addEventListener('click', togglePlay); } } // Controls & Sounds Methods // ---------------------------------------------------------- function togglePlay() { let player = document.querySelectorAll('.player') if (player.paused === false) { player.pause(); isPlaying = false; document.querySelector(".fa-pause") .style.display = 'none'; document.querySelector(".fa-play") .style.display = 'block'; } else { player[0].play(); document.querySelector(".fa-play") .style.display = 'none'; document.querySelector(".fa-pause") .style.display = 'block'; isPlaying = true; } } {% for product in products %} <div class="card-trip"> <div class="player-section"> <img src="{{ product.image.url }}" /> <div class="audio-player"> <a class="playerButton"> <span> <i class="fas fa-play"></i> </span> <span> <i class="fas fa-pause"></i> </span> </a> <audio id="player" class="player"> <source src="https://api.coderrocketfuel.com/assets/pomodoro-times-up.mp3"> Your browser does not support the audio element. </audio> </div> </div> <div class="card-trip-infos"> <div> <h2>{{product.name}}</h2> <p>{{product.description}}</p> <button class="btn" type="button">buy now - ${{product.price}}</button> <p>{{product.tag}}</p> </div> </div> </div> {% endfor %} -
Django 3.0.4 brings ASGI. Makes sense continue patching things with gevent?
I've tried run my django project through uvicorn but it led to the following error: DatabaseWrapper objects created in a thread can only be used in that same thread My django project patched things for gevent: the default gevent path_all plus psycogreen patch. Remove these patches makes the uvicorn works. But Why this errors occurs, is ASGI incompatible with gevent? -
How would I create a page fo a tournament that lets the user choose who won the match?
I currently have a page for each tournament on my website and this shows basic info (rules, creator, etc.). I want to create a page (linked to on this page) which shows all the matches for the round of the tournament I have calculated and then lets you pick which team won from the two. For example Team1 vs Team2 Click the winner I have a table called Match class Match(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) score = models.IntegerField(db_column='Score', null=True) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) winner = models.BooleanField(db_column='Winner', null=True) How do I create a page that enables me to change the winner field with a button or something else? Please let me know if you need any more information -
Django/Issues with RDS Aurora Postgres
I have utility cron jobs working on thousands of records at a time (read/write). They keep getting the following error, randomly, and without a pattern: django.db.utils.InternalError: cannot execute UPDATE in a read-only transaction The database is RDS Aurora Postgres -- I have two instances in that cluster -- one Writer/One Reader. I created a single endpoint that includes both of them, thinking read/write usage from my application will be routed and managed intelligently by the cluster. I may have have been wrong here. Is there anything else I (besides Exception handling.......) that I can use to make continuous read/write requests from the cluster more robust? It's really unusable this way. -
Obtaining user location - Django, GeoIP2
I am trying to get user locations. Everything looks good if I turn on the development server on my server, using: python manage.py runserver 157.245.228.127:8000 But if I'm trying to get locations by going to the site, for exapmle: http://157.245.228.127/ this is not working properly. Of course, this results in the correct location being obtained http://157.245.228.127:8000/ . Why when I try to enable my server through python manage.py runserver can recive locations correctly and in the other case not? My file: views.py from django.contrib.gis.geoip2 import GeoIP2 [...] ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Not work' -
Display name along with the count in descending order in Django
I have two models within my models.py file as described below: class Company(models.Model): company_name = models.CharField(max_length=100) def __str__(self): return f"{self.company_name}" Class Jobs(models.Model): job_title = models.CharField(max_length=100) job_company = models.ForeignKey(Company, models.on_delete=CASCADE) job_location = models.CharField(max_length=50) job_salary = models.CharField(max_length=20) def __str__(self): return f"{self.job_title}" The data present within these tables is as shown below: COMPANY -------------------- | COMPANY_NAME | -------------------- | Google | | Facebook | | Microsoft | | Amazon | -------------------- JOBS ------------------------------------------------------------------- | JOB_TITLE | JOB_COMPANY | JOB_LOCATION | JOB_SALARY | ------------------------------------------------------------------- | ENGINEER | GOOGLE | SAN JOSE | 5000 | | MANAGER | AMAZON | NYC | 8000 | | DELIVERY MAN | AMAZON | WASHINGTON DC | 2000 | | ACCOUNTANT | MICROSOFT | SFO | 4000 | | SALES LEAD | GOOGLE | SFO | 5000 | | DESIGNER | GOOGLE | NYC | 3500 | | CHEF | GOOGLE | NYC | 2500 | ------------------------------------------------------------------- I would like to display the following output on my template: COMPANY NAME ALONG WITH THE NUMBER OF JOBS BEING OFFERED AT THE COMPANY IN DESCENDING ORDER AS SHOWN BELOW. GOOGLE (4) AMAZON (2) MICROSOFT (1) Thank you so much for your time and help! -
take a choice off if the name starts with A Django
thanks for your time: i'd like to take one choice option off if the name of the People starts with letter 'a': basically if People.nome or (Animal.pessoa) starts with letter 'A' i'd like to take the choice (2,'GATO') off. is there a way to do that or should i try another aproach besides a ChoiceField from django.db import models from django.core.validators import RegexValidator class People(models.Model): nome = models.CharField(max_length=200) birthday_date = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) def cant_have_cat(self): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] self.maiusculo = self.pessoa.upper if self.maiusculo[0] == 'A': self.tipo != 2 return field_choices class Animal(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) name = models.CharField(max_length=100) tipo = models.IntegerField(choices=cant_have_cat) custo = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return '%s %s' % (self.pessoa, self.name) forms.py class AnimalForm(forms.ModelForm): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] name = forms.CharField(max_length=100) tipo = forms.ChoiceField(choices=field_choices) custo = forms.DecimalField(max_digits=7, decimal_places=2) class Meta: prefix = 'animal' model = Animal fields = ('name', 'tipo', 'custo') def clean(self): people_name = self.People.nome upper = people_name.upper() if upper[0] == 'A': Animal.tipo != 2 -
How do I create a date range filter in a class based view?
My class based view in "views.py" class PostListView(ListView): model = Post.objects.filter(created__range=["2020-03-09", "2020-03-31"]) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] I have a variable "created" for when the post is created but dont know how to filter the post within a range. -
Django migrations for custom types
I would like to extend django migrations functionality - for legacy project. I am trying to do is create migrations for example for custom Enum types, which are already defined inside the DB. I used django's customized introspection command to extract all the details required to build up Enum structure inside my django project. The important thing is that Enum type inside my django project is a customized django.db.models.fields.Field. The structure of the Enum type and its implementation details are not that important to this issue. The problem is when it comes to executing makemigrations and migrate. Django django.apps.apps registry stores only models, which are registered in the ModelBase metaclass. Which in turn does not allow me to inspect my Enum types. How could I extend django migrations functionallity without monkey patching all things suchas django.apps.Apps, django.db.migrations.state.ProjectState etc. ? The only other way I can think of is to create totally custom app that would mirror all files from Django migrations system, with customized classes for registry and state etc. But this would probably break if there is an update of Django, not to mention its not ideall solution to copy&paste all modules. Update 1 I thought I create a … -
Django filter relationship in models.py
Assuming the following scenario at 2 seperated apps where i want to count() the number of posts at my template: Categories/models.py class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=20, verbose_name="Title") ... @property def posts(self): return Post.objects.filter(category_id=self.id).count() Posts/models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title") content = models.TextField(verbose_name="Content") tag = models.CharField(verbose_name="Meta", max_length=70, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) template.html: <h5>Number of Post elements: {{ category.posts }}</h5> sadly this always results in the following error: ImportError: cannot import name 'Post' from partially initialized module 'Posts.models' (most likely due to a circular import) -
Django migrations throws ORA-00955 error when using oracle database
I'm stuck in a weird situation where I have to be using an oracle database along with Django. Before I get started I would like to mention that I run the database from inside a docker container. The problem that I've stumbled upon is that even though the database is up and running, I initialised a connection with DataGrip to it and it works just fine when it comes to Django everything blows up. This is how I configured the database inside Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'localhost:1521/ORCLCDB.LOCALDOMAIN', 'USER': 'terkea', 'PASSWORD': 'test', } } But when I run python manage.py makemigrations python manage.py migrate it throws up this error Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, … -
How to correctly show tags from TaggableManager via Crispy forms?
When I edit the form, then unloading the attached tags to this object and get a list on the HTML template <div class="col-md-6"> {{ form.tags|as_crispy_field }} </div> [<Tag:Sport> ,<Tag:Music>] models.py class NewsForm(ModelForm): class Meta: model = News fields = ['Title', 'tags',] widgets = { 'tags': forms.TextInput(attrs={'data-role': 'tagsinput'}) } I think need to somehow call this method def get_tags(self): return self.tags.names() -
Creating sign in for custom model in Django
There are lots of methods to realize user authentication in Django. And I used model form to create a form and sign up process. Now I really have no idea about signing in. I can't use built-in login, because there is no relation between my model (it's called Account) and django's built-in User model. I want to get some advice about the way. Here are my codes: views.py: def sign_up(request): context = {} form = SignUpForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('/') else: form = SignUpForm(request.POST or None, request.FILES or None) context['form'] = form return render(request, "sign_up.html", context) models.py: class Account(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=60) username = models.CharField(max_length=30) password = models.CharField(max_length=60) university_name = models.ForeignKey( University, on_delete=models.CASCADE, blank=True, null=True) isPhysicalAccount = models.BooleanField(default=False) def __str__(self): return self.username forms.py: lass SignUpForm(forms.ModelForm): class Meta: model = Account fields = "__all__" def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) -
ManyToManyField breaking in Admin screens and shouldn't be
I have some models like this: class Category(models.Model): class Meta: ordering = ['name'] name = models.CharField(max_length=100) text = models.TextField(blank=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Tool(models.Model): name = models.CharField(max_length=30, null=True, default='') url = models.URLField(max_length=250, null=True, default='') image_url = models.URLField(max_length=250, null=True, default='', blank=True) about = models.TextField(default='', null=True, blank=True) tags = models.ManyToManyField( Tag, related_name="tools" , blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category1") altcategory = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category2") And everything seem ok, except when I go to add a tag to a Tool in the Admin screens. I can create a Tool and Tag but when I select a tag in the taglist in the Admin screens and Save I get: The above exception (syntax error at or near "ON" LINE 1: ...ls_tool_tags" ("tool_id", "tag_id") VALUES (1, 2) ON CONFLIC... ^ ) was the direct cause of the following exception: with the sql: ('INSERT INTO "tools_tool_tags" ("tool_id", "tag_id") VALUES (%s, %s) ON ' 'CONFLICT DO NOTHING') The DEBUG screen is saying the error is at "tag_id", is strange... I hope it's not a version thing, since I'm using Heroku and have been really impressed with how everything "just works". My Django version is '3.0.4' …