Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Session's Not Saved After Move From Local Pc to VPS
I have big problem ... since i want to move my local django project to vps and run it .... i remove sqlite and migrations (- inits remain) and Create Postgre Sql And Connect it to my django project and makemigrations and ... i can login in django admin or any other stuffs but sessions that i saved it with request.session['something'] = 'something' dosent save's but in local computer it's works :( .. i tried request.session.modified = True But It Dosent Work .. Please Help -
what do I need to learn about React for rest framework?
I'm seeking to learn react for using rest framework of Django. I already have some basic knowledge of Javascript and a little of ES6. I started watching some tutorials and knew some react concepts like functional component, class component, props, states. but I'm not sure if I'm on the right path learning what I really need to learn and I don't want spend much time and effort on something I won't make use of. so, I was wondering if I need to learn the whole react technology or just some specific concepts? and if it's only some concepts I need to learn about, then what are those concepts? -
Error writing to many to many field django rest framework api
This seems to be my solution https://stackoverflow.com/a/48636446/7989638 (for "How can I make a writable ManyToManyField with a Through Model in Django Rest Framework? ") but I am getting this error : {"images":["Incorrect type. Expected pk value, received unicode."]} their solution works in the create method of the serializer but i debugged and checked that it never reaches that method; returns error beforehand. Could you please help me fix this. Thanks -
Adding a value to a database field that is in your model but is not in your form
I have a model with a property called authID that looks like this: authID = models.CharField(max_length=400) In my view, all of the fields that are in my form get put into the database as follows: if request.method == 'POST': form = PersonalDetailsModelForm(request.POST) if form.is_valid(): form.save() What I want to know how to do is that when they submit the form, I want to also put the value of authID into my database. However, authID is not a field in my form. I don't want to make it a hidden field either for security reasons. How do you add a value to a database field that is in your model, but is not in your form? -
Need help in rendering a dataframe in html in django
I am new to python and django. need help to convert the below code to django model/view.py in order to render the output as a table with subtotal functionality. from kiteconnect import KiteConnect import iv_greeks import pandas as pd import csv import itertools from pprint import pprint apikey = open('apikey.txt','r').read() apisecret = open('apisec.txt','r').read() atr = open('access_token.txt','r').read() kite = KiteConnect(api_key=apikey) kite.set_access_token(atr) def lastprice(symbol): a = kite.ltp(symbol) for i,j in a.items(): b = j.pop('last_price') return b from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) while (current_time > "09:00:00") & (current_time < "15:30:00") : positions = kite.positions() N = 1 net = dict(itertools.islice(positions.items(), N)) for typ,pos in net.items(): with open('net_position.csv', 'w', encoding='utf8', newline='') as output_file: fc = csv.DictWriter(output_file, fieldnames=pos[0].keys(), ) fc.writeheader() fc.writerows(pos) positions = pd.read_csv('net_position.csv') positions['Underlying'] = positions.tradingsymbol.str.split('19').apply(lambda x: x[0]) positions['Strike'] = positions.tradingsymbol.str.split('DEC').apply(lambda x: x[1]) positions['StrikePrice'] = positions.Strike.str.split('CE').apply(lambda x: x[0]) positions['StrikePrice'] = positions.StrikePrice.str.split('PE').apply(lambda x: x[0]) positions['StrikePrice'] = positions.StrikePrice.astype(float) positions['CallPut'] = positions.Strike.str[-2:] positions.rename(columns = {'product' : 'Product','quantity' : 'Qty', 'average_price' : 'Avg', 'last_price' : 'LTP', 'unrealised' : 'Unrealised', 'realised' : 'Realised', 'pnl' : 'PnL'}, inplace = True) #import underlying instrument token fno = pd.read_csv('nse_stk.csv') positions.rename(columns = {'instrument_token' : 'instrument_token_tradingsymbol'}, inplace = True) fno.rename(columns = {'tradingsymbol' : 'Underlying'}, inplace … -
Django EditStamdata() got an unexpected keyword argument 'instance'
Hej, I got a error if I load a Form: from django import forms from .models import CountryList, Stamdata from django.db.models.functions import Lower from django.contrib.auth.models import User class EditStamdata(forms.ModelForm): Firmanavn = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), label='Firmanavn') EMail = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'autofocus': True}), label='EMail') Bank = forms.CharField(widget=forms.Textarea(attrs={'rows' :'4', 'class': 'form-control', 'autofocus': True}), label='Bank') Navn = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), label='Navn') Adresse = forms.CharField(widget=forms.Textarea(attrs={'rows' :'4', 'class': 'form-control'}),label='Adresse') Land = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),queryset=CountryList.objects.values_list('countryname', flat=True).order_by('code'), initial='Denmark', to_field_name='countryname') CVRCountrycode = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control col-md-4'}),label='CVR Landkode', queryset=CountryList.objects.values_list('code', flat=True).order_by('code'), initial='DK', to_field_name='code') CVR = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'form-control'}),label='CVR Nummer') class Meta: model = Stamdata labels = { 'Byen': 'By', 'CVRCountrycode': 'Landekode', 'CVR': 'CVR Nummer', } fields = ['Firmanavn', 'UserID', 'Adresse', 'Land', 'CVRCountrycode', 'CVR', 'EMail', 'Bank', 'Navn'] And the view: def EditStamdata(request): StamdataData = get_object_or_404(Stamdata, pk=1) # if this is a POST request we need to process the form data if request.method == 'POST': form = EditStamdata(request.POST, instance=StamdataData) if form.is_valid(): form.save() return HttpResponseRedirect('backend/stamdata.html') else: print ('somethin goes wrong') form = EditStamdata(instance=StamdataData) return render( request, 'backend/stamdata.html', {'form': form }, ) And then I got this error message: EditStamdata() got an unexpected keyword argument 'instance' If I google it everbody fix it if they uses forms.ModelForm but I use it. -
Is there a way to get a query/stored procedure field and pass it to a form as an uneditable field, alongside other editable fields?
View: def post(self, request): form = AnswerForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() messages.success(request, 'Thank you for your request') return redirect('consumer_answer') args = {'form':form} return render(request, self.template_name, args) Form class AnswerForm(forms.ModelForm): question1 = forms.ModelChoiceField(queryset = Question.objects.all()) class Meta: model = Answer fields = ['answer', 'consumer'] Template {% for answers in answer_request %} <p>______________________________________________________________</p> <b><li> {{answers.5}}</li></b> <i><p> {{answers.6}}</p></i> Question ID: {{answers.8}}<br> <form method="post"> {% csrf_token %} {{form.as_p}} <select id="question1"> <option value= {{ answers.8 }}> Label </option> </select> <button type="submit">Submit Answer {{answers.8}}</button> </form> {% endfor %} </ol> {% endif %} At the moment, the above creates a blank form field called 'answer' (fine as completed by user and then posts to db, but the next two fields of 'consumer' and 'question' are drop downs of all instances in the model). Would like the 'consumer' and 'question' field to be uneditable with the result of the query so they are then posted to the db. The query works fine outside of the form as the loop above the form successful iterates and displays the output, I would just like to get it into the form. Thank you in advance for any help. -
Django and remote MariaDB
I use Django on a Postgres DB. Then I connect remote MySQL databases to it, no problem. But now I want to connect a remote MariaDB. I have a problem: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (110)") This problem seems to come from the remote DB. However I checked the rights of the database and the remote server. I can connect to this database remotely from HeidiSQL, or a local PhpMyAdmin. So I start to think that maybe it comes from Django, Python, connectors ... Please do you know this problem? -
Access to CreateView form modal on every page
I'm wondering is it possible to create modal that include CreateView form and have access to it on every page in django, on every view? So far I have a CreateView in my views.py: class ScenarioCreateView(CreateView): model = Scenario fields = ['title', 'area', 'author'] urls.py path('scenario/new/', ScenarioCreateView.as_view(), name='scenario-create'), and modal: <li><a class="modal-trigger" href="#modal1"><i class="material-icons">add</i></a></li> <!-- Modal Structure --> <div id="modal1" class="modal" method="post" action="/scenario/new/"> <div class="modal-content"> {% block new %} {% endblock %} </div> <div class="modal-footer"> <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a> </div> </div> It's working now only from /scenario/new/, of course. I should probably change the path in urls.py, right? Could you help me? -
How do i fix this operational error in Django?
I created a comment view in my views.py, for the user to write and submit comments through a form. The comments will be displayed on the same template the info regarding a movie is shown. When I try to enter one of the films i get this error: OperationalError at /myapp2/2/ no such column: myapp2_comentario.pelicula_id views.py def detallesPelicula(request, pelicula_id): peliculas = get_list_or_404(Pelicula.objects.order_by('titulo')) pelicula = get_object_or_404(Pelicula, pk=pelicula_id) actor = get_list_or_404(Actor.objects) comentarios = Comentario.objects.filter(pelicula=pelicula).order_by('fecha') comment_form = CommentForm(request.POST or None) if request.method == 'POST': if comment_form.is_valid(): comentario = comment_form.save(commit=False) comentario.usuario = request.user comentario.save() return HttpResponseRedirect(pelicula.get_absolute_url()) context = {'pelicula': pelicula, 'peliculas': peliculas, 'comentarios':comentarios,'comment_form':comment_form} return render(request, 'detallesPelicula.html', context) my models.py class Comentario(models.Model): usuario = models.ForeignKey(User,on_delete=models.CASCADE) pelicula =models.ForeignKey(Pelicula, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True,null=True,blank=True) texto = models.TextField(max_length=2000, default="") def __str__(self): return self.usuario.nickname forms.py class CommentForm(forms.ModelForm): class Meta: model = Comentario fields = ['texto'] -
How to make a selection form in Django and use the selected value as session variable in a view?
When a user visits my web app he needs to select an account number within a dropdown menu. I then want to use his selection for further view functions within the session. 1.) How to create the required form? class selectMT4(forms.Form): CHOICES = (('Option 1', 'Option 1'),('Option 2', 'Option 2'),) field = forms.ChoiceField(choices=CHOICES) Here I am not sure how to offer the right options to select. The available account numbers are linked to his pk in the database table. He might have 10 entries with account number X and 2 entries with account number Y e.g.. So I somehow need to query each different available account number to use it as options in the form. This is how it looks like, thus the desired select options should be Option 1: 1925323 and Option 2: 1933381. Is it possible to implement such querySet within the form class itself? 2.) How to use the selected option in a view function? def getTrades(request, *args, **kwargs): trades = serializers.serialize('json', Trades.objects.filter(DID=request.user.DID)) return HttpResponse(trades) After the user made his selection, I want to use the selected value for view functions within that user session. In particular I would like to add the users selection as another … -
ImportError: cannot import name 'modelname' from 'apps.models' (D:\project\django\projects\django\apps\models.py)
thanks to your visit to my post, i one error here, please help me to find whats wrong in my code. i use django 2.2. i get one wrong : ImportError: cannot import name 'CategoryRoom' from 'rooms.models' (D:\project\django\voice web app\django\rooms\models.py) my full list in my comand line is like this : (env) D:\project\django\voice web app\django>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\project\django\voice web app\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\project\django\voice web app\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "D:\project\django\voice web app\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\project\django\voice web app\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\project\django\voice web app\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python 3.7.5\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\project\django\voice web app\django\rooms\models.py", line 4, in <module> from promotions.models import Bundle File "D:\project\django\voice web app\django\promotions\models.py", line 3, in <module> from rooms.models import … -
WeasyPrint HTML to PDF not rendered Images in TEST VM Environment - Django
I am using Django + WeasyPrint for HTML to PDF generation. In HTML template I am having around 2 SVG files. While running in Development (local) server, it rendered SVG Images when converting HTML to PDF. Whereas in TEST Server(Which runs by using NGINX and Docker Container), it fail to render SVG files. In WeasePrint, I have mentioned my TEST URL (http//test.sampleproject.com:8000) in the base_url. I don't know why it is working in my dev server and not working in TEST Server My Code. html_string = render_to_string('sample.html', {'data': data}) result = HTML(string=html_string, base_url='http//test.sampleproject.com:8000').write_pdf(presentational_hints=True) response = HttpResponse(result, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename={}'.format('sample.pdf') return response In my Template file I have loaded around 10 images. Ex: 'sample.html' template file: {% load staticfiles %} <img src="{% static 'svg/Logo1.svg' %}" alt="" /> <img src="{% static 'svg/Logo2.svg' %}" alt="" /> Please help me to render the SVG files in the output PDF. -
ValueError('Related model %r cannot be resolved' % self.remote_field.model) inside a single app
Here is models.py from django.db import models class Owner(models.Model): first_name = models.CharField('Ім`я', max_length=30) last_name = models.CharField('Фамілія', max_length=30) surname = models.CharField('По-батькові', max_length=30) class Address(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник') house = models.IntegerField('Будинок', default=0) street = models.CharField('Вулиця', max_length=30) city = models.CharField('Місто', max_length=30) region = models.CharField('Область', max_length=30) cantry = models.CharField('Країна', max_length=30) class Car(models.Model): number = models.IntegerField('Номер', primary_key=True) date = models.CharField('Місто', max_length=30) brand = models.CharField('Марка', max_length=30) colors = models.CharField('Кольори', max_length=30) state = models.CharField('Стан', max_length=30) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, verbose_name='Власник') address = models.ForeignKey(Address, on_delete=models.CASCADE, verbose_name='Адреса') class Engine(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, verbose_name='Машина') cylinders = models.CharField('Циліндри', max_length=30) fuel_injection = models.CharField('Вприскування пального', max_length=30) supercharger = models.CharField('Суперчарджер', max_length=30) catalytic = models.CharField('Каталізатор', max_length=30) automatic = models.CharField('Автоматичний', max_length=4) class Performance(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) acceleration = models.FloatField('0-100 kmph (сек)', default=0) max_speed = models.IntegerField('Максимальна швидкість', default=0) fuel_eff = models.FloatField('Витрата пального', default=0) pollution_class = models.CharField('Клас забруднення', max_length=8) base_price = models.IntegerField('Базова ціна', default=0) class Type(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) body_type = models.CharField('Тип кузова', max_length=16) no_of_door = models.IntegerField('Кількість дверей', default=0) no_of_seats = models.IntegerField('Кількість сидіннь', default=0) engine_place = models.CharField('Місце мотору', max_length=2) drivetrain = models.CharField('Привід', max_length=16) class Body(models.Model): car = models.OneToOneField(Car, on_delete=models.CASCADE, parent_link=True, verbose_name='Машина') # car = models.ForeignKey('Машина', Car, on_delete=models.CASCADE) … -
How to pass initial choices from view to form
I'm trying to pass choices from django based view to form choice field what I did: forms.py class FormName(forms.Form): freq = forms.ChoiceField(choices=FREQ) start_date = forms.DateField(widget=forms.TextInput( attrs={'type': 'date'} ), label='Start Date') projects = forms.ChoiceField(required=False, label='Project') views.py def view_name(request, *args, **kwargs): all_projects = list( Model.objects.filter(user_id=user_id).values("project_id", "project_name").distinct()) projects = tuple((q['project_id'], q['project_name']) for q in all_projects) form = FormName(initial={'freq': grouping_by, 'start_date': start_date, 'projects': projects}) in view code I retrieve the choices as tuple of tuples and I want to pass it in the initial part how can I do that? many thanks -
AttributeError: 'ManyToManyField' object has no attribute 'First_Name'
i encountered the following problem when i try to migrate list of models one of which contains a ManyToMany field. class Item(models.Model): File "C:\Users\helin\Downloads\Django\E-commerce\Farmers\Farmersapp\models.py", line 60, in Item sluger = farmer.First_Name AttributeError: 'ManyToManyField' object has no attribute 'First_Name' Below are the models i created.any help is appreciated.Thank you class Farmer(models.Model): id = models.AutoField(default=1,primary_key=True) First_Name = models.CharField(max_length=15) Last_Name = models.CharField(max_length=15) def __str__(self): return self.First_Name+" "+self.Last_Name def get_farmer(self): return self.farmer.First_Name+" " +self.farmer.Last_Name class Item(models.Model): id = models.AutoField(default=1,primary_key=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=6) price = models.FloatField() description = models.TextField(blank=True) image = models.ImageField() farmer = models.ManyToManyField(Farmer, through='ItemAmount',related_name='item') sluger = farmer.First_Name slug = models.SlugField(default=sluger) def __str__(self): return self.category class ItemAmount(models.Model): farmer = models.ForeignKey(Farmer, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) -
Can not set value of ace editor with template tags filters
I have an ace editor in my html page,for which I can write editor.setValue( '//Your code here'); It perfectly works and I get an editor with "//Your code here" written inside it. But when I pass a template tag from django backend,with this line. def func(request): context={"message":"hello there,write your code"} return render(request,'index.html',context) and try to set value using template tagging filter with this line editor.setValue({{message}}); It is not working,If I write it in simple html,It works,but not inside setValue() function. -
Django check and alternate Docker Compose file: Debug flag not being set?
I'm trying to prep a Django application for production. I created an alternate docker-compose YML file where I specify DEBUG=0. However when I run the django check for deployment, it says that DEBUG is set to True. Any thoughts on where I'm going wrong? I thought it was an issue with my use of Docker. But is it perhaps an issue with how I'm using Django? Here are my steps: Created my project with docker-compose.yml (see below) Created docker-compose-prod.yml for production (see below) Ran the following $ docker-compose down $ docker-compose -f docker-compose-prod.yml up -d --build $ docker-compose exec web python manage.py check --deploy Output of the check: ?: (security.W018) You should not have DEBUG set to True in deployment. Some of investigatory steps so far: A. Check the environment variables. $ docker-compose exec web python >>> import os >>> os.environ.get('DEBUG') '0' B. Try rebuilding docker image in different ways, e.g. with --no-cache flag C. Set the DEBUG flag in settings.py in a conditional code block (rather than using os.environ.get). This seemed to work. But I don't understand why? Code detail below. Code excerpts Excerpt from docker-compose.yml services: web: ... environment: - ENVIRONMENT=development - SECRET_KEY=randomlongseriesofchars - DEBUG=1 Excerpt from docker-compose-prod.yml … -
CSS class changed but the style is taking time to get applied
I added a new class in the custom CSS file in a Django app and changed the HTML accordingly. The problem is that the class is getting applied to let's say a button but the page is not showing the changes. For example: Please check the below snippet <button type="button" class="btn btn-primary btn-lg">Text</button> I added a new class .btn-custom in custom.css and changed the HTML file as well. Now after the refresh, the above tag changed to <button type="button" class="btn btn-custom btn-lg">Text</button> But the style is not applied to the page. I check the custom CSS file by opening the source and the changes I made are there. After 2 to 3 hrs the changes getting reflected. I tried hard refresh as well cache clearing and every other option related to cache -
Display formatted excel output on HTML while running external python script
So i have this huge python script which combines multiple excel files and generates another 20 excel files with formatted pivot tables etc. Since i am going to handover this script to people with no python knowledge, i have created a django project which will enable the users to run this script with a click of a button on their web browser. As of now the output gets saved in multiple excel files. So what i actually want to do is display the output below the execute button on the same webpage as soon as the script is completed its execution. As of now the script displays output as follows: b' MRC ACT ... Variance_y %real_var\r\n0 INDONESIA 5263639608.007611 ... 9899814.618474 100.199738\r\n1 MALAYSIA 3577129.588221 ... 1251126.219085 108.868625\r\n2 PHILIPPINES 27816561.032899 ... -153405.655029 97.436131\r\n3 SINGAPORE 3653201.384013 ... 611488.423571 100.843299\r\n4 THAILAND 74495246.352116 ... 13710289.449428 101.175474\r\n5 VIETNAM 31212513.847313 ... -54368.594170 100.000000\r\n\r\n[6 rows x 9 columns]\r\n' This is the snippet of code i am using: views.py: def external(request): #inp=request.POST.get("param") out=run([sys.executable, 'C:\\Users\\rsm\\Downloads\\ABC\\abc.py'], shell=False, stdout=PIPE) print(out) return render(request,'home.html', {'data1':out.stdout}) home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Python Button Script</title> </head> <body> <br> <form action="/external/" method="post"> {% csrf_token%} {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute Script"> </form> </body> </html> … -
Django ORM Query , how to convert the query set to tuple of tuples
I'm trying to do this from query (('1','A'), ('2','B'), ....) to use it as choice field in my form, how to convert my query result to do this ? where 1,2 is the row id and A,B is another columns value many thanks -
Add existing API into django rest framework
Besides the API I created by using the django rest framework, now I want to add the existing commerial API into the backend, how to do this? The commerial API include several part(API), for example, /prepare, /upload, /merge,/get_result, etc. They all use the "POST" indeed. Do I need to call the commerial API directly on the frontend? Or I need to integrate the commerial API in to one backend API? Any suggestions are appreciated.Thanks. For example: ``` class TestView(APIView): """ Add all the commerial API here in order /prepare(POST) /upload(POST) /merge(POST) /get_result(POST) return Result """ ``` -
change mintime on flatpicker based on currentdate
I am using flatpickr to show the calender time.I want to set the minimum time with the variable,and on change of the date if the date is selected anyother date except today's date the minimum time should be changed. The minumtime is 13:00. so on the first click the minimum time will be 13:00.But if the user selects any other date other than today the minimum time should be chanegd.Please help in proceeding with this. let minimumtime = "13:00" let start_date = $vehicle_request_form.find("#id_start_date").flatpickr( { altInput: true, altFormat: "F j, Y H:i", enableTime: true, time_24hr: true, weekNumbers: true, minDate: "today", minTime: minimumtime, maxDate: new Date().fp_incr(730), locale: { firstDayOfWeek: 1 }, onChange: function (selectedDates, dateStr, instance) { var date = new Date(Date.parse($("#id_start_date").val())); date.setMinutes(date.getMinutes() + 1); newDate = Date.parse(date.toString()); end_date.set("minDate", newDate); end_date.setDate(newDate, true); start_date.set("minTime","16:00"); } }); -
How to Import wagtailvideo in wagtail
In Shell:- 1st try :- from wagtailvideos.models import AbstractVideo 2nd try :- from wagtail import wagtailvideos_video Nothing Works, I want to use it Directly on my Templates thats why i am importing it. and I want to add custom fields in wagtailvideo. What steps should I take to add custom fields. in wagtailvideo -
Assign image to ImageField WITHOUT saving (django)
my code: class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) slug = models.SlugField(blank=True,null=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:50] if self.source_url and not self.image: result = urllib.request.urlretrieve(self.source_url) self.image = os.path.basename(self.source_url), File(open(result[0], 'rb')) if self.source_url: if '//' in self.source_url: d = self.source_url.split('//')[1].split('/')[0] else: d = self.source_url.split('/')[0] try: domain = Domain.objects.get(domain_url=d) except Exception as e: print(e) domain_object = Domain.objects.create(domain_url=d) domain = domain_object self.domain = domain return super(AttackImage, self).save(*args, **kwargs) error: Traceback (most recent call last): File "crawl_ebaumsworld.py", line 92, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 66, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/home/michael/projects/deepsteg/engine/models.py", line 62, in save return super(AttackImage, self).save(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql for sql, params …