Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django APScheduler not executing jobs according to schedule with Apache and mod_wsgi
I have a Django project that uses django-apscheduler with the following configuration: Apache virtualhost WSGIPassAuthorization On WSGIScriptAlias / /some/app/wsgi.py WSGIDaemonProcess some-app \ user=someapp threads=15 display-name=some-app \ python-path=/some/app/venv/lib/python3.7/site-packages WSGIProcessGroup some-app Scheduled tasks from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job from administration.scheduled_tasks import add_db_backup, delete_old_db_backups scheduler = BackgroundScheduler(timezone=utc) scheduler.add_jobstore(DjangoJobStore(), 'default') register_events(scheduler) @register_job(scheduler, 'cron', hour='0', minute='0') def db_backups_job(): add_db_backup() delete_old_db_backups() scheduler.start() As expected, the scheduled job is visible in Django admin. Also, the jobs execute sometimes, for example the daily job above has executed seven times during this month, although today is 15th and it should thus have executed 15 times. Note that I have restarted Apache during this time. This seems to be a process lifetime issue. It seems that the mod_wsgi process is suspended and thus APScheduler jobs cannot run. What is the lifetime of the mod_wsgi process? How can I assure that the jobs execute according to schedule or at least daily? -
How Do I Load A Comments Form within the Blog Object View ? Or can those things somehow be loaded independently?
So I am in the process of creating a custom comments app for Django == 2.1 And I'd like to know how to load both the existing blog entry, and the comment form that will store the ContentType as blog instead of one of the other models which it can be associated with. The Method Resolution Order demands that that the leftmost View or mixin will be the one that is searched first for missing methods not declared within that respective View, or those Views that call the super().get() method ( form example ). Therefore I have concluded that the View for the Blog app should have the following code. blog/views.py class BLogTechObjectView(SingleObjectMixin, TemplateResponseMixin, BlogTechView): model = Blog slug_url_kwarg = 'blogtitle' template_name = 'extendsBlog.html' context_object_name = 'blog' slug_field = 'blog_name' def get(self, request, *args, **kwargs): blog = self.get_object() return render(request, 'extendsBlog.html', {'blog':blog}) comments/models.py class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() def __str__(self): return '{} made this comment on : {} '.format(self.user, self.timestamp) def __unicode__(self): return '{} made this comment on : {} '.format(self.user, self.timestamp) comments/views.py class CommentFormView(generic.CreateView): form_class = CommentForm success_url = None template_name … -
FATAL: password authentication failed for user / but user exist
I'm banging my head against a wall here. I need another set of eyes. This is error I get: django.db.utils.OperationalError: FATAL: password authentication failed for user "localproject" FATAL: password authentication failed for user "localproject" I have set up the database like this in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'project', 'USER': 'localproject', 'PASSWORD': 'MahPassword', 'HOST': 'localhost', 'PORT': '', } } And I have created the Scheme like this: postgres=# CREATE DATABASE project; Set the user like this: postgres=# CREATE USER localproject WITH PASSWORD 'MahPassword'; Set the priviligies for the scheme like this: postgres=# GRANT ALL PRIVILEGES ON DATABASE project TO localproject ; And the database list looks like this: postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+------------------------ project | postgres | UTF8 | en_CA.UTF-8 | en_CA.UTF-8 |=Tc/postgres + | | | | | postgres=CTc/postgres + | | | | | localproject=CTc/postgres Why on earth do I get the error? -
Django: Show View after password entry
How can I return a View only after letting the user enter a password which is checked against the link? class Foo(models.Model): url = models.CharField(max_length=10) #a randomly created ASCII-string name = models.CharField(max_length=10) password = models.CharField(max_length=10) url_patterns = [path('foo/<url>/admin', views.foo, name='foo_admin'),] So a user goes to url: localhost/foo/bar now he should enter the correct password to see the content of model Foo with url='bar'. -
How to map an existing python class to a Django model
I'm writing a web scraper to get information about customers and appointment times to visit them. I have a class called Job that stores all the details about a specific job. (Some of its attributes are custom classes too e.g Client). class Job: def __init__(self, id_=None, client=Client(None), appointment=Appointment(address=Address(None)), folder=None, notes=None, specific_reqs=None, system_notes=None): self.id = id_ self.client = client self.appointment = appointment self.notes = notes self.folder = folder self.specific_reqs = specific_reqs self.system_notes = system_notes def set_appointment_date(self, time, time_format): pass def set_appointment_address(self, address, postcode): pass def __str__(self): pass My scraper works great as a stand alone app producing one instance of Job for each page of data scraped. I now want to save these instances to a Django database. I know I need to create a model to map the Job class onto but that's where I get lost. From the Django docs (https://docs.djangoproject.com/en2.1/howto/custom-model-fields/) it says in order to use my Job class in the Django model I don't have to change it at all. That's great - just what I want. but I can't follow how to create a model that maps to my Job class. Should it be something like from django.db import models import Job ,Client class JobField(models.Field): description … -
Django Form Not Rendering HTML from class HomeForm
For some reason I cannot get my Django form to render. I'm not sure what I'm missing. I'm trying to get the class HomeForm(forms.Form) to render on the myaccount/change.html page and have been unsuccessful. I'm new to Django so I might be missing a small detail somewhere but I thought I got everything covered from the djago documentation. If anyone can help me out it would be gladly appreciated. Thanks! users/forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from .models import CustomUser class HomeForm(forms.Form): post = forms.CharField() your_name = forms.CharField(label='Your name', max_length=100) class CustomUserCreationForm(UserCreationForm): # job_title = forms.IntegerField(label='2 + 2', label_suffix=' =') # yes = forms.IntegerField(required=True) tos_check = forms.BooleanField(required=True, label='I have read and agree to the Terms of Service.') age_check = forms.BooleanField(required=True, label='I am 21 years of age or older.') class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email') help_texts = { 'username': '', 'email': '', # 'password1': 'None', # 'password2': 'Test' } class CustomUserChangeForm(UserChangeForm): tos_checktwo = forms.BooleanField(required=True, label='I have read and agree to the Terms of Service.') class Meta(UserChangeForm.Meta): model = CustomUser fields = ('username', 'email', 'tos_checktwo') # class Meta: # model = CustomUser # fields = ('username', 'email', 'tos_check',) users/views.py from django.http import HttpResponse from django.http … -
Ignoring Test Files with Nose/unittest
I have two test files. One is standard TestCases. The other has selenium tests in it. I have a docker-compose file setup to run the selenium tests with their associated services. The tests run in bitbucket-pipelines. First it runs the test with the standard TestCases. Then in the next step it uses docker-compose to run the tests that include selenium since it needs compose to set up the selenium services. The issue I'm having is it's trying to run the selenium tests during the first step when there isn't any selenium containers running. I entered this in my Django settings file used for the first testing part: NOSE_ARGS = [ '--exclude=(__init__.py)', '--exclude=(../tests/selenium_tests.py)', '--exclude=(selenium_tests.py)', '--with-coverage', '--cover-package=sasite', '--with-xunit', '--xunit-file=test-results/nose/noseresults.xml', '--verbosity=3', '--cover-xml', '--cover-xml-file=test-results/nose/noseresults.xml', '--id-file=test-results/nose/noseids' ] and in my settings for the second: NOSE_ARGS = [ '--exclude=(__init__.py)', '--with-coverage', '--cover-package=sasite', '--with-xunit', '--xunit-file=test-results/nose/noseresults.xml', '--verbosity=3', '--cover-xml', '--cover-xml-file=test-results/nose/noseresults.xml', '--id-file=test-results/nose/noseids' ] As you can see, I want to exclude the selenium tests for the first part, and use them for the second. But even with my exclude in nose_args it still runs the selenium tests in the first part. Here is my bitbucket-pipelines.yml: prod-final: - step: name: Build image, run tests, and push to Docker Hub caches: - docker … -
page is not opening by giving url django
I am unable to show purchasing template by writing URL "purchaing" on browser. I am beginner here. modelform venv projectforms urls.py bookingform urls.py views.py projectforms.urls from django.contrib import admin from django.urls import path, include from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('',include('bookingform.urls')), path('purchasing/', include('bookingform.urls')), ] bookingform.urls from django.urls import path from . import views urlpatterns = [ path('',views.add_model), path(r'^purchasing/',views.purchasing_view,name="purchasing"), ] bookingform.views def purchasing_view(request): if request.method == "POST": purchasing_form = purchasingform(request.POST) if purchasing_form.is_valid(): purchasing_form.save() messages.success(request, 'Purchaing Record Saved') # return redirect('/') return render(request, "purchasing.html", {'purchasing_form': purchasing_form}) else: purchasing_form = purchasing() # purchaing = purchasing.objects.all() return render(request, "purchaing.html", {'purchasing_form': purchasing_form}) -
Materialize sidenav not working in Django
I am able to see the hamburger icon which appears when the screen is made smaller, but when I press it is unresponsive. This is the code for my base.html file {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!-- Materialize icons --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> {% block head %} <title>Home</title> {% endblock %} </head> <body> <!-- navbar --> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo center">Logo</a> <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <li><a href="collapsible.html">Javascript</a></li> <li><a href="mobile.html">Mobile</a></li> </ul> </div> </nav> <!-- hamburger icon side navbar --> <ul class="sidenav" id="mobile-demo"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <li><a href="collapsible.html">Javascript</a></li> <li><a href="mobile.html">Mobile</a></li> </ul> <script> $(document).ready(function(){ $('.sidenav').sidenav(); }); </script> {% block body %} <h1>Base</h1> {% endblock %} <!-- Compiled and minified Jquery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script> </body> </html> I also have a js folder in static folders with materialize.js inside. Although I'm unsure what's supposed to go there. I've tried using various versions of jQuery but nothing has worked so far. I made a responsive navbar in bootstrap with no problems so not sure what … -
Django template rendering under a wrong URL
Im working on an application (to learn django) where it has kind of master template. and the view.py @login_required def home(request): return render(request, '../templates/mainSection/home.html') def createshipment(request): if request.method == "GET": # shipmentNumber is defined by 'SHN-000' + next Id in the shipment Table try: # trying to retrive the next primaryKey nextId = Shipment.objects.all().count() nextId += 1 except: # if the next ID is null define the record as the first nextId = 1 # creating the form with the shipment ID form = CreateShipmentForm(initial={'shipmentNumber':'SHN-000' + str(nextId)}) return render(request, '../templates/mainSection/createshipment.html', {'form': form}) def saveshipment(request): if request.method == 'POST': form = CreateShipmentForm(request.POST) if form.is_valid(): try: form.save() except (MultiValueDictKeyError, KeyError) as exc: return HttpResponse('Missing POST parameters {}'.format(exc), status=400) else: messages.error(request, form.errors) return render(request, '../templates/mainSection/fillshipment.html') def viewshipment(request): return render(request, '../templates/mainSection/viewshipment.html') def fillshipment(request): if request.method == "GET": # creating the form productForm = CreateProductForm() # Retrieving The Product types for the ShipmentForm productType_list = ProductTypes.objects.all() shipment_list = Shipment.objects.all() return render(request, '../templates/mainSection/fillshipment.html', {'productTypes': productType_list, 'shipments': shipment_list, 'productForm': productForm}) and the urls.py urlpatterns = [ path('home/', views.home,name="home"), path('home/createshipment/',views.createshipment,name="createshipment"), path('home/createshipment/saveshipment/',views.saveshipment,name="saveshipment"), path('home/fillshipment/',views.fillshipment,name="fillshipment"), path('home/viewhipment/',views.viewshipment,name="viewshipment"), ] The problem that Im trying to solve is, After submitting a form and navigating to the next, the template diffrent under the previous URL. … -
Django - loop using models.PositiveIntegerField variable
I have this code: class Zapas(models.Model): tym_domaci = models.ForeignKey(Tym, on_delete=models.CASCADE) tym_hoste = models.ForeignKey(Tym, on_delete=models.CASCADE) datum = models.DateTimeField('datum zapasu') goly_domaci = models.PositiveIntegerField(default=0) goly_hoste = models.PositiveIntegerField(default=0) for x in range (goly_domaci): strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_domaci}) nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_domaci}) for x in range (goly_hoste): strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_hoste}) nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_hoste}) What i am trying to do, is to load all the players that scored a goal and players that assisted on it (if there is any) for each team. Problem is, that i cannot use goly_domaci and goly_hoste in the for loop because they are PositiveIntegerField and not an Integer. Is there any way to convert the PositiveIntegerField into Integer? Or can I even use the for loop like this? I am new to python and Django so I really dont know how to solve it. Thanks for help :-) -
How to arrange posts from different models in Order of time when they were created
Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. I have 400 fixed groups. Users have to choose from the existing 400 groups for their posts. Users cannot add, delete, update group's. Furthermore: Users can become a member of groups and when they click on a certain group. They see all the posts in that group. Users can follow-unfollow other users. **What I have right now:**When a user signs-in. In his home page he sees. All the posts of the each individual group he is a member of. When all the posts from all the groups are done with. He then sees the posts of all the people he follows one by one What I want: I want the posts to be arranged by time Example: If one of the people he follows just wrote a post then that post is first. Chronologically the second post was in one of the groups that he is a member of. That post comes second... You get the idea Below are my models class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message … -
Lost old data after add new data Django Admin
class Song(models.Model): song_id = models.AutoField(default=1,primary_key=True,editable=False) file = models.FileField(upload_to=only_filename,null=True,blank=True) name = models.CharField(max_length=50) album_id = models.ForeignKey(Album, on_delete=models.CASCADE) lyric = models.TextField() cover_imagemodels.ImageField(upload_to="img/",default="img/None/icon.jpg") listen_time = models.PositiveIntegerField(default=0,editable=False) def __str__(self): return self.name Above is my class model. First, I login to superuser in Django Admin, then add a new song. It's success. But, after that I continue add another song, there is only a newest song is saved, and older song dispear. I use mysql command line to check and there is only newest one is exist. How to fix it? Sorry for my bad english. -
Selenium Testing - Test if Clicking Button Opens Correct Items
I have two buttons on my page, one for viewing a pdf (opens in new tab) and one for downloading pdf (downloads it directly by adding the attachment header. Here's my testing code so far: def test_study_popover_view_clicked(self): cls.selenium_chrome.get('https://www.shenkan-associates.com/') try: target_element_chrome = cls.selenium_chrome.find_element_by_id('study-item-7') target_element_chrome.click() popover_element_chrome = cls.selenium_chrome.find_element_by_class_name('popover') popover_view_button_element_chrome = cls.selenium_chrome.findElement(By.cssSelector('.popover > .popover-content > .popover-actions > .study-view')) except NoSuchElementException as ex: self.fail(ex.msg) nt.assert_true(popover_element_chrome.is_displayed()) nt.assert_true(popover_view_button_element_chrome.is_displayed()) nt.assert_equal(popover_view_button_element_chrome.text, 'View') popover_view_button_element_chrome.click() def test_study_popover_download_clicked(self): cls.selenium_chrome.get('https://www.shenkan-associates.com/') try: target_element_chrome = cls.selenium_chrome.find_element_by_id('study-item-7') target_element_chrome.click() popover_element_chrome = cls.selenium_chrome.find_element_by_class_name('popover') popover_download_button_element_chrome = cls.selenium_chrome.findElement(By.cssSelector('.popover > .popover-content > .popover-actions > .study-download')) except NoSuchElementException as ex: self.fail(ex.msg) nt.assert_true(popover_element_chrome.is_displayed()) nt.assert_true(popover_download_button_element_chrome.is_displayed()) nt.assert_equal(popover_download_button_element_chrome.text, 'Download') popover_download_button_element_chrome.click() As you can see I click the download and view button elements. at the end of each method. Clicking view should open a pdf in a separate tab. Clicking download should start to download the pdf directly. I just need a way to test that the buttons are doing what they should. How can I test this? Thanks -
TypeError: __init__() got an unexpected keyword argument 'topic'
while i was adding value to a query set i got this this error. models.py from django.db import models class Topic(models.Model): def __init__(self): topic=models.CharField(max_length=264,unique=True) def __str__(self): return self.topic class Webpage(models.Model): def __init__(self): topic=models.ForeignKey(Topic) name=models.CharField(max_length=264,unique=True) url=models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): def __init__(self): name=models.ForeignKey(Webpage) date=models.DateField() def __str__(self): return str(self.date) #t=Topic(topic="shoaib") Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __init__() got an unexpected keyword argument 'topic' -
Why am I getting an UnorderedObjectList Warning even though I'm following a conventional usage of the order_by() function?
I have a generic list view from which I paginate using the querysets from two separate models : Message and safeTransaction. django terminal output gives this warning upon entry to my inbox view : /usr/local/lib/python3.6/dist-packages/django/views/generic/list.py:88: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: QuerySet. allow_empty_first_page=allow_empty_first_page, **kwargs) This is the View and get_context_data method : ### Inbox list class class InboxListView(ListView): #This view lets the user view all the messages created in a list model = Message template_name = "myInbox/inbox.html" paginate_by = 3 # paginating twice here #so the page gets paginated in a convenient way for my template. def get_context_data(self, **kwargs): message_list = Message.objects.filter(recipient=self.request.user) .order_by('-date') safeTransaction_list = SafeTransaction.objects .filter(trans_recipient=self.request.user) .order_by('-date') queryset = list(chain(message_list, safeTransaction_list)) #paginator setup start paginator = Paginator(queryset,3) page = self.request.GET.get('page') safe_T_list = paginator.get_page(page) #iterable list for template #paginator setup done context = super(InboxListView, self).get_context_data(**kwargs) context.update({ 'now': timezone.now(), 'message_list':safe_T_list, }) return context What I am doing in this method is chaining the filtered querysets into a list, then paginating that as one queryset. The problem is that even before I do that, my filtered Messages and SafeTransactions are seen as unordered lists. This confuses me because the typical usage of order_by() on the django website is … -
is it necessary to implement ModelForm in our project to implement a CreateView (CBV) in Django 2.0.2?
I am a beginner programming in Django framework and I am learning how to implement a CreateView (a class based view for creating a form based on a model) in my views.py file. -
Python django Need return name instead of id foreginkey
class Product(models.Model): name = models.CharField(max_length=300, default='default name') description = models.TextField(max_length=800, blank=True, null=True) link = models.TextField(default='0') type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True, blank=True) keyword = models.OneToOneField(KeyWords, on_delete=models.CASCADE, null=True, blank=True) model don't return data from ForeignKey -
why don't save password in my database of Django
i work with Django. i use AbstractBaseUser for create User in models. i create form's for my models . my forms don't save password in my database Forms: from django import forms from django.contrib.auth import get_user_model class Register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email') def clean_username(self): User = get_user_model() username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = … -
django debug toolbar Internal IP and static files
I installed Django debug toolbar and configured it as explained in the docs. I am in local development configuration. As soon as I set up Internal IPs as indicated I get the following error > FileNotFoundError at /admin/ [Errno 2] No such file or directory: '/home/odile/Documents/dev_logiciels/djangoE6000_techniques/E6000_stitch_techniques/static' Settings.py is ALLOWED_HOSTS = ['127.0.0.1', ' E6000.pythonanywhere.com'] INTERNAL_IPS = ['127.0.0.1'] ...... STATICFILES_DIRS = ( os.path.join(BASE_DIR, "E6000_stitch_techniques", "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') When I comment the line Internal-IPS I get no error but no debug bar. ANy help welcomed. -
remote: -----> Python app detected remote: ! Requested runtime (Python 3.6.4) is not available for this stack (heroku-18)
remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python 3.6.4) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to sreeman-billing. remote: To https://git.heroku.com/sreeman-billing.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/sreeman-billing.git' i have found many answers to this question so i have changed the version to the stable version that heroku supports but heruko isnt taking the version from runtime file instead it detecting the version automatically please can someone suggest me any way to make this work -
How can I handle multiple image uploads without the server slowing down?
I followed this tutorial to upload multiple images with the help of AJAX. https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html To summarize it: I have a model that stores the images A form with an image field A view that handles the form in the post method Ajax sends a post request to this view We have a server on Heroku an the problem is if someone uploads a lot of images with a size of >5MB per image the site is extremely slow. Not only for the uploader but for every other user as well. How can you solve such a problem? -
RelatedObjectDoesNotExist at /login/
Everything was working fine now this is the error im getting i cant even login in to admin it gives the same error there too -
Django json field
Want to know the detail usage of django json field. Is it best idea for django modelform? If I use django json field, how to use edit view easily? New to django and didn't find good example of usage. -
Overriding serializer create for nested serializer with many=True
I am trying to have the ClassificationResultsSerializer many Classifications by having a nested serializer as shown below. class ClassificationSerializer(serializers.ModelSerializer): class Meta: model = Classification fields = ('summary', 'wiki_url', 'score') class ClassificationResultsSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') classifications = ClassificationSerializer(many=True) def create(self, validated_data): classifications_data = validated_data.pop('classifications', []) classificationresults = ClassificationResults.objects.create(**validated_data) for data in classifications_data: Classification.objects.create(classificationresults=classificationresults, **data) return classificationresults class Meta: model = ClassificationResults fields = ('id', 'owner', 'classifications') I defined the create method for ClassificationResultsSerializer to handle the nesting as per https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers, and I call the ClassificationResultsSerializer in my views as such: serializer = ClassificationResultsSerializer(data={ 'owner': self.request.user, 'classifications': [ { 'summary': 'a summary', 'wiki_url': 'url', 'score': 1 } ] }) but I keep getting psycopg2.IntegrityError: null value in column "classifications" violates not-null constraint The reason I'm sure is because I'm popping classifications in create, then creating the classificationresults without classifications now being null, despite the documentation telling me to do this. How am I able to solve this problem?