Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError: (1062, "Duplicate entry for key 'email'"). django
I have this model file with customuser defined in it class CustomUser(AbstractBaseUser,PermissionsMixin, GuardianUserMixin): email = models.EmailField(max_length=50, verbose_name='email address', unique=True) first_name = models.CharField('first name', max_length=15,blank=False) last_name = models.CharField('last name', max_length=15,blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) slug = models.SlugField('slug', max_length=50, unique=True, null=True) is_active = models.BooleanField('active',default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: app_label = "latiro_app" db_table = "users" permissions = ( ("view_user", "view User"), ("edit_profile", "Edit Profile"), ) def get_full_name(self): full_name = '{0} {1}'.format(self.first_name, self.last_name) return full_name.strip() def get_short_name(self): return self.first_name def generate_user_slug(self): max_length = CustomUser._meta.get_field('slug').max_length full_name = self.get_full_name() slug = original = slugify(full_name)[:max_length] for i in itertools.count(1): if not CustomUser.objects.filter(slug=slug).exists(): break slug = '{0}-{1}' .format(original[:max_length - len(str(i)) - 1], i) return slug def save(self, *args, **kwargs): if not self.slug: self.slug = self.generate_user_slug() super().save() def get_anonymous_user_instance(CustomUser): return CustomUser(first_name='Anonymous') class Profile (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, null=False, verbose_name='list of users') phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}') phone_number = models.CharField('phone number', validators=[phone_regex], max_length=50, blank=True) country = models.CharField(max_length=50,blank=True) province = models.CharField(max_length=50) city = models.CharField(max_length=50,blank=True) profile_picture = models.ImageField(upload_to='user_profile/%y/%m/%d/', blank=True) followers = models.IntegerField(default=0, null=True) following = models.IntegerField(default=0, null=True) And this signal def create_user_profile(sender, instance, created, **kwargs): if kwargs.get('created', True) and not kwargs.get('raw', False): profile = Profile(user=instance) profile.save() post_save.connect(create_user_profile, sender = settings.AUTH_USER_MODEL) When run first migrations, … -
Django - Cant activate users after registration
I'm trying to activate users after their registration. First, user submits a form with his personnal information, then he receives a confirmation link redirecting to a form to define his password. After registering this password, I'm trying to activate and authenticate the user. However is_active doesn't stay to True when I set it programmatically but it works when I do it in the admin interface. I'm really confused and have no idea what to look for. Below are my user models and the concerned view. Thanks in advance for any help. Models class User (AbstractUser): # some fields validation_token = models.CharField (max_length=32, null=True, blank=True) def __str__(self): return self.username class IndividualUser (User): # some other fields The activation view form = PasswordForm(request.POST) if form.cleaned_data.get('password1') == form.cleaned_data.get('password2'): user.set_password(form.cleaned_data.get('password1')) user.is_active = True user.save() user = authenticate(username=user.username, password=form.cleaned_data.get('password1')) login(request, user) -
Site is crashed at the time of deploy an app on heroku
I can't change anything in heroku app like if i am change any single word like HTML. When changes done in git the next step is deploy an app in heroku. When deploy is done the app is crashed. i didn't find any error for this. Please tell me why my app is crashed again and again.Also if i change HTML it also crashed the site. My site is "clubfred.nl" and data comes from heroku url. Error Code is: "H10 app crashed" i already check this"$ heroku logs --tail" but didn't find anyhing. -
Django trouble creating function to delete all items in sessions / cart
I'm trying to create a function to empty all of the items from my cart in sessions. I have a perfectly good function that removes individual item, but can't get it to work for all. Can you let me know what I'm doing wrong? Thanks! I've tried to create the following function: cart.py class Cart(object): ... def clear(self): self.session.cart[settings.CART_SESSION_KEY] = {} self.session.modified = True Called it in my url/views/template like: urls.py path('cart/clear/', Buylist_views.clear, name= 'empty_cart'), views.py def clear(request): cart = Cart(request) cart.clear() return redirect('cart') template ... <button type="submit" formaction="{% url 'empty_cart' %}"> Empty Cart </button> </form> I've also tried the following function: def empty(self): for each in self.cart: del each self.save() Your insight would be much appreciated! -
Django scrf verification failed
I'm currently trying to adjust my django server with gunicorn and gninx. I met several issues when I tried to upload files : with time-out which I solved by adjusting gninx and gunicorn parameters. SOLVED with file's max_size which I solved by adjusting gninx parameters. SOLVED with "scrf verification failed" : I added the following settings : 'django.middleware.csrf.CsrfViewMiddleware' I added the crsf_token in each of my forms Upload works for little files but I would like to upload file with a max_size of 70Go. I tried to upload 10Go files, it works. I tried to upload 20Go files, and "scrf verification failed" happened. So I have several questions : Where does this issue could come from? Given that it takes a lot of time to transfer files, could the srcf_token be "outdated"? Do you have some ideas/pointers in order to solve this issue? -
Site not Working after SSL settings
I need some help in order to fix my production SSL settings. I have put these settings and when i enable them the production site doesnt work. I erased them, the site is working only on http. Is this right? Why this happens on the production site? CORS_REPLACE_HTTPS_REFERER = True # HOST_SCHEME = "https://, http://" HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True I would appreciate if you can help me! Thanks! -
Creating multiple forms with a single model
I want to create multiple forms using single model. Is it possible? First I made a model including all the fields I need. models.py class AcademicsUpto10(models.Model): PRE_PRIMARY_SUBJECT_CHOICES = ( ('Abacus', 'Abacus'), ('Handwriting Basic', 'Handwriting Basic'), ('English Phonetics', 'English Phonetics'), ('English', 'English'), ('KG Academic Class', 'KG Academic Class'), ) SUBJECT_1TO5_CHOICES = ( ('All subjects', 'All subjects'), ('Vedic Maths', 'Vedic Maths'), ('Mathematics', 'Mathematics'), ('Science', 'Science'), ('English', 'English'), ('Hindi', 'Hindi'), ('Environmental Studies', 'Environmental Studies'), ('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'), ('Handwriting English/Hindi', 'Handwriting English/Hindi'), ) SUBJECT_6TO10_CHOICES = ( ('Mathematics', 'Mathematics'), ('Science', 'Science'), ('Computer Science', 'Computer Science'), ('English', 'English'), ('Social Science', 'Social Science'), ('Sanskrit', 'Sanskrit'), ('Environmental Studies', 'Environmental Studies'), ('French', 'French'), ('German', 'German'), ('Spanish', 'Spanish'), ('Mathematics - Science (Combo)', 'Mathematics - Science (Combo)'), ('Olympiad Maths/Science', 'Olympiad Maths/Science'), ) BOARD_CHOICES = ( ('CBSE', 'CBSE'), ('ICSE', 'ICSE'), ('State Board', 'State Board'), ('International Board', 'International Board'), ) GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ('Flexible to get the best tutor', 'Flexible to get the best tutor'), ) DAY_CHOICES = ( ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ('Flexible on days to get the best tutor', 'Flexible on days to get the best tutor'), ) SLOT_CHOICES = ( ('Early Morning (6AM-8AM)', … -
Adim page in website created using django shiws the old,basic version
I have used django to make a website. Initially I got a newer version of the admin page. But now i get some older,basic version of it. I have made no changes in the program. Help me get the newer version of the admin page. CLICK HERE FOR THE NEW VERSION TYPE OF ADMIN PAGE I WANT(TAKEN FROM INTERNET) CLICK HERE FOR THE VERSION I GET AT PRESENT(BASIC VERSION) -
Populate hidden field with javascript array
I'm using django to submit a list of graphics/titles to a player in a table like this... <table> {% for title in titles %} <tr><form action="{% url 'show_title' %}" method="POST"> {% csrf_token %} <td width="1%"><input type="image" src="{% static 'css/img/CG-Play.png' %}" border="0" alt="Submit" /></td> <td width="20%">{{title.name }}</td><td width="78%">{{title.occupation }}</td> <td><input type="checkbox" class="delete" name="delete" value="{{ title.id }}" /></td> <input type="hidden" name="f0" value="{{ title.name }}" /> <input type="hidden" name="f1" value="{{ title.occupation }}" /> </tr> </form> {% endfor %} </table> included in each form is a submit image/button that sends the correct info in the hidden fields to the player. Also included is a checkbox with the class "delete" that I want to access in another form to delete the chosen/checked titles. Due to the HTML layout, the form for delete is in a different location, so I want to use javascript to gather the "{{ title.id }}" data present in the form above, and send the data in a hidden field in form Nr. 2 <form action="{% url 'delete_titles' %}" method="POST"> {% csrf_token %} <input type="hidden" id="input_form_1" name="java_array" value="java_values" /> <button type="submit" class="actionbutton deletebutton" name="delete_titles" onclick="return confirm('Delete (' + $(':checkbox:checked').length + ') title(s) - Are you sure?')" >Delete Titles</button> </form> I tried with … -
Airflow UI on subdomain
I am trying to configure airflow on my ubuntu server with multiple virtual hosts enabled. I want to enable the airflow UI to check and control my DAGs. How can I set my web server address to load airflow UI. My domain is : test.abcd.com and I want my Airflow ui to be loaded at test.abcd.com:8080/admin -
Explication Models and queries in django
I have question and problem at the same time, I have two models in deferents, projects like this PROJECT: TransactionMaster.models => TransactionMaster class TransactionMaster(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) trans_status = models.BooleanField() trans_name = models.CharField() PROJECT: TransactionDetails.models => TransactionDetail from app.transactionMaster.models import TransactionMaster class TransactionDetail(models.Model): transaction = models.ForeignKey(TransactionMaster, on_delete=CASCADE) current_status = models.IntegerField() transdetail_name = models.CharField() how Can I do the next sql query SELECT * FROM User as u inner join TransactionMaster as tm in u.id=tm.user_id inner join TransactionDetail as td in tm=td.transaction_id where tm.trans_status=td.current_status and SELECT * FROM TransactionMaster as tm inner join TransactionDetail as td in tm.id=td.transaction_id where tm.trans_status=td.current_status I try the second query like this: TransactionDetail.object.filter(TransactionMaster__id=transaction_id, trans_status=TransactionMaster__current_status) Please help me with this queries, and could you answer me what can I do in models in the different project, please. thanks for your attention Angel Rojas -
Django & Js : use cleaned_data instead of request.POST on simple HTML inputs
i've created a form in forms.py , and after submiting the form, the values are inserted in my database smoothly, using form.cleaned_data. my template has a button (called : "ajouter une ligne") that adds a new line (the line contains a form similar to the original one). this action (of adding line) is coded by Js. my problem is ,when i want to submit the final form that contains the original line and the second . it only submits the first one, because the first ligne is created on forms.py so on submition it's submited with clean_data . However the second line is created on the template using js directly so form.cleaned_data doesn't work on it. here is my template original row : <form action="/veentes" method="POST" enctype="multipart/form-data">{% csrf_token %}{{ form.non_field_errors }} <table style ="border-collapse: separate;border-spacing: 15px;" id="div1"> <tr><td width="5%">N P</td><td width="25%">Désignation</td><td width="8%">Date de Facture</td><td width="10%">Montant HT</td><td width="10%">TVA</td><td width="10%">Montant TTC</td></tr> <tr style="border:1px solid black;" > <td><div class="col-xs-1"><b><p name="np1">1</p></b></div></td> <td> {% render_field form.designation1 class="form-control" id="inlineFormInputName" placeholder="désignation" name="designation1" %}{{form.degn.errors}} </td> <td>{% render_field form.datefacture1 class="form-control" id="inlineFormInputName" placeholder="Date de Facture" name="datefacture1" %}{{form.dateFac.errors}} </td> <td> {% render_field form.mht1 class="form-control" id="inlineFormInputName" placeholder="Montant HT" name="mht1" %}{{form.mht.errors}} </td> <td> {% render_field form.mtva1 class="form-control" id="inlineFormInputName" placeholder="TVA" name="mtva1" %}{{form.mtva.errors}} </td> <td>{% … -
Django ForeignKey Validation For Multiple Databases
I have a Django 1.11 app which configure for using multiple database for different clients. In the user setting, I has defined a field to specify which database the user should use. For example, in setting.py I have the following settings: DATABASES = { 'default': { .... database setting .... }, 'DB_A': { .... database setting .... }, 'DB_B': { .... database setting .... }, } I have a model that has two tables: class Customer(models.Model): customer_name = forms.CharField(), . . .... class Order(models.Model): order_no = models.CharField(), customer = models.ForeignKey('Customer') . . .... Then I have a model form for the Order: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['order_no', 'customer', ....] widgets = { 'order_no': forms.TextInput(), 'customer': forms.Select(), .... In the view function, i use manual select of database to get the table data: def order_edit(request): customer_list = models.Customer.objects.using(request.session['db']).all() if request.method == 'POST': form = forms.OrderForm(request.POST) if form.is_valid(): form.save(using=request.session['db']) return redirect('/') else: form.fields['customer'].queryset = customer_list return render(request, 'order_edit.html', {'form': form}) else: form = forms.OrderForm() form.fields['customer'].queryset = customer_list return render(request, 'order_edit.html', {'form': form}) In the template 'order_edit.html', I have the field: <form> {{ form.customer }} {{ form.order_no }} {{ form.customer.errors }} {{ form.order_no.errors }} </form> For example, user … -
AttributeError: 'NoneType' object has no attribute 'split' Getting Error unknowingly on CMD. How to resolve it?
[21/Mar/2018 16:28:54] "GET /static/chapters/svg/h8-b-01.svg HTTP/1.1" 404 1786 [21/Mar/2018 16:29:10] "GET /static/chapters/images/newh-down-indicator-b.svg HTTP/1.1" 200 1028 [21/Mar/2018 16:32:47] "POST /myaccount/signup/ HTTP/1.1" 302 0 [21/Mar/2018 16:32:47] "GET / HTTP/1.1" 200 23860 Not Found: /svg/reasoning_skill_shadow.svg [21/Mar/2018 16:32:48] "GET /static/chapters/svg/h8-b-01.svg HTTP/1.1" 404 1786 [21/Mar/2018 16:32:48] "GET /svg/reasoning_skill_shadow.svg HTTP/1.1" 404 3890 [21/Mar/2018 16:32:48] "GET /static/chapters/js/newh.js HTTP/1.1" 200 8000 Not Found: /svg/question_ans.svg [21/Mar/2018 16:32:48] "GET /svg/question_ans.svg HTTP/1.1" 404 3860 Traceback (most recent call last): File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [21/Mar/2018 16:32:48] "GET /static/chapters/js/newh.js HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 59852) Traceback (most recent call last): File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Arun Pandey\AppData\Local\Programs\python\python36\lib\wsgiref\handlers.py", … -
Django model filter avoid join when filtering by relation id
Django ORM query projects = Project.objects.filter(category__id=1111) This generates following sql query, [join used] """" select * FROM "project" INNER JOIN "category" ON ( "project"."category_id" = "category"."id" ) WHERE "project"."category_id" = 1111 """" Is it possible to avoid join and get result like this? """" select * FROM "project" WHERE "project"."category_id" = 1111 """" -
Django & Postgres: persisting 'ProgrammingError: column does not exist'
I know this question has been asked on SO before however I have tried everything that has been suggested in the answers and none seem to work. Problem: I have a model class called 'Accomm' in my Django project where I have a number of objects stored. On the web pages where I try to retrieve one or more instances of 'Accomm' then the following error is raised... ProgrammingError at / column objects_accomm.description does not exist LINE 1: ...omm"."id", "objects_accomm"."mapped_location_id", "objects_a... This problem started to occur when I migrated a new field 'description' to the 'Accomm' model. Tried solutions: I have attempted to do the following things... clear all Django migrations (using the --zero and --empty commands); clear the database (PostgreSQL 10); clear both the migrations and database; changing the name of my database in the Django project settings.py file. None of these seem to work. I have also followed tutorials here, here and here. Full error: Django Version: 1.11.7 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.humanize', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'rest_framework', 'accounts', 'maps', 'objects', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in … -
Unique together in Django User Model
I want to update Django User table, and add another field into it. This is how I do. class User(AbstractBaseUser): platform = models.CharField(max_length=10) Now, since there's a field USERNAME_FIELD which takes a unique field. However, I want that username and platform should be unique_together, not just username. How can I achieve that? -
Django: __init__() got an unexpected keyword argument 'request'
I am trying to have two forms in one class based view. My view is: class ListAndCreate(CreateView): model = xmpp_buddy_groups form_class = xmpp_buddy_groups_form second_form_class = sip_extension_form template_name = "xmpp/index.html" success_url = reverse_lazy('xmpp:index') def get_context_data(self, **kwargs): context = super(ListAndCreate, self).get_context_data(**kwargs) context['object_list'] = self.model.objects.all() extension = SipExtension.objects.values_list('sip_extension', flat=True) for buddy_groups in group_names: for sip in buddy_groups.sipextension_set.all(): sip_extension = sip.sip_extension print(sip_extension) context['extension'] = extension SipExtension.objects.exclude(sip_extension__in=extension) print(extension) context['form'] = self.form_class(request = self.request) context['form2'] = self.second_form_class(request=self.request) context['extensions'] = SipExtension.objects.exclude(sip_extension__in=extension) return context I am getting error init() got an unexpected keyword argument 'request'. Where am I going wrong? -
Best Practice - Router: with Django Rest Framework for Many-to-Many relationship
I am developing a Restfull API with Django and Django Rest-Framework and DRF. I have the following models. class Account(models.Model): [...] class Course(models.Model): sudents = models.ManyToManyField(Student, through='StudentCourse', blank=True) class StudentCourse(models.Model): student = models.ForeignKey(Account) course = models.ForeignKey(Course) As you can see, the course can be created without students. But Students should be able to subscribe the course later. api/accounts/<username>/courses #-> return list of courses the student has subscribed api/courses/<id>/accounts #-> return a list of all students in the course api/courses/<id>/accounts/<username> #-> create StudentCourse relationship How do I have to implement the views, what's the best practice to create the relationship (focus on the routes)? Should there be an extra API endpoint for the StudentCourse-Model or is that okay? -
How to correctly consume external API pagination?
I wonder what is the correct way to consume external API pagination. I have a "Service A" API which returns paginated list of objects. I have a "Service B" which gets data from "Service A" API. Now i would like to implement pagination in "Service B" but i have no idea how should it be done. Let's assume that "Service A" returns 10 objects per page and "Service B" also should display 10 objects per page. Thank you -
Django query selecting values and objects
I have a problem with the queries when selecting values and objects. Here is a sample structure: class Property(models.Model): name = models.CharField(max_length=70, blank=True, verbose_name="Property Name") type = models.CharField(max_length=10) class Agreement(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name="prop") renter = models.ForeignKey(User, verbose_name="Kiracı", related_name = "renter01") Here is the first filter. qs1 = Agreement.objects.all() This one returns property and renter as objects. So I can refer the object details such as for q in qs: print(q.renter.firstname) Here is the second filter. When I need only some fields I use this filter: qs2 = Agreement.objects.all().values('renter',...) In that case the query returns the pk value of the renter user; and I cannot use it as object. Is there a way that I can select certain columns and keep the objects in it as objects? -
Django - HTML template form does not pass content to django view
I'm trying to make a Django application, but I have an Issue that template doesn't pass it's content to view. this is my form.. <form action="{% url 'view-job' %}" method="post" enctype=application/x-www-form-urlencoded> {% csrf_token %} <div> <label for="name">Job name: </label> <input type="text" id="name" /> </div> <div> <label for="owner">Owner: </label> <input type="text" id="owner" /> </div> ... and this is my post handling view (views_job.py) def job(request, pk=None): if request.method == 'GET': return get(request, pk) elif request.method == 'POST': return post(request) ... and post(request) def post(request): #data = json.loads(request.body.decode("utf-8")) #data = load_json(request) new_job = create_new_job(request) #new_job = create_new_job(request) if new_job != False: return new_job else: return HttpResponse(status=500) create_new_job(req) def create_new_job(req): config = parse_config() try: queryset = Job.objects.create( name=req.POST.get('name'), owner=req.POST.get('owner'), execute_date=req.POST.get('execute_date'), created_date=timezone.now(), master=req.POST.get('master') if 'master' in req.POST != None else config[DEFAULT][MASTER], deploy_mode=req.POST.get('deploy_mode') if 'deploy_mode' in req.POST != None else config[DEFAULT][DEPLOY_MODE], conf=req.POST.get('conf'), classpath=req.POST.get('classpath'), app_arguments=req.POST.get('app_arguments'), user_params=req.POST.get('user_params'), status=READY, ) #queryset.save() except: print("Error") print(req.POST.get('name')) return False return render(req, 'jobUI/job_details.html', { #'job':queryset } ) The console prints INFO 2018-03-21 18:48:29,033 basehttp 1321 140106696156928 "GET /jobUI/job/ HTTP/1.1" 200 1799 INFO 2018-03-21 18:48:30,208 basehttp 1321 140106696156928 "GET /jobUI/job/newjob/ HTTP/1.1" 200 1620 Error None ERROR 2018-03-21 18:48:47,499 basehttp 1321 140106696156928 "POST /jobUI/job/ HTTP/1.1" 500 0 I don't know why request.POST['name'] is None … -
"ManagementForm data is missing or has been tampered with" error
I running Django app with "tabbed_admin" app, recently I installed "admin_view_permission" I got below Error ManagementForm data is missing or has been tampered with Can anyone please suggest what is wrong with tabbed_admin with admin_view_permission. I did not add any custom view or validation in my app. -
cPickle datetime ImportError
I am having an ImportError when loading a pickle file, but the error only happens in one particular file, and not in other(s). So file1.py consists of a handful of function definitions to create a particular model given a pickle file with data. The other file, test.py, uses the functions in the previous file to create instances given different pickle files so those objects can be tested. I had never had any problem with cPickle in the test file up until now and I have no idea why this started happening. My test file just looks like this: import os from django.test import TestCase from file1 import import_object class PickleTest(TestCase): fixtures = [...] @classmethod def PickleTest(cls): super(DebugTest, cls).setUpClass() # instantiate an object for each pickle in the pickles directory path = 'pickles' for f in os.listdir(pickles_path): if f.endswith('.p'): import_object('{}/{}'.format(path, f)) def test(self): self.assertTrue(1 + 1, 2) The error happens when calling import_object. This is the import_object function in file1.py: def import_object(pickle_path): with open(pickle_path, 'rb') as f: d = pickle.load(f) return _import_object(d) And the error happens in the line d = pickle.load(f): ImportError: No module named datetime Import error messages are useless most times, but usually the issue is a circular … -
Why is my jinja variable not passing data to javascript?
I have a javascript function for plotting a graph on the basis of an array. The array has to be passed from the views.py in django. I am using jinja logic for passing the array from django. This is my views.py: def index(request): #style.use('ggplot') auth_tok = 'ozznMBmrYaK5QcBngxUq' df = quandl.get('WIKI/GOOGL',authtoken=auth_tok) df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume',]] df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0 df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0 df = df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']] forecast_col = 'Adj. Close' df.fillna(-99999,inplace=True) forecast_out = int(math.ceil(0.01*len(df))) df['label'] = df[forecast_col].shift(-forecast_out) x = np.array(df.drop(['label'],1)) x = preprocessing.scale(x) x = x[:-forecast_out] x_lately = x[-forecast_out:] df.dropna(inplace = True) y = np.array(df['label']) y = np.array(df['label']) X_train , X_test , y_train , y_test = cross_validation.train_test_split(x,y,test_size=0.2) clf = LinearRegression(n_jobs = -1) clf.fit(X_train , y_train) accuracy = clf.score(X_test,y_test) forecast_set = clf.predict(x_lately) print(forecast_set, accuracy , forecast_out) df['Forecast'] = np.nan last_date = df.iloc[-1].name last_unix = last_date.timestamp() one_day = 86400 next_unix = last_unix + one_day for i in forecast_set: next_date = datetime.datetime.fromtimestamp(next_unix) next_unix += one_day df.loc[next_date] = [np.nan for _ in range(len(df.columns) - 1)] +[i] df = df.values df.tolist() x1 = [2005,2007,2009,2011,2013,20150] y1= df[0] print(y1) return render(request, 'visit/index.html', {'onY' : y1 , …