Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make my comment form in Django to start working
I have a blog app and i am trying to add comments feature on the application, but it is not displaying properly, the comment form is suppose to display Name, Email and Body which is not showing... this is the picture in my web app Below is my view.py code from django.contrib import messages from django.contrib.auth.mixins import (LoginRequiredMixin, UserPassesTestMixin) from django.contrib.auth.models import User from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView) from .models import Post from django.core.files.storage import FileSystemStorage from .forms import PostForm, CommentForm from . import models def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def upload(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('post_detail') else: form = PostForm() return render(request, 'blog/post_detail.html', {'form': form }) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 6 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = … -
How to use http only cookie with django rest framework?
I read about some of the issues related to storing jwt token in local storage that's why I am trying to store token in http-only cookie. I am using following approach. from rest_framework.views import APIView from rest_framework.response import Response import jwt from django.conf import settings from rest_framework import status class LoginView(APIView): def post(self, request, format=None): email = request.data['email'] password = request.data['password'] # dummy user authentication if email == 'email' and password == 'password': encoded = jwt.encode( {'email': email}, settings.SECRET_KEY, algorithm='HS256') response = Response() response.set_cookie(key='token', value=encoded, httponly=True) response.data = { 'user': email, } return response else: return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED) Question 1: Is this a right approach to set httponly cookie using django rest framework? response = Response() response.set_cookie(key='token', value=encoded, httponly=True) response.data = { 'user': email, } return response After this every time when I am getting a request from the client (using React with axios) I am able to access the cookie using request.COOKIES['token'] in django view. Using this I can write my own function for authentication but I don't think it is a perfect approach because generally, we pass token in Authorization headers which sets the request.user based on the token and if I use this approach I … -
Can I annotate a field based on the state of another row?
Given the following models (simplified for illustrative purposes): class Item(models.Model): order = models.PositiveIntegerField() ... class Response(models.Model): student = models.ForeignKey(...) is_viewed = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) ... I need a list of Items, with certain fields from their related Response (if it exists) for a given Response.student (i.e. I want to know information about the item, as well as any information related to what the given student has responded to it). The following query seems to do just that. In reality, I need more than just is_viewed, but again...simplification. Item.objects.filter( responses__studentparticipation=studentparticipation ).values("responses__is_viewed") This all seems to work fine. There is a business rule that dictates that an Item should only be viewable for a student if the student has viewed the previous (according to Item.order) Item. Thus, for each Item in my QuerySet, I need an 'is viewable' status: For each Item: If a Response object does not exist for the previous Item, we assume that the previous Item has not been viewed, thus the current Item is not viewable. If a Response object does exist for the previous Item, the 'is viewable' status for the current Item depends upon the previous Item's matched Response's is_viewed field. If no previous … -
How to display uploaded PDF file in django adminsite
I want to display uploaded(via FieldField) pdf file at Django adminsite. Without displaying pdf file, it's download automatically. Bellow, I share my code what I am trying: models.py file: from django.db import models from common.models import SubCategory,QuestionHistory # Create your models here. class BigotoBochor(models.Model): question_history = models.ForeignKey(QuestionHistory,on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE) pdf_file = models.FileField(upload_to='bigotobochor') admin.py file: from django.contrib import admin from .models import BigotoBochor from django.utils.safestring import mark_safe # Register your models here. @admin.register(BigotoBochor) class BigotoBochorAdmin(admin.ModelAdmin): list_display = ('question_history','subcategory','embed_pdf_file',) # list_editable = ('published',) list_filter = ('subcategory','question_history__board__name','question_history__year',) search_fields = ('question_history__year','question_history__board__name') list_per_page = 25 # profile pic def embed_pdf_file(self,obj): if(obj.pdf_file != None and obj.pdf_file != "" ): return mark_safe('<embed src="{0}" type="application/pdf" width="50%" height="400px"/>'.format(obj.pdf_file.url,)) embed_pdf_file.short_description = 'Question' How to display pdf file in adminsite? -
How to add a customized link/url field in Django admin panel?
in Django admin.py, how to add a customized link/url field download_pdf into the admin view? class CustomerAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'full_name', 'download_pdf'] def full_name(self, obj): return obj.first_name + " " + obj.last_name def download_pdf(self, obj): return "<a href=''>PDF</a>" # this is not working the above code is not working, the download_pdf field shows as text but not a link. -
Rest-framework ID issue on React frontend to display data in a "color yes, color no" mode
I am trying to build an API server with Django and React as frontend. I'm having an issue with the id I'll be using to display the publications on my React page. My goal is to display a "color yes, color no" background (black, white, black, white ... for instance). In React I have this so far: {news && news.list.map((item) => { return( <NewsPiece key={item.id} title={item.title} active={item.id % 2 === 0 ? true : false} #when active, white, otherwise black /> ) })} This is my modal in Django. class Publication(models.Model): title = models.CharField(max_length=250, blank=False, null=False) subTitle = models.CharField(max_length=500, blank=True, null=True) author = models.CharField(max_length=100, blank=True, null=True) inter = models.BooleanField(default=False, null=True) #if my publication is in english or not created_at = models.DateTimeField(default=timezone.now) And below is my serializer: class PublicationMiniSerializer(serializers.ModelSerializer): newsPaper = NewsPaperSerializer(many=False) columnist = ColumnistSerializer(many=False) class Meta: model = Publication fields = ('title', 'id', 'created_at') And this is a short example of what my DB look like: ------ id: 1 #display color would be black as id % 2 === 0 is false Title: esse é o título #(this is the title in pt-br :)) inter: false ------ id: 2 #display color would be white Title: this is the title inter: … -
Django form is not considering initiial form data correctly on foreignkey
I am currently trying to prefill a form with initial values and so far a CharField and a IntegerField works like a charm. My main issue occurs when overwriting the Queryset that comes to the "foreign key" field. initials = { "title": self.title, #works "description": self.description, #works "category": mycustomchoicefield, #doesnt work "price": float(self.prices.last().value), #works } Everything looks ok until this runs: self.initial.update(initials) What's happening is that the full queryset gets returned instead of the "reduced" queryset with only the values I want. mycustomchoicefield = forms.models.ModelChoiceField(reducedQuerySet) Where should I be looking into? I've been doing pdb.set_trace but I am quite lost on where else to modify my code. This runs on my forms.py file and my views.py is not affecting ¡. -
how to display these results from tweepy in an array format suitable to jquery
class TweetAnalyzer(): """" Class for tweet analysis """ def tweet_to_data_frame(self, tweets): df = pd.DataFrame(data=[tweet.text for tweet in tweets ], columns=['tweets']) df['id']= np.array([tweet.id for tweet in tweets]) df['len'] = np.array([len(tweet.text) for tweet in tweets]) df['date'] = np.array([tweet.created_at for tweet in tweets]) df['source'] = np.array([tweet.source for tweet in tweets]) df['likes'] = np.array([tweet.favorite_count for tweet in tweets]) df['retweets'] = np.array([tweet.retweet_count for tweet in tweets]) df['in_reply_to_screen_name'] = np.array([tweet.in_reply_to_screen_name for tweet in tweets]) df['in_reply_to_status_id'] = np.array([tweet.in_reply_to_status_id for tweet in tweets]) df['in_reply_to_user_id'] = np.array([tweet.in_reply_to_user_id for tweet in tweets]) #the loops are essential in the data presentation ('for tweet in tweets') print(json.dumps(df, indent=4, sort_keys=True, default=str)) return json.dumps(df, indent=4, sort_keys=True, default=str) -
Postgresql How to Search billion float array with similarity
I have a 8 billion vector data, I want to use a vector to search the top 10 nearest vector My Vector is 256 float array ex. [ -1.424556434, 2.54513413553, -0.34351354.........] I already use this to get all a b distance. but it is Brute-force Substring Search np.dot(vector, b) / (np.linalg.norm(a) * np.linalg.norm(b)) -
Foreign Key With Groups of Reference Model
Consider the following scenerio: You are building Django for slack where there are multiple groups of people: Group 1: John Lizzy Mya Group 2: Oliver Taylor If I have a Message model that has a foreign key to a Group and a User in a group. In admin, how do I make it so that the User foreign key only allows selection from users in the Group? Thanks! -
Chaining Filter in Django in another statement
I have been searching about how to chain Django Filters and I understood the examples given by the docs. But it does not show the equivalent of this filtering. queryset = Blog.objects.filter(entry__headline__contains='Lennon') queryset = queryset.filter(entry__pub_date__year=2008) Is this the same as this? Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008) Since it filters first the blogs with headline Lennon and then from the filtered blogs, it will filter again with pub date 2008. So basically it only returns Blogs with Lennon as the headline and with a pub date 2008 Or this? Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) Since it is just like making the second filter on a new line. -
Unknown field error with the reverse side of a many to many field in forms.ModelForm for the reverse model
I have two models in two apps. AppTwo.ModelTwo has a M2M to AppOne.ModelOne. ...AppOne.py class ModelOne(models.Model): some fields team = FK TO THE TEAM ...AppTwo.py class ModelTwo(models.Model): team = FK TO THE TEAM models = models.ManyToManyField( "appname.ModelOne", blank=True, related_name="all_the_models") Those work great until i try to make a ModelForm for AppOne.ModelOne. class ModelOneAddModelTwoForm(forms.ModelForm): def __init__(self, team, *args, **kwargs): super(ModelOneAddModelTwoForm, self).__init__(*args, **kwargs) self.fields["all_the_models"].widget = forms.widgets.CheckboxSelectMultiple() self.fields["all_the_models"].help_text = "" self.fields["all_the_models"].queryset = ModelTwo.objects.filter(team=team) class Meta: model = ModelOne fields = ['all_the_models', ] The team is passed in via the get_form_kwargs on the view that calls the form. When I try to use the UpdateView that calls that form, I get this error: django.core.exceptions.FieldError: Unknown field(s) (all_the_models) specified for ModelOne I can't for the life of me figure out what I'm doing wrong. I have tried configuring this three ways to sunday but I can't see it. I can see it in the Django Model Documentation for the model in /admin/docs/model/appone.modelone/ but outside of that I can't get that field to load. It does load perfectly fine on the form for the model that the relationship is defined on. What am I missing? -
How can I have two WSGI Daemon Processes for two Django Apps at the same time
I need to server two Django Apps with Apache and I'm using standard procedure on serving wsgi.py using Apache. My first Daemon Process is this: WSGIDaemonProcess app1 user=www-data group=www-data threads=50 python-home=/usr/bin/python3.6 My second Daemon Process is this: WSGIDaemonProcess app2 user=www-data group=www-data threads=50 python-home=/usr/bin/python3.6 I understood from trial and error that they can't have the same user and group and that If I do what I have done above, one app will function properly and the other will go down. How could I make this work? -
Django JsonResponse: User matching query does not exist
So I´ve tried to make an ajax for my models but it is giving me a matching query does not exist, here is the full error: Internal Server Error: /messages/notification/ Traceback (most recent call last): File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\detail.py", line 106, in get self.object = self.get_object() File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\views.py", line 26, in get_object obj, created = Thread.objects.get_or_new(self.request.user, other_username) File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\models.py", line 29, in get_or_new user2 = Klass.objects.get(username=other_username) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 415, in get raise self.model.DoesNotExist( django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. HTTP GET /messages/notification/ 500 [0.16, 127.0.0.1:56012] Also here is my code: models.py class ProfileImage(models.Model): """ Profile model """ user = models.OneToOneField( verbose_name=_('User'), #to=settings.AUTH_USER_MODEL, to = User, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') notifications = models.FloatField(default='0') views.py def notifications(request, user_id, *args, **kwargs): user = User.objects.get(pk=user_id) user.profile.notifications … -
Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts/user/(?P<user_id>[0-9]+)/$']
NoReverseMatch at /bookdetail/1/ Reverse for 'user' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts/user/(?P<user_id>[0-9]+)/$'] I'm getting an error when I try to view a detail of a book at http://127.0.0.1:8000/bookdetail/1/. It's strange because I do not even call for user in my html page. As you can see, at this point, I'm just calling the book title. I've been trying to solve this issue for a couple of days with no luck. Does anyone see anything that could throw this error? views.py def book_detail_view(request, book_id): obj = get_object_or_404(Book, id=book_id) context = {'object': obj, return render(request, "bookexchange/book_detail.html", context) urls.py app_name = 'bookexchange' urlpatterns = [ path('', home_view, name='home'), path('list/', item_list_view, name='item-list'), path('detail/<int:item_id>/', item_detail_view, name='item-detail'), path('update/<int:item_id>/', item_update_view, name='item-update'), path('delete/<int:item_id>/', item_delete_view, name='item-delete'), path('bookdetail/<int:book_id>/', book_detail_view, name='book-detail'), ... book_detail.html {% extends 'base.html' %} {% block content %} <p>{{ object.title }}</p> models.py class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=500) def __str__(self): return self.title def get_absolute_url(self): return reverse("bookexchange:book-detail", kwargs={"book_id": self.id}) -
Problems importing from parent Package
That is what my directory looks like. I am running closepoll.py and in closepoll.py i am trying to import models.py . I am importing it like so: from polls.models import Question as Poll but i get this error: ModuleNotFoundError: No module named 'polls' . I have also tried importing like so: from ...models import Question as Poll and got this error: ImportError: attempted relative import with no known parent package. -
Not able to display entire table from MySQL database in Django
I am new to Django and I am trying to display MySQL DB table from MySQL workbench. But only one column is getting displayed and I not sure why? Can anyone suggest any solutions for this? -
Implement different serializing strategy for HTTP methods
With the model and serialzier listed below: # Django Model class class Model(models.Model): id = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=30) # DRF serializer class class ModelSerializer(serializers.ModelSerializer): class Meta: fields = ["id", "name"] model = Model How to implement the serializer to accept and validate the id field for HTTP POST requests (it should be unique and at most 10 characters) but for PUT requests the unique validation should be skipped and just be checked len(id) <= 10. I am looking for an idiomatic, clean and efficient way to do this. -
The url() function in Django has been deprecated - Do I have to change my source code?
The url() function in django has been deprecated since version 3.1. Here's how backwards compatibility is being handled; def url(regex, view, kwargs=None, name=None): warnings.warn( 'django.conf.urls.url() is deprecated in favor of ' 'django.urls.re_path().', RemovedInDjango40Warning, stacklevel=2, ) return re_path(regex, view, kwargs, name) For now, re_path() is returned when the url() function is called. When the function is completely removed, will the projects that use it have to change their source code? -
Django - legacy DB with no write, custom user model - possible?
Is there a way to create a custom user model using a table from a legacy database without writing any changes to the legacy DB in Django? I have a legacy database that I have got my models from using inspectdb. One of these tables I would like to use as my custom user model which I've been able to set up and set this model as the AUTH_USER_MODEL I don't want to write the django tables to my legacy DB so I've created another db - setting this as default in my settings.py file. I've set up a router.py script very similar to this https://datascience.blog.wzb.eu/2017/03/21/using-django-with-an-existinglegacy-database/ but when I tried to run this I got this error: django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Foreign key 'django_admin_log_user_id_c564eba6_fk_Users_UserID' references invalid table 'Users'. (1767) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)") I think I get this error because i'm not allowing writing to the legacy DB and the user table isnt in my second DB for the Django tables. Any thoughts how I can aroud this? Thanks in advance -
How to access updated Django variables in templates' Javascript?
I have the following variable in my room.html template: {{ participants | json_script:"participants"}} Suppose the variable has been changed in my views.py after the user enters the view, how can I access the updated variable in my Javascript? I have considered auto-refreshing the view periodically, but I'm concerned it would make the users uncomfortable. -
What's the difference between Django Framework and Django CMS?
Good day everyone, I just started learning Python 4 months ago and have made games with Pygame using OOP. I just started 2 weeks ago learning Django, following some tutorials online along side the Django documentation. The docs are really cool actually. My goal is to become a fullstack web developer capable of doing a full website that you can buy products from a business, e-commerce and other blog style pages etc for local businesses and hopefully one day my own business. I have read there is Squarespace, Wix, Wordpress etc to create websites using drag&drop features for people who can't code and know zero about coding. What is the difference between the Django framework I am learning and "Django CMS"? I've read CMS stands for "Content Management System"... Is Django CMS like Wordpress? Wix? Squarespace? When to use Django framework (coding from scratch, making models, views, templates etc) and when to use "Django CMS"? I started learning python because I want to get into 3 fields of programming: 1. Web development (full e-commerce + users + blog website) 2. Robotics (teaching kids about robotics and solving community problems with automation) 3. Mobile Apps (business ecommerce app and capable of … -
Django: How to update multiple rows in admin table?
i got the next problem: I want tu update the "TOTAL PAGADO" field with the previous column "PRECIO TOTAL" by selecting multiple rows and then apply an action called "Saldar precio". enter image description here and the return is that: enter image description here i've been trying something like that: total_pagado = queryset.update(total_pagado= queryset[0].get_precio_total()) I know that the problem here is that 0, that only return the first selected value, but i dont know how to solve it. It's my first time doing a question here so sorry if i'm breaking some posts rules (and sorry for my english) Thanks! -
Django cannot unpack non-iterable Profile object error
i am trying to create multiple appoinments for a user and anytime i do it i get this error. Traceback (most recent call last): File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\core\models.py", line 47, in create_appointment appointment,created = cls.objects.get_or_create(patient=patient,hospital=hospital) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 573, in get_or_create return self.get(**kwargs), False File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 436, in get num if not limit or num < limit else 'more than %s' % (limit - 1), During handling of the above exception (get() returned more than one Appointment -- it returned 2!), another exception occurred: File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\dashboard\views.py", line 31, in bookapp Appointment.create_appointment(hospital,request.user.profile) File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\core\models.py", line 49, in create_appointment appointment = cls.objects.filter(patient).order_by('id') File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q split_subq=split_subq, check_filterable=check_filterable, File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1255, in build_filter arg, value = filter_expr Exception Type: TypeError at /dashboard/connect/add/2/ … -
Django with Postgres AutoField increment from maximum number of already existing data
I'm building an app with an Angular frontend and django with postgres backend. The app is mainly for data entry into a database with a fairly straightforward schema. Each table in the database has an AutoField primary key which increments with each new record created in that table. I used migrate to get the schema from models.py reflected in postgres, which worked perfectly fine. From there I then uploaded already existing data directly into postgres. Data going forward will be entered via the app. The problem is, I thought the AutoField would increment from the max primary key, but whenever I enter a new record, either via an Angular form or directly in django, it is incrementing from 1 for every table, even if an ID 1 already exists in the table, and gives me an error. The only table that doesn't give an error is because the IDs there start from 1000000, so 1 isn't already taken. How would I go about adjusting this so it increments from the maximum value? I've seen some solutions about changing where it increments from using ALTER statements, but I don't want to change anything that already exists in the data as it …