Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Improving cold start up times on Google App Engine running Django on Python 3.7 Standard environment
I'm running a Django-based web app on Google App Engine under the Python 3.7 Standard Environment. When using the app, requests usually take around 500ms, which is completely acceptable. Howevever, when the app has not been accessed for some time (a few minutes), the logs show that the Google App Engine instance is shut down, and the next request requires gunicorn to load again and takes about 20 second. I obciously can't have users wait 20 seconds before the page loads. When testing on my local setup, the server takes a few seconds to load environment variables, and then the debug server loads almost immediately. I don't think there is a problem with my code, given that once the "cold start" occurs, everything is running fast, so it's not like the requests are waiting for a database read or something like that. What options are there to optimise django cold starts on Google App Engine? So far, I've increased instance class to F4, and specified the number fo gunicorn workers according to this guide. I can in theory go to F4_1G, but that's the highest available instance, and it doesn't seem to address the cold start issue. The only other … -
Django Validation error not showing on form
#I want to check the user registration.# ##if the username has already been registered, give the user a validation error.## In my terminal environment, the data_user dictionary is also printed but in my form registration, a username validation error does not work into help.html This is the same Form. ---> https://imgur.com/a/osAv0xn models.py from django.db import models class SignUpModel(models.Model): name = models.CharField(max_length=20,null=True) family = models.CharField(max_length=30,null=True) username = models.CharField(max_length=10) email = models.EmailField(null=True,unique=True) password = models.CharField(max_length=20,null=True) # Create your models here. class LoginModel(models.Model): username = models.CharField(max_length=15) password = models.CharField(max_length=20) views.py from django.shortcuts import render from .forms import * from django.contrib.admin.views.decorators import staff_member_required @staff_member_required() def blogPostSignUpView(request): form = BlogPostSignUpModelForm(request.POST or None) if form.is_valid(): form.save() print(form.cleaned_data) form = BlogPostSignUpModelForm() template_name = "help.html" context = {"title":"register","form":form} return render(request,template_name,context) @staff_member_required def blogPostLoginView(request): form = BlogPostLoginModelForm(request.POST or None) if form.is_valid(): # print(request.POST) # obj = form.cleaned_data # data_user = SignUpModel.objects.filter(username=obj['username']) # print(data_user) # if obj['password'] == data_user['password']: # print(data_user) obj = form.save(commit=False) obj.save() # form = BlogPostLoginModelForm() template_name = 'help.html' context = {"title":"login","form":form} return render(request,template_name , context) forms.py from django import forms from .models import SignUpModel,LoginModel #Sign UP Form class BlogPostSignUpForm(forms.Form): name = forms.CharField() family = forms.CharField() username = forms.CharField() email = forms.CharField(widget=forms.EmailField) password = forms.CharField() class BlogPostSignUpModelForm(forms.ModelForm): … -
how to fix "djang-admin not recognized"
I just formatted my OS due some reason so installed python and django again. I tried to create the python project in the same environment as previous project but unlike that it does not recognizes the "django-admin" command please help me to solve this issue. I tried reinstall it with pip and also created the environmental variable for django still not worked. enter image description here -
I am working on django but my static files are no loading
These are my files kindly tell me what i am doing wrong or what changes are needed to be done settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) index.html {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'firstapp/style.css' %}"/> <h1>Here are all Albums</h1> {% if all_albums %} <ul> {% for album in all_albums %} <li><a href="{% url 'firstapp:detail' album.id %}">{{ album.album_title }}</a> </li> {% endfor %} </ul> {% else %} <h1>No data found</h1> {% endif %} style.css body{ background: white url{"images/background.png"}; } -
Save an output file on disk using shell commands in a django app
I am creating a script to run shell commands for simulation purposes using a web app. I want to run a shell command in a django app and then save the output to a file. The problem I am facing is that when running the shell command, the output tries to get saved in the url that I am in which is understandable. I want to save the output to for example: '/home/myoutput/output.txt' rather than /projects or /tasks I have to run a whole script and save it's output to the txt file later but that is easy once this is done. Tried os.chdir() function to change directory to /desiredpath first from subprocess import run #the function invoked from views.py def invoke_mpiexec(): run('echo "this is a test file" > fahadTest.txt') FileNotFoundError at /projects Exception Type: FileNotFoundError -
Creating ModelForm with EmbeddedModelField and customize fields within EmbeddedModelField
I have a model (parentmodel) which is having a EmbeddedModelField (embedmodel). This is basically a document in MongoDB. Below is the Model classes class embedmodel(models.Model): sendto = models.CharField(max_length=10) sendtouser = models.CharField(max_length=15) sendtogroup = models.CharField(max_length=15) class parentmodel(models.Model): name = models.CharField(max_length=30, unique=True, primary_key=True) type = models.CharField(max_length=11) enabled = models.BooleanField() rule = models.EmbeddedModelField(model_container=embedmodel) class Meta: managed = False db_table = 'parentmodel' And this is how my document in mongodb looks like { 'name': 'rule1', 'type': 'static', 'enabled': True, 'rule': { 'sendto': 'external', 'sendtouser': 'sam', 'sendtogroup': 'vendor' } } I am trying to create a form which helps me create new rules and this is what i have in forms.py where i want to customize the form fields as well. class RulesForm(forms.ModelForm): name = forms.CharField(max_length=30, required=True) type = forms.CharField(max_length=11, required=True) enabled = forms.BooleanField(widget=forms.CheckboxInput) class Meta: model = parentmodel fields = ['name', 'type', 'enabled', 'rule'] How to do customize the fields being displayed from embedmodel? I tried the below but no luck. class RulesForm(forms.ModelForm): name = forms.CharField(max_length=30, required=True) type = forms.CharField(max_length=11, empty_value="UserDefined", required=True enabled = forms.BooleanField(widget=forms.CheckboxInput) sendto = forms.ChoiceField(widget=forms.Select, choices=[(1, 'External'), (2, 'Internal')]) sendtouser = forms.CharField(max_length=30, required=False) sendtogroup = forms.CharField(max_length=30, required=False) class Meta: model = Rules fields = ['name', 'type', 'enabled', 'rule'] and class RulesForm(forms.ModelForm): … -
How can i use other apps api in my own project?
Let's say i wanted to use the weather api to implement in my django code. I know how to create Rest-api in django but how can i use api of other sources to django itself? -
Display checkbox value from Database Django
I'm making a ModelForm. I have a Gender field in which I have given choices.In forms.py file I have converted those choices into checkbox using widget. models .py class UserModel(models.Model): #username=models.ForeignKey( # on_delete=models.CASCADE, # related_name='custom_user') name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) forms.py class UserForm(forms.ModelForm): class Meta: model=UserModel exclude=() widgets = { 'DOB': forms.SelectDateWidget(), 'gender':forms.RadioSelect(), #'hobbies':forms.CheckboxSelectMultiple() } everything works fine and data is stored in database,But when I fetch data from the database using commands.Instead of getting the name of choice I get 'M',or 'F'. I know for choice field we can user object.get_gender_display to get name of choice and it returns full name of choice. But since I have converted the choice to checkbox field in forms.py,now when I fetch data from database using object.get_gender_display it returns functools.partial(<bound method Model._get_FIELD_display of <UserModel: hoo>>, field=<django.db.models.fields.CharField: gender>) How can I get original name as "Male' and 'Female' ? Thanks -
How to Get a function from one app to be used in another app in Django
I have two apps Products and Shopping_cart, and I have a model in the shopping_cart app called order with the method get_cart_items and get_cart_total, In the shopping_cart app i have a view called order_details which gives the order summary, However in the products app i have a view which renders the index.html ,so i want to show the order summary on the header of the index.html template using the order_details view from the shopping_cart app on the same app works fine but on the products app doesn't template <div class="header-cart-content flex-w js-pscroll"> <ul class="header-cart-wrapitem w-full"> {% for item in order.get_cart_items %} <li class="header-cart-item flex-w flex-t m-b-12"> <div class="header-cart-item-img"> <img src="{{ MEDIA_URL }}{{ item.product.get_featured_image.url }}" alt="IMG"> </div> <div class="header-cart-item-txt p-t-8"> <a href="#" class="header-cart-item-name m-b-18 hov-cl1 trans-04"> {{ item.product.name }} </a> <span class="header-cart-item-info"> {{ item.product.price }} </span> </div> </li> {% empty %} <p> You have not added any items yet.</p> {% endfor %} </ul> {% if order.get_cart_total != None %} <div class="w-full"> <div class="header-cart-total w-full p-tb-40"> Total:${{ order.get_cart_total }} </div> {% endif %} {% if order.get_cart_items %} <div class="header-cart-buttons flex-w w-full"> <a href="{% url 'shopping_cart:order_summary' %}" class="flex-c-m stext-101 cl0 size-107 bg3 bor2 hov-btn3 p-lr-15 trans-04 m-r-8 m-b-10"> View Cart </a> <a href="{% … -
Django: List Items of each categories in a single page
I'm working on checklist app and each checklist have tasks with categories. I would like to list the tasks per category in the format below: Category 1 Task 1 of Category 1 Task 2 of Category 1 Category 2 Task 1 of Category 2 Task 2 of Category 2 I’ve tried this answer - Django: List Products of each Categories in a page But always have a blank list without any errors.. class Checklist(models.Model): slug = models.SlugField(max_length=250, unique=True, blank=True) name = models.CharField(max_length=250, unique=True) profile = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ForeignKey( ChecklistCategory, blank=True, null=True, on_delete=models.SET_NULL ) language = models.ForeignKey( ChecklistLanguage, blank=True, null=True, on_delete=models.SET_NULL ) image = models.ImageField( upload_to='images/checklist/cover/%Y/%m/%d/', default='default_cover.png', blank=True, null=True ) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='checklist_likes', blank=True) class Meta: ordering = ['-name'] def get_like_url(self): return reverse('checklist_like_toggle_url', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('checklist_url', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.id: self.slug = gen_slug(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class ChecklistTaskCategory(models.Model): task_category_name = models.CharField(max_length=250, unique=True, blank=True) def __str__(self): return self.task_category_name class ChecklistTask(models.Model): task = models.CharField(max_length=300, unique=True, blank=True) description = models.TextField(max_length=500, blank=True, null=True) checklist = models.ForeignKey( Checklist, on_delete=models.CASCADE, blank=True, null=True ) task_category = models.ForeignKey( ChecklistTaskCategory, blank=True, null=True, on_delete=models.CASCADE) done = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='task_done', blank=True) slug = models.SlugField(max_length=250, unique=True, blank=True) def get_done_url(self): return … -
Login page returned "account does not exist" after successful registration of user
I am a newbie in django web development. I was creating a simple bank web application. The registration works well as users can be created and logged in automatically. However, when I log out the user and try to log in again, the page tells me that the account does not exist. I think the error is in my views.py file. I have tried to find the error but as I have said I am a newbie. Kindly, someone assist me. views.py: def login_view(request): if request.user.is_authenticated: return redirect("home") else: form = UserLoginForm(request.POST or None) if form.is_valid(): account_no = form.cleaned_data.get("account_no") password = form.cleaned_data.get("password") # authenticate with Account No & Password user = authenticate(account_no=account_no, password=password) if user is not None: login(request, user, backend='accounts.backends.AccountNoBackend') messages.success(request, 'Welcome, {}!' .format(user.full_name)) return redirect("home") context = {"form": form, "title": "Load Account Details", } return render(request, "accounts/form.html", context) backends.py: from django.contrib.auth import get_user_model User = get_user_model() class AccountNoBackend(): def authenticate(self, request, account_no=None, password=None): try: user = User.objects.get(account__account_no=account_no) if user and user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I expect to be redirected to a success page but instead it cannot find the requested account number -
Django custom template filter feeding cookie or default value
I'm designing a custom django filter, just to make sure it works I have something like this {{ "Sleeps:"|translate:"fr" }} and it works. Now in the final implementation, I want it to get a cookie or else use a default value {{ pg.title|translate:request.COOKIES.lang|default:"en" }} I'm getting this error VariableDoesNotExist at /chalet/belle-chery Failed lookup for key [lang] in {'_ga': 'GA1.1.1026479868.1547798010', 'cookie-policy': 'true', 'csrftoken': 'VrVrvgZUfFrWhFDFjLIvZgOus9NrmjDx1JwNP2lzvz2FRAGmC1lLrKwiH4g31X5F', 'sessionid': 'ptp6smvt9w95qtqlkc7klx736u5k7uu5'} so it doesn't implement the default part. So I figure there's either a way to fix this or use middleware to set the cookie if it's not set. Would be nice if it doesn't need middleware. -
Use Querysets and JSON correctly in API View
I am trying to write my custom API view and I am struggling a bit with querysets and JSON. It shouldn't be that complicated but I am stuck still. Also I am confused by some strange behaviour of the loop I coded. Here is my view: @api_view() def BuildingGroupHeatYear(request, pk, year): passed_year = str(year) building_group_object = get_object_or_404(BuildingGroup, id=pk) buildings = building_group_object.buildings.all() for item in buildings: demand_heat_item = item.demandheat_set.filter(year=passed_year).values('building_id', 'year', 'demand') return Response(demand_heat_item)) Ok so this actually gives me back exactly what I want. Namely that: {'building_id': 1, 'year': 2019, 'demand': 230.3}{'building_id': 1, 'year': 2019, 'demand': 234.0} Ok, great, but why? Shouldn't the data be overwritten each time the loop goes over it? Also when I get the type of the demand_heat_item I get back a queryset <class 'django.db.models.query.QuerySet'> But this is an API View, so I would like to get a JSON back. SHouldn't that throw me an error? And how could I do this so I get the same data structure back as a JSON? It tried to rewrite it like this but without success because I can't serialize it: @api_view() def BuildingGroupHeatYear(request, pk, year): passed_year = str(year) building_group_object = get_object_or_404(BuildingGroup, id=pk) buildings = building_group_object.buildings.all() demand_list = [] for … -
Override default show option in datatables
I'm trying to override "show entries" option in datatable using jquery provided in datatables documentation. But it looks like datatable js cdn is overriding this to 10 again. After reloading it shows "25" but then again changes to "10" again. <script> $('#items2').dataTable( { "lengthMenu": [ [25, 50, -1], [25, 50, "All"] ] } ); </script> <script> $('#items').dataTable( { "lengthMenu": [ [25, 50, -1], [25, 50, "All"] ] } ); </script> -
send array of data as post to django
I am trying to send post request through a form to django views so as to use it to retrieve data from database on next page (action page). I am not getting the data on second page however. I have tried to use array in the name and assign array value in the form. I tried a for loop of values and names as well. However no data is received at the second page. The form to send post request: <form method="post" action="{% url 'cartpage' %}" id="formcart"> {% csrf_token %} <script> for(var i=0;i<prods.length;i++){ document.write('<input type="gone" name="cartitems[]" style="display: none;" value="prods[i]" />'); } </script> </form> Trying to get post data and the array elements on the second page in views.py: def cart(request): if request.method == 'POST': try: cartitems = request.POST.getlist('cartitems') except (KeyError): raise firstval = pionizedb.objects.filter(id__contains=cartitems[:1]) context = { 'firstval': temfil, } return render(request, 'cart.html', context) alert({{firstval}}); in html page should return first value of the array. -
How to return multiple rows with django subquery?
I am trying to get values from subquery to use in annotation, and gives an django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression error. I have queries like q = A.objects.filter(id=OuterRef('id'), b=b)\ .select_related('provider')\ .only('id', 'b', 'code')\ .distinct('code')\ .values_list('code', flat=True) t = t.annotate(**{x: ArrayAgg(Subquery(hotel_match))}) I really want to return multiple values if exists with combining ArrayAgg and StringAgg to export values as csv. How can I work with that ? -
pip install raises raise BadZipfile, "File is not a zip file"
I am trying to do pip2.7 install -r req.txt in my virtual environmen. made a virtual environment virtualenv -p python venv22 activated it source venv22/bin/activate then did sudo pip2.7 install -r req.txt Tried to install package via pip install but after installing it showed that the modules were not found. So I tried with pip2.7 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 324, in run requirement_set.prepare_files(finder) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 484, in unzip_file zip = zipfile.ZipFile(zipfp, allowZip64=True) File "/usr/lib/python2.7/zipfile.py", line 770, in __init__ self._RealGetContents() File "/usr/lib/python2.7/zipfile.py", line 811, in _RealGetContents raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file You are using pip version 9.0.1, however version 19.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.``` How do I install the packages? -
Error occured while reading WSGI handler. ModuleNotFoundError' while hosting DJango on IIS. Can't find settings
I am doing this for the first time. I am trying to host my Django rest app on Windows IIS server. I have followed this tutorial https://medium.com/@Jonny_Waffles/deploy-django-on-iis-def658beae92 but I am getting the following error. Does it have to do something with my conda environment? I haven't used any config file. I've set the environment variables in the system variables instead. In my settings.py WSGI_APPLICATION = 'webapi.wsgi.application' IN wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapi.settings') application = get_wsgi_application() Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "webapi.wsgi.application" could not be imported: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File "C:\inetpub\wwwroot\webapi\webapi\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\ProgramData\Anaconda3\envs\api_env\lib\importlib\__init__.py", line 127, in import_module … -
How to get predicted value of my linear regression model on html page
I'm preparing machine learning model via django project but I'm not able to get that value via views.py to html page. I've tried same concept to print any value on html page,but when I'm sending the same for my machine learning model but I'm not able to get that value. Views.py: from django.shortcuts import render,HttpResponse import pandas as pd import statsmodels.formula.api as sm def pricepred(request): wine = pd.read_csv('https://drive.google.com/file/d/1Eww8ChM1ZQgwCCKkMiUBi1xcs39R6C45/view') model = sm.ols('Price ~ AGST + HarvestRain + WinterRain + Age', data=wine).fit() d = {'Year': pd.Series([2019]), 'WinterRain': pd.Series([700]), 'AGST': pd.Series([15]), 'HarvestRain': pd.Series([100]), 'Age': pd.Series([10]), 'FrancePop': pd.Series([90000.000])} df_test = pd.DataFrame(d) predictDF = model.predict(df_test) context = { 'pred': predictDF } return render(request, 'pricepred.html', context) pricepred.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <title>Real Price</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" type="text/css"> <link href="{% static 'CSS/style.css' %}" type="text/css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div class="container-fluid"> <h1>Welcome to Price Prediction Page</h1> {{ pred }} </div> </body> </html> urls.py: from django.urls import path from . import views urlpatterns = [ path('pricepred/', views.pricepred), ] I expect the output of 'pred' i.e. value of prediictDF on html page but I'm getting "urlopen error [Errno 11001] getaddrinfo failed" … -
How to make a loop in function of views.py
I am just trying to simplify it and want to make a loop in views.py instead of writing every item. But it is not working. Destination is a class in models.py and I am getting data from database. from django.shortcuts import render from . models import Destination from django.db.models import Q def index(request): query = request.GET.get('srh') if query: match = Destination.filter(Q(desc_icontains=query)) # instead of writing this target1 = a, b= [Destination() for __ in range(2)] a.img = 'Article.jpg' b.img = 'Micro Tasks.jpeg' a.desc = 'Article Writing' b.desc = 'Micro Tasks' # I am trying to make a loop but it is not working. target1 = Destination.objects.all() for field in target1: [Destination(img = f'{field.img}', title = f'{field.title}') for __ in range(2)] -
linking css stylesheet django python3?
I am pretty new to Django and I do not know how to link CSS and or javascript to my project. Don't want to have a project with no CSS. Thank you for any help, sorry if this is a very dumb question. Have a nice day! -
How to range the items in generator?
How to make this range working in function. Whenever I limit n, it gives every result without limit. Here I used Destination() which is a class in models.py # This is to show you def generator(f, n, *args, **kwargs): return (f(*args, **kwargs) for __ in range(n)) # This is the problem target1 = Destination.objects.all() for field in target1: [Destination(img = f'{field.img}',title = f'{field.title}') for __ in range(2)] #models.py class Destination(models.Model): title = models.CharField(max_length=255) img = models.CharField(max_length=255) -
django gives duplicate error everytime the project runs
I am trying to add some data which is in response_body to my 'Offenses' table in my database 'dashboard' I want to add this data only once,so at the first time the data was added to my database successfully but after that it gave me this error because it obviously refuse to create duplicate entry for another oid which is set as unique How can I modify my code so that the data is added only once and no duplicate data is added and it does not give me this error django.db.utils.IntegrityError: (1062, "Duplicate entry '4767' for key 'PRIMARY'") Below is my code. I have created the table from models.py and adding the data from views.py because the data is present in views.py and it was easier to add the data from here. if there is any other suitable approach please suggest. models.py from django.db import models from django.contrib.auth.models import UserManager from django.core.validators import int_list_validator # Create your models here. class Offenses(models.Model): oid = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=20) assigned_to = models.CharField(null=True, max_length=20) categories = models.TextField(null=True) category_count = models.IntegerField(null=True) policy_category_count = models.IntegerField(null=True) security_category_count = models.IntegerField(null=True) close_time = models.TimeField(null=True) closing_user = models.IntegerField(null=True) closing_reason_id = models.IntegerField(null=True) credibility = models.IntegerField(null=True) relevance = models.IntegerField(null=True) … -
Can we upload a tree structure in one go to django server? Like we do using git?
Can we upload a tree structure in one go to the django server? Like we do by using git? We can use multiple file upload in Django but that doesn't solve the issue for hierarchical tree structure upload. -
Lightbox 2 doesn't work with django and bootstrap cards?
I have a page where I want to show images uploaded by users in a bootstrap card.The light box isn't loading right but the console doesn't show errors of the js/css files. here's the template of the images: <div class="row"> {% for image in Patient_detail.images.all %} <div class="col-md-4"> <div class="card"> <div class="card mb-4 shadow-sm"> <a href="{{ image.pre_analysed.url }}" data-lightbox="image-1" data-toggle="lightbox"> <img src="{{ image.pre_analysed.url }}" class="img-thumbnail" > </a> <div class="card-body"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </form> </div> </div> </div> </div> {% endfor %} and here's the base.html files loading <script src="{% static 'js/lightbox.js' %}"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://unpkg.com/tableexport.jquery.plugin/tableExport.min.js"></script> <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.js"></script> <script src="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table-locale-all.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> and the style sheets: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://unpkg.com/bootstrap-table@1.14.2/dist/bootstrap-table.min.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css" rel="stylesheet"> <link href="{% static 'css/lightbox.min.css' %}" rel="stylesheet"> the images do show but the lightbox effect doesn't happen plus i want to resize/crop the images inside the cards and show the full size in the lightbox.