Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accidentally deleted django project database, now I cannot access mysql
I am developing a project on Django, and was working on a project named project, which I deleted via DROP DATABASE *project* to start over from scratch, thinking I could simply create a new one via CREATE DATABASE *project*. The problem I'm having is that now, no matter what command I run: python manage.py migrate mysql (sudo) mysql -u root I get the same error: ERROR 1049 (42000): Unknown database '*project*' So, I cannot even access mysql to create a new database. Any ideas? -
How to post out of model fields django forms
How to post a checkboxFiled without django user.contrib fields in forms forms.py class Meta: model = User fields = ("user_type","email","password1","password2",'is_email_promotions') widgets = {'is_email_promotions':forms.CheckboxInput()} #it is out of user model also not related any model -
Django - nested query to reply on comments
I have the following two models to make it possible that users can answer/reply onto a comment class Comment(models.Model): objects = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Comment_Answere(models.Model): objects = None id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) Creating a reply works like a charm but I don't know how I properly pull all answers/reply's for a specific comment at my template/View def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) list_comments = Comment.objects.get_queryset().filter(post_id=pk).order_by('-published_date') # not sure how the comment_answers query has to look like comment_answers = Comment_Answere.objects.filter(post_id=pk).order_by('-published_date') paginator = Paginator(list_comments, 10) page = request.GET.get('page') comments = paginator.get_page(page) args = { 'post': post, 'comments': comments, 'comment_answers': comment_answers, } return render(request, 'post_detail.html', args) At my template I later than do something like this: {% for comment in comments %} {% for comment_answer in comment_answers %} {% endfor %} {% endfor %} Would be awesome if smb. could give me a hint on how I have to stack comments and there reply's together as I currently have all reply's … -
Cannot run paho mqtt client -> “ImportError: cannot import name 'client' "
I installed Eclipse Paho, clone the repository and install whit these comands: pip install paho-mqtt git clone https://github.com/eclipse/paho.mqtt.python cd paho.mqtt.python python setup.py install it's ok. but when i run the project, i have this error: File "/home/andrius/Scrivania/django_python/CalendarEsit/Calendar/__init__.py", line 1, in <module> from . import aws_iot File "/home/andrius/Scrivania/django_python/CalendarEsit/Calendar/aws_iot.py", line 10, in <module> from paho.mqtt.client import client ImportError: cannot import name 'client' -
How to fix ? IntegrityError at /profiles/profile/ NOT NULL constraint failed: profiles_userprofile.user_id
I am using Django 3.0.3 and python 3.8.5 I am running through an error :IntegrityError at /profiles/profile/ NOT NULL constraint failed: profiles_userprofile.user_id Can you anyone tell where I am actually making mistake ? I am trying with the code given. profile/models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(("First Name"), max_length=50) last_name = models.CharField(("Last Name"), max_length=50) profile_pic = models.ImageField(upload_to='Displays', height_field=None, width_field=None, max_length=None) phone_number = models.IntegerField(("Phone Number")) email = models.EmailField(("Email Address"), max_length=254) city = models.CharField(("City"), max_length=50) bio = models.CharField(("Bio"), max_length=50) def __str__(self): return self.email def get_absolute_url(self): return reverse("profiles:userprofile_detail", kwargs={"pk": self.pk}) def create_profile(sender, **kwargs): if kwargs['created']: profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) profiles/forms.py class Meta: model = UserProfile fields = ("profile_pic","first_name","last_name",'email',"phone_number","bio","city",) def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['first_name'].label = 'First Name ' self.fields['last_name'].label ='Last Name ' self.fields['profile_pic'].label = 'Profile Picture' self.fields['phone_number'].label = 'Phone No. ' self.fields['bio'].label ='Bio' self.fields['city'].label ='City' self.fields['email'].label = 'Email Address' profiles/views.py class UserProfileCreateView(CreateView): redirect_field_name = 'profiles/userprofile_detail.html' form_class = UserProfileForm model = UserProfile def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["created"] = 'created' return context class UserProfileDetailView(DetailView): model = UserProfile class UserProfileUpdateView(UpdateView): redirect_field_name = 'profiles/userprofile_detail.html' form_class = UserProfileForm model = UserProfile profiles/userprofile_form.html {% extends 'base.html' %} {% block content %} {% if 'created' in created %} <a href ="{% url 'profiles:update' pk=userprofile.pk … -
SMTP data error.550 b the form address doesn't match a verified sender identity
I am trying to send mail in my django project. Whenever I try to send email it shows the error like the screenshot. here I generated API in sendgrid and used it in my project. And I also disable two step verification in my email and allow less secure app enable. My setting is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = "this is the API_KEY that I generated in sendgrid" EMAIL_PORT = 587 EMAIL_USE_TLS = True -
Django Channel Error wile building a chat application
I am trying to build a chat application using Django and channel. But I am getting not able to get my view file (room.html) My main project name is "techChat" and I have a app called "chat" I ma trying all this code from :- https://channels.readthedocs.io/en/latest/tutorial/part_2.html When i enter the lobby name i get page not found. I also have the asgi file if you take a look at my file structure whose img is below. Help! My Code views.py :- chat/urls.py (App urls file):- techChat/urls.py (main project urls file) My room.html template file:- My index.htm file template My Index Page output :- Now when I Enter the "lobby" in the text box I get Page Not Found Error! -
i have a problem with load lazy pagination in my django website
this is my views.py in the views.py i have some filter like this: def home8(request): context = {} qs=Post.objects.all().order_by('-pub_date') city = request.GET.get('city') area= request.GET.get('area') def is_valid_queryparam(param): return param != '' and param is not None if is_valid_queryparam(city): qs1=qs.filter(city=city) if is_valid_queryparam(area): qs1=qs.filter(area=area) paginator = Paginator(qs1, 8) page_request_var = "page" page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context['queryset'] = paginated_queryset return render(request, 'index.html',context) and in my index.html i set this code to loadlazy pagination by scroll {% if queryset %} {% for post in queryset %} <div class=" col-12 col-md-6 col-lg-4 infinite-item px-1 mb-3" id="col"> <div class="card " id="card"> <div class="card-horizontal "> <a href="{{ post.get_absolute_url }}"> <img src="{{ post.image1.url }}" class="card-img-top " /> </a> <div class="card-body " > <h5 class="card-title text-truncate">{{ post.title1 }}</h5> <span class="text-muted">{{post.whenpublished}}</span> </div> </div> <div class=" card-footer"> <div class="row" id="place"> <span class="text-truncate place" ><i class="fa fa-map-marker" aria- hidden="true"></i> {{post.city}} | {{ post.area }}</span> <span class="price float-left mr-auto" >{{ post.after_off1|intcomma }}<span class="org"> </span></span> </div> <div class="row"> <div id="badge "> <span class="badge badge-pill float-right " style=""><span class="percent"> ٪{{ post.off1 }} </span> </span> </div> {% if post.original_amount1 %} <s class=" org-price text-muted float-left mr-auto" >{{ post.original_amount1|intcomma }}<span class="off"> </span></s> {% endif %} … -
How to append img src and it's url in jquery for ajax view in django?
I want to use ajax where user can post image or text . But first i have to show ajax list which i don't know how to. this is the post i want to append to jquery for ajax view. It has image of the author of the post and the title and img posted by user. {% for object in object_list %} <div class="post-card" > <p> <img class="rounded-circle profile-image" src="{{ object.author.profile.image.url }}"> <span class="auth-span"><b>{{ object.author }} </b><i class="fa fa-check-circle"></i> </span> <span class="date-span">{{ object.date_created|timesince }} ago</span> </p> <p><a href="{% url 'detail' object.id %}" class="title">{{ object.title }}</a></p> <div> {% if object.Image %} <p><a href="{% url 'detail' object.id %}"><img src="{{ object.Image.url }}" class="img-fluid" alt="Responsive image" ></a></p> {% endif %} </div> <div class="icon-div" > <p class="icon" style="mt"> <i class="fa fa-comments"></i> <i class="fa fa-heart" ></i> <i class="fa fa-share-square"></i> <i class="fa fa-eye"></i> </p> </div> </div> {% empty %} {% if request.GET.q %} <p style="color: var(--text-color);margin-top: 20px;margin-left: 250px;">NO tweets found</p> {% else %} <p>NO tweets yet.</p> {% endif %} {% endfor %} I have already setup serializers and others and it worked fine. Every img and post is working fine without ajax . So all i want to know is the method to append the elements … -
How to Display value in Drop-down in Django Template?
I am trying to display value in dropdown from databse, and I am getting value through id, but it's displaying only one value which is save in my database. But i want all dropdown value. Please let me know how i can display all values in dropdown. Here is my models.py file where dropdown code is written... TYPES = [ ('A', 'Active'), ('D', 'Not Active'), ] and these values are savingin another modes using choices,and A and D are storing in my Database. Here is my views.py file.. def getdata(request, id): display=Mymodel.objects.filter(pk=id).first() context={'display':display} return render(request, 'page.html', context) and here is my page.html file where I am displaying data in dropdown.. <select name='types'> <option value="{{display.types}}">{{display.get_types_display}} </option> </select> but this is displaying in dropdown Active values only, but i want both values, I want to edit data using this form. ANd if A is saved in my database then in default Active should be select and if D is saved in my database then Not Active should be select in default, rest values should be display in dropdown. -
Unexpected models generated by `model_bakery` in Django unit test
I've used model_bakery (and before that, model_mommy) a fair amount, so this bug is making me feel like I'm taking crazy pills. from model_bakery import baker # BaseTestCase inherits from django.test.TestCase # it creates a tenant object assigned to self.tenant in BaseTestCase.setUp class TestSchemas(BaseTestCase): def setUp(self): super().setUp() self.assertEqual(Tenant.objects.count(), 1, "This one passes") self.assertTrue( Tenant.objects.filter(pk=self.tenant.pk).exists, "The only tenant I expect is here, persisted, and correct." ) self.campaign_schema = baker.make( "Schema", tenant=self.tenant, ) # This is the failing assert self.assertEqual( Tenant.objects.count(), 1, "This case fails. I _expect_ no additional Tenant objects to have been created." ) from django.db import models class Tenant(models.Model): tenant_xid = models.BigIntegerField("Tenant ID", primary_key=True) class Schema(models.Model): form_schema_xid = models.BigIntegerField("schema ID", primary_key=True) tenant = models.ForeignKey( Tenant, models.CASCADE, db_column="tenant_xid", related_name="schemas" ) As indicated in the assertion messages, the setUp method starts off how I expect, with one Tenant object. I use baker to create a Schema. I expect the schema to use the existing Tenant, yet it seems to be creating a second one instead, as the final assert shows AssertionError: 2 != 1 I've simplified the case down to the bare minimum, but I'm struggling to understand what's happening. There aren't any overridden methods on the models, the BaseTestCase isn't … -
django rest framework - How can I edit the header with drf_yasg?
I develop an API with DRF and I implemented swagger in It throught drf_yasg. When I use swagger UI to test my endpoints, the basic header is not good enough. I need to add an acceptance parameter wich is the version of my API. -
how to upload multiple Image in Django
I am trying to upload multiple images in my Django project, but it is not working. Although, I have tried many things but there is no error. My HTML FILE <input type="file" class="form-control" name="photo" id="photo" accept=".png, .jpg, .jpeg" onchange="readFile(this);" multiple> My Models class MyGeneralModel(models.Model): some_name=models.CharField(max_length=50,blank=True, null=True) ..... Here I am generating dynamic file name. def get_image_filename(instance, filename): title = instance.image_for.some_name slug = slugify(title) unique_slug = slug return "scammer_images/%s-%s" % (unique_slug, filename) Here is my Image Model. class Images(models.Model): image_for = models.ForeignKey(MyGeneralModel, default=None,on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image',blank=True, null=True) And my views.py is here. The variable get is the instance of MyGeneralModel. for file in request.FILES.getlist('photo'): instance = Images.objects.create(image_for=get,image=file) -
How to pass a value to the template in class based views in django?
I want to send a value of a variable to a PostDetail template, Here's the function of the views.py file class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() obj.view_count += 1 obj.save() return obj def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) texts = self.object.content Read_Time=get_read_time(texts) print(Read_Time) return context Here's the output of the terminal:- [04/Sep/2020 19:29:04] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089 0:02:00 [04/Sep/2020 19:29:24] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089 I want to send the 0:02:00 to my template, How can I make this happen? -
Why Does Django Query to Check Uniqueness?
tl;dr: Why does Django's uniqueness check on INSERT require a SELECT query, and can I permanently disable it? I'm working to highly optimize a Django app that is writing to a PSQL database. I have a uuid column which is a primary_key as part of my model. It is the only unique field in the model. id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False, null = False, blank = False, help_text = 'The unique identifier of the Node.' ) The issue I'm encountering is that when attempting to save a new item, Django automatically performs a uniqueness check query prior to the insert: SELECT (1) AS "a" FROM "customer" WHERE "customer"."id" = \'1271a1c8-5f6d-4961-b2e9-5e93e450fd4e\'::uuid LIMIT 1 This results in an extra round trip to the database. I know that the field must be unique, but of course Django has already configured this at the database level - so if it tries to insert a row with a non-unique field it will get an error. I've implemented a workaround which suppresses the query by adding the following to my model: def validate_unique(self, *args, **kwargs): # Make sure that we never validate if ID is unique. Duplicates OK. current_exclude … -
Annotate count of related related filtered objects
I have these models: class Shop(..): category = ForeignKey... class Product(..): category = ForeignKey... is_active = BooleanField... class Category(..): name = ... I need to annotate the number of active products for each category. Basically this: for cat in Category.objects.all(): count = Product.objects.filter(shop__category=cat) I tried: Category.objects.annotate(product_count=Count('shop__products'),filter=Q(shop__products__is_active=True)) django.core.exceptions.FieldError: Related Field got invalid lookup: is_active This raises an error. Do you know how to annotate this? -
Convert SQL query in Django model format
I'm trying to convert an SQL query into django format but as I'm quite new to django I'm having some trouble. My query: select make_name, count(*) as count from main_app_make as make join main_app_model as model on make.id = model.make_id join main_app_vehicle as vehicle on model.id = vehicle.model_id group by make.make_name The result: Audi 1 Mercedes-Benz 2 My models: class Make(models.Model): make_name = models.CharField(max_length=50) make_logo = models.CharField(max_length=400) def __str__(self): return self.make_name class Model(models.Model): model_name = models.CharField(max_length=50) make = models.ForeignKey(Make, on_delete=models.CASCADE) def __str__(self): return self.model_name class Vehicle(models.Model): type = models.ForeignKey(VehicleType, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) body_type = models.ForeignKey(Body, on_delete=models.CASCADE) ... This is what I tried: options = Make.objects.all().values('make_name').annotate(total=Count('make_name')) -
Call not yet defined Model's manager in predefined Model Method Django
I have 2 models: class Person(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Message(models.Model): sender = models.ForeignKey(Person, related_name='messages_sent', on_delete=models.CASCADE) recipient = models.ForeignKey(Person, related_name='messages_recieved', on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text Notice Person was defined before Message. I can reference Message before it's definition in Person if I use a ForeignKey like so: class Person(models.Model): myfield = models.ForeignKey('message', on_delete=models.CASCADE) to call a not yet defined Model before definition. But what's the best way to call a not yet defined Model in a previously defined Model's method? Example: class Person(models.Model): name = models.CharField(max_length=150) myfield = models.ForeignKey('message', on_delete=models.CASCADE) # First reference before definition def __str__(self): return self.name def send_message(self, message, recipient): sent_message = Message.objects.create(sender=self, recipient=recipient, text=message) # Second reference before definition in a method somehow? return sent_message class Message(models.Model): sender = models.ForeignKey(Person, related_name='messages_sent', on_delete=models.CASCADE) recipient = models.ForeignKey(Person, related_name='messages_recieved', on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text Is there a way to do this without defining the Person model below the Message model? If so, what'd be the best approach? Thanks in advance! -
Django authentication from mobile app using DRF API: how to?
I am neewbie in DRF. To resume, in one hand I have a Django web app with a Django authentication and a Django Rest API app layer. In the other hand, I have a Flutter mobile app. I would like users to be able to connect to mobile app using Django authentication and DRF API. below the start code for a very basic API, just to test the "concept" my first idea was to use a POST method even if I don't want to save record but just send data in Json format from mobile app to Django but as I could have expected I get an HTTP 400 Bad Request ("A user with that username already exists.") None of the APIView views match what I need so Should develop a simple API with pure Django? How should I do that? ***serializer.py*** class LoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] ***views.py*** class UserLogin(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): if get_object_or_404(User,username='admin'): pront('true') return True else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ***urls.py*** urlpatterns = [ path('user/', views.UserLogin.as_view(), name='user-login'), ] ``` -
xhtml2pdf not loading font's
Trying to load fonts with static. When rendering/loading page directly everything loads. But when loading as pdf it doesn't load the correct fonts! pdf.html (also yes I am loading static on pdf page. also yes link_callback is added as supposed.): @font-face { font-family: 'Mulish'; font-weight: 600; src: url("{% static 'fonts/Mulish-Regular.TTF' %}") } @font-face { font-family: 'Mulish'; font-weight: 700; src: url("{% static 'fonts/Mulish-Bold.TTF' %}") } html { font-family: 'Mulish' !important; } utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.CreatePDF(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8', link_callback=link_callback) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def link_callback(uri, rel): s_url = settings.STATIC_URL # Typically /static/ s_root = settings.STATIC_ROOT # Typically /home/userX/project_static/ m_url = settings.MEDIA_URL # Typically /static/media/ m_root = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ if uri.startswith(m_url): path = os.path.join(m_root, uri.replace(m_url, "")) elif uri.startswith(s_url): path = os.path.join(s_root, uri.replace(s_url, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (s_url, m_url) ) return path I know that adding a full URL path to src does WORK but it is not acceptable because I don't want to change path every single time I need to load something -
How to make and use custom template-loader in Django
I am trying to write a custom template loader in django which serves html templates which are present in a folder in my s3 bucket. Following is my custom_loader file from django.conf import settings from django.template import Origin, Engine from django.template.loader import TemplateDoesNotExist from django.template.loaders.base import Loader from boto3.session import Session from django.template import engines ACCESS_KEY_NAME = getattr(settings, 'AWS_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) SECRET_KEY_NAME = getattr(settings, 'AWS_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) TEMPLATE_BUCKET = getattr(settings, 'AWS_STORAGE_BUCKET_NAME') django_engine = engines['django'] template = django_engine.from_string("Hello {{ name }}!") class S3Engine(Engine): def __unicode__(self): return "s3_engine" def __str__(self): return "s3_engine" class Loader(Loader): is_usable = True def __unicode__(self): return "loader" def __init__(self, *args, **kwargs): django_engine = engines['django'] print(engines.all()) template = django_engine.from_string("Hello {{ name }}!") print(template) params = args[0] print(args) print('params', params) session = Session(aws_access_key_id=ACCESS_KEY_NAME, aws_secret_access_key=SECRET_KEY_NAME) s3 = session.resource('s3') self.bucket = s3.Bucket(TEMPLATE_BUCKET) super(Loader, self).__init__(*args, **kwargs) # self.engine = S3Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader) def getKeys(self): keys_objects = [] for obj in self.bucket.objects.filter(Prefix="media/festive_html/"): key = obj.key keys_objects.append({ 'key': key, 'object': obj }) return keys_objects def get_contents(self, origin): print(111111) print('origin', origin) try: keys_objects = self.getKeys() for key_object in keys_objects: print('origin', origin) print('key_object', key_object) if key_object['key'] == origin: return key_object['object'].get()['Body'].read() except FileNotFoundError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name, template_dirs=None): tried = [] # print('template_name', template_name) # … -
Append css while removing the previous css in multipage Django Dash application
I have implemented a multipage Dash Django application. I have two different apps and I want each app to have its own external css file. I tried to configure the css in each page app with app1.py cssStylesheets = ['app1.css', 'app1.bootstrap.css'] for stylesheet in cssStylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) app2.py cssStylesheets2 = ['app2.css', 'app2.bootstrap.css'] for stylesheet in cssStylesheets2: app2.css.append_css({ "external_url": '/static/' + stylesheet }) I also tried to configure the external css based on the pathname input received dash_app.py @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): cssStylesheets = ['app1.css', 'app1.bootstrap.css'] cssStylesheets2 = ['app2.css', 'app2.bootstrap.css'] for stylesheet in external_stylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) if pathname == '/app1/': for stylesheet in cssStylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) return app1.layout elif pathname == '/app2/': # for stylesheet in cssStylesheets: # app.css.append_css({ # "external_url": '/static/' + stylesheet # }) return app2.layout But the problem is that for the first time that it loads the page it gets the previous css (ex. Loading /app1 --> No css, Refresh app1 --> app1.css, Loading /app2 --> app1.css, Refresh app2--> app2.css) -
django testcase with --keepdb is not resetting object ids between tests
Recently I updated my django app, which was made with Python 2.7 and Django 1.11, to Python 3 and Django 3.1. I had several testcases using django.test.TestCase. Several of these tests were made assuming the database would be completely reset between test executions and, among other things, it was expected that the last id for the models would be reset as well, such as that if I create an object on a test and save it to the database, the object would always receive the same id starting from 1. This behaved exactly like this on Django 1.11, and I was able to use the --keepdb flag to avoid recreating the database everytime. However after I upgraded to Python 3 and Django 3.1 I noticed this is no longer the case. I noticed that all objects are deleted from the database after the test execution, but on next test executions the new objects are created with pk starting from the last used pk, so I can no longer count with the fact that the created objects will have a predictable pk. This leads to a really annoying behavior that if I run my test just after recreating the db the … -
Django and AJAX - replaceWith not replacing my element, it is adding it and not removing the original
I am doing an AJAX call on my django application to update data on the page without refreshing. When I submit the AJAX request and use replaceWith() the element I am trying to replace is getting added to the page, but not replacing the original. Simplified code: page.html <table> {% for form in formset %} <tr> <td>{{form.evidence}}</td> {% include 'detail.html' %} </tr> {% endfor %} </table> detail.html {% if obj %} {% if updated %} <td id='{{obj.id}}-detail' colspan=2>Updated</td> {% else %} <td id='{{obj.id}}-detail'>not updated</td> {% include 'save_container.html' %} {% endif %} {% else %} {% include 'save_container.html' %} {% endif %} save_container.html <div class='btn-group mr-1 mb-1'> <button id='{{ form.instance.id }}-save-button' action="{% url 'results:save_class' %}" type='button' class="btn btn-warning save-classification">Save</button> </div> views.py def save_class(request): data = dict() if request.method == 'POST' and request.is_ajax(): obj = Table.objects.get(id=request.POST['id']) form = Form(data=request.POST, instance=obj, saved=True) if form.is_valid(): ... save form to table ... data['form_is_valid'] = True obj = VariantClassification.objects.get(id=obj.id) data['html_detail'] = render_to_string( 'details.html', {'obj': obj, 'updated': True }) else: data['form_is_valid'] = False data['form_errors'] = form.errors.values() return JsonResponse(data) save.js $(function () { $(".save-classification").click(function () { var id = $(this).attr('id').replace('-save-button',''); var url = $(this).attr('action'); var var_n = $(this) var evidence = $(this).closest("tr").find("td." + id + '-evidence-cell').find("li.evidence-cohort-li").find("input.textinput").val(); // some … -
Uploading Files through django rest api
Question 1: I want the user to be able to upload files through the Api, I am using postman to test the api, here is my code: views.py: class FileUploadView(APIView): parser_classes= (MultiPartParser, FormParser) permission_classes = [permissions,] def post(self, request, *args, **kwargs): file_serializer = SLRSerializer(data= request.data) if(file_serializer.is_valid()): file_serializer.user = request.user return Response(file_serializer.data, status= status.HTTP_401_UNAUTHORIZED) else: return Response(file_serializer.errors, status= status.HTTP_400_BAD_REQUEST) models.py class SLRModel(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete= models.CASCADE, null= True) user_folder = models.FileField(upload_to= /path/to/folder, null= True) whenever I try to upload something through the api using postman, I dont get an error, but I get the following on postman: { "user_folder": null, "user": null } even though I am logged in, and have uploaded a file. Question 2: When I login into the admin dashboard, and then try to access the models from there. I get the following error message Error Message: OperationalError at /admin/App/model/ no such column: App_model.user_id Request Method: GET Request URL: http://localhost:8000/admin/App/model/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such column: App_model.user_id Thanks.