Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-transmissions - UnknownTriggerException() in get_template()
from transmissions import message gives an import error. Should it be from transmissions.trigger import message When i do this i get more exceptions like UnknownTriggerException() in get_template. Here are the code snippets: (Am trying to implement my own channel here) from django.conf import settings from messaging.html_gen_methods import HtmlGen from transmissions.trigger import message from transmissions.models import TriggerBehavior class BaseEmail(object): def __init__(self, notification): self.target_user = notification.target_user self.sender = notification.trigger_user self.trigger = notification.trigger_name self.client = HtmlGen(self.sender, self.trigger) def check_validity(self): raise NotImplementedError() def send(self): try: res = self.client.run(to=self.to) if not res: raise ChannelSendException() return res except Exception as e: raise ChannelSendException("There was an error in sending sms to {}, error: {}".format(self.to, e.args)) @message('welcome-app-user',behavior=TriggerBehavior.TRIGGER_ONCE_PER_CONTENT) class WelcomeAppUser(BaseEmail): def check_validity(self): try: self.to = self.target_user.email return True except: return False -
write a program which takes a file and classify the file type to below Html/system verilog/CPP/python
I there. I just started with the machine learning with a simple example to try and learn. So, I want to classify the files in my disk based on the file type by making use of a classifier. The code I have written is, import sklearn import numpy as np #Importing a local data set from the desktop import pandas as pd mydata = pd.read_csv('file_format.csv',skipinitialspace=True) print mydata x_train = mydata.script y_train = mydata.label #print x_train #print y_train x_test = mydata.script from sklearn import tree classi = tree.DecisionTreeClassifier() classi.fit(x_train, y_train) predictions = classi.predict(x_test) print predictions And I am getting the error as, script class div label 0 5 6 7 html 1 0 0 0 python 2 1 1 1 csv Traceback (most recent call last): File "newtest.py", line 21, in <module> classi.fit(x_train, y_train) File "/home/initiouser2/.local/lib/python2.7/site- packages/sklearn/tree/tree.py", line 790, in fit X_idx_sorted=X_idx_sorted) File "/home/initiouser2/.local/lib/python2.7/site- packages/sklearn/tree/tree.py", line 116, in fit X = check_array(X, dtype=DTYPE, accept_sparse="csc") File "/home/initiouser2/.local/lib/python2.7/site- packages/sklearn/utils/validation.py", line 410, in check_array "if it contains a single sample.".format(array)) ValueError: Expected 2D array, got 1D array instead: array=[ 5. 0. 1.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single … -
Android to Django - always showing 401
I am trying to connect to my Django backend server from my app. While in local/dev with http connection the android app is getting connected to the server, it is rreturning HTT 401 error for all API calls via the app (except the login call). However, funny thing is using Postman, I'm being able to reach the prod server. Following is one of the code snippets (android): try{ URL targetUrl = new URL(targetURL); httpConnection = (HttpURLConnection) targetUrl.openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Authorization", "jwt " + mToken); httpConnection.setConnectTimeout(10000); //10secs httpConnection.connect(); Log.i(TAG, "response code:" + httpConnection.getResponseCode()); if (httpConnection.getResponseCode() != 200){ Log.e(TAG, "Failed : HTTP error code : " + httpConnection.getResponseCode()); return Constants.Status.ERR_INVALID; } //Received Response InputStream is = httpConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; while((line = rd.readLine()) != null) { response.append(line); //response.append('\r'); } rd.close(); Log.i(TAG, response.toString()); // Save the tenant details return parseTenantInfo(response.toString()); }catch (MalformedURLException e) { e.printStackTrace(); return Constants.Status.ERR_NETWORK; } catch (SocketTimeoutException e) { e.printStackTrace(); return Constants.Status.ERR_NETWORK; } catch (IOException e) { e.printStackTrace(); return Constants.Status.ERR_UNKNOWN; }finally { if(httpConnection != null) { httpConnection.disconnect(); } } Following is the target url: private static final String targetURL = Constants.SERVER_ADDR + APIs.tenant_get; Here, SERVER_ADDR is https://www.example.com/ and tenant_get is apitogettenantinfo/ I am always getting 401 … -
Many to Many Relationship in django model
I am currently trying to design my django models for the following situations: I have a class that is called User and every user has a unique userid. Now I want to do a ranking, based on the coins a user has. However, I want to make only users that are friends visible to the user when the user views the ranking. Therefore I am defining a class Friends that has a ManytoMany field “isfriend” that contains all the userids that the User is friends with. However, I feel that the way I am trying to do this is not the best way to go. Any suggestions how I should implement this? class User(models.Model): userid = models.CharField(max_length=26,unique=True) coins = models.IntegerField() def __str__(self): return self.userid class Friends(models.Model): isfriend = models.ManytoManyField(User) def __str__(self): return self.isfriend -
(HELP) Django Model Form does not recognize Image file
I created a Form using one of my models i.e (Post), for my blog website. The form is meant for writers to post articles. In that form there is an Image attribute where the writer can upload an image. However, when i try to upload an image and post it, i get a feedback saying "field required", i think the form is not recognizing the image am trying to upload onto the the database. please help: this is the form view from views.py: def formview(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return render(request, 'form.html', {'form':form}) this is from forms.py: from django import forms from .models import Post class PostForm(forms.ModelForm): image = forms.FileField class Meta: model = Post fields = ['category', 'title', 'body', 'image', 'author'] this from my models.py: class Post(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=100) pub_date = models.DateTimeField(auto_now_add=True) body = models.TextField() image = models.FileField() author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=1) def __str__(self): return self.title this is my forms.html template: <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <button type="submit">Post</button> this is my urls.py: from django.conf.urls import url from . import views app_name = 'posts' urlpatterns = [ url(r'^$', views.homeview, name='homeview'), url(r'^(?P<pk>[0-9]+)$', views.postview, … -
Unable to use static files in Heroku Django
I've read just about every stack post on this as there are a good amount of them. Nothing has worked for me. I'm not able to access my .js and .css files, even with DEBUG = True. My file structure is: \appname\static\js and \appname\static\css When issuing a heroku logs --tail I can see the error 2017-10-09T00:16:39.777590+00:00 app[web.1]: Not Found: /static/js/base.js I'm able to build and do a git push heroku master and I can see that my static files are added. Here is the output: remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: template dir: /tmp/build_3c87dc946f04c9e273dcb5bdd8979d51/static/template remote: source dir: /tmp/build_3c87dc946f04c9e273dcb5bdd8979d51/static remote: 64 static files copied to '/tmp/build_3c87dc946f04c9e273dcb5bdd8979d51/staticfiles'. remote: remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 51.7M remote: -----> Launching... remote: Released v47 remote: https://miningmanager.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/miningmanager.git 6f9da22..a6eda72 master -> master I believe I have my settings.py set up correctly as I am matching another app I am using on heroku and this other app works just fine. TEMPLATE_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, 'template') TEMPLATES … -
Filter Users for field in Django Admin
In my Django Admin I have a field to choose the Author if I create a new Article, but I can choose every User which is registered to my Page. The longer the list, the longer it takes, until I have found the right user in the list. How can I filter the list so that only members of the group authors are available? In the Django Documentation I could not find anything suitable. from django.contrib import admin from .models import Article, Comment class CommentInline(admin.TabularInline): model = Comment extra = 1 class ArticleAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['author']}), (None, {'fields': ['title']}), (None, {'fields': ['text']}), (None, {'fields': ['slug']}), ('Date', {'fields': ['published_date', 'created_date']}), ] list_display = ('title', 'published_date', 'created_date') list_filter = ['published_date', 'author'] search_fields = ['title'] inlines = [CommentInline] admin.site.register(Article, ArticleAdmin) -
Django migration error
I am trying to run: python manage.py migrate command on my production server but I get an error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/home/jundymek/domains/netnet24.eu/public_python/mainapp/admin.py", line 25, in <module> from .forms import SiteAddFormFull, EmailForm File "/usr/home/jundymek/domains/netnet24.eu/public_python/mainapp/forms.py", line 168, in <module> class EmailForm(forms.Form): File "/usr/home/jundymek/domains/netnet24.eu/public_python/mainapp/forms.py", line 175, in EmailForm email_template = forms.ChoiceField(choices=[(i, i) for i in config.EMAIL_TEMPLATES.splitlines( File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/django/utils/functional.py", line 235, in inner return func(self._wrapped, *args) File "/usr/home/jundymek/.virtualenvs/katalog/lib/python3.5/site-packages/constance/base.py", line 18, in __getattr__ raise AttributeError(key) AttributeError: EMAIL_TEMPLATES In my development environment there is no error. It appears only on production. … -
Web Development Interview [on hold]
I'm looking for a web developer to interview for a project I'm working on at school. I would really appreciate it if developers can take 10 min of their and get interviewed on Skype by myself. It won't take long. This would really help me on my research and help develop my product. Any volunteers? Best, Thanks! -
Server Error 500 when DEBUG=False
I am trying to deploy a web application to Heroku using Django. I can run the app locally just fine, but when I try to load it up live with DEBUG = False, I get a server 500 error. If I change the settings to DEBUG = True, it works. I would appreciate any help. Error log 2017-10-08T19:33:03.000000+00:00 app[api]: Build started by user me@email.com 2017-10-08T19:33:19.148973+00:00 heroku[web.1]: Restarting 2017-10-08T19:33:19.149620+00:00 heroku[web.1]: State changed from up to starting 2017-10-08T19:33:19.717815+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2017-10-08T19:33:19.732436+00:00 app[web.1]: [2017-10-08 19:33:19 +0000] [4] [INFO] Handling signal: term 2017-10-08T19:33:19.732487+00:00 app[web.1]: [2017-10-08 19:33:19 +0000] [8] [INFO] Worker exiting (pid: 8) 2017-10-08T19:33:19.732716+00:00 app[web.1]: [2017-10-08 19:33:19 +0000] [9] [INFO] Worker exiting (pid: 9) 2017-10-08T19:33:19.833095+00:00 app[web.1]: [2017-10-08 19:33:19 +0000] [4] [INFO] Shutting down: Master 2017-10-08T19:33:20.012423+00:00 heroku[web.1]: Process exited with status 0 2017-10-08T19:33:18.676112+00:00 app[api]: Release v30 created by user me@email.com 2017-10-08T19:33:18.676112+00:00 app[api]: Deploy 8f625678 by user me@email.com 2017-10-08T19:33:03.000000+00:00 app[api]: Build succeeded 2017-10-08T19:33:29.936137+00:00 heroku[web.1]: Starting process with command `gunicorn portfolio.wsgi` 2017-10-08T19:33:32.419548+00:00 app[web.1]: [2017-10-08 19:33:32 +0000] [4] [INFO] Starting gunicorn 19.6.0 2017-10-08T19:33:32.420072+00:00 app[web.1]: [2017-10-08 19:33:32 +0000] [4] [INFO] Listening at: http://0.0.0.0:23534 (4) 2017-10-08T19:33:32.420207+00:00 app[web.1]: [2017-10-08 19:33:32 +0000] [4] [INFO] Using worker: sync 2017-10-08T19:33:32.424142+00:00 app[web.1]: [2017-10-08 19:33:32 +0000] [8] [INFO] Booting worker with … -
Appear data in URL form bu using Django
I want to create a record and want to appear data in the form fields. How can I do that ? Do I need to write javascript for it. If you help me, really apprepriate it. Thanks for now. Here is models.py; class hesaplarim(models.Model): hesap_id = models.AutoField(primary_key=True) tc_no = models.IntegerField(unique=True) name = models.CharField(max_length=55) surname = models.CharField(max_length=55) phone_number = models.IntegerField() gender = models.CharField(max_length=5) Here is views.py; def home(request): form = HesapForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: form = HesapForm() return render(request, 'home.html', {'form': form}) Here is forms.py; class HesapForm(forms.ModelForm): ERKEK = 'ERKEK' KADIN = 'KADIN' gender_choices = ( (ERKEK, 'ERKEK'), (KADIN, 'KADIN') ) tc_no = forms.IntegerField(widget=forms.NumberInput) name = forms.CharField(widget=forms.TextInput) surname = forms.CharField(widget=forms.TextInput) phone_number = forms.IntegerField(widget=forms.NumberInput) gender = forms.ChoiceField(choices=gender_choices) class Meta: model = hesaplarim fields = ('tc_no', 'name', 'surname', 'phone_number', 'gender') Here is html file; <form method="post" class="form-horizontal" novalidate> {% csrf_token %} <div class="form-group"> <label for="id_tc_no">TC No:</label> {{ form.tc_no }} </div> <div class="form-group"> <label for="id_name">Ad:</label> {{ form.name }} </div> <div class="form-group"> <label for="id_surname">Soyad:</label> {{ form.surname }} </div> <div class="form-group"> <label for="id_phone">Cep Telefonu:</label> {{ form.phone_number }} </div> <div class="form-group"> <label for="id_gender">Cinsiyet:</label> {{ form.gender }} </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Kaydet"> </div> </form> -
Python convert python-amazon-simple-product-api results to json using Django
I am writing an API in Python Django and rest framework. I am using a python packaged called python-amazon-simple-product-api to access amazon advertising API. I am trying to feed the results into the rest framework and return the results as JSON Here is my code so far. class AmazonProductsViewSet(viewsets.ViewSet): def list(self, request, format=None): products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations") products = list(products) With this code I get the following error; TypeError: Object of type 'AmazonProduct' is not JSON serializable So I am trying to find a way of making the AmazonProduct object serializable or a better solution. -
Sending Ajax request but not able to receive at the receiver's end
I am using XMLHTTPRequest object to send some data from one of the templates in Django to another function in view.py This is a part of my template: function fun_submit() { var var_theme = document.getElementById("theme").value; var var_author = document.getElementById("author").value; var var_entry = document.getElementById("entry").value; var xmlhttp = new XMLHttpRequest(); xmlhttp.open('GET',"http://127.0.0.1:8000/first_page/something/",true); var data_upload = var_theme; xmlhttp.send('w='+encodeURI(var_theme)); window.location.href = 'http://127.0.0.1:8000/first_page/something/'; xmlhttp.close(); } and my view function is: def something(request): py_data = request.GET.get('w') return HttpResponse(py_data) when I return py_data, the page says None. I suspect the data is not getting transmitted. Any help or suggestion is really welcome. Thanks. -
Django rest framework bind decimal values from Brazilian currency format
I have to serialize data for a django rest framework application, some of values will be on Brazilian currency format like 1.234,45. How can I bind those number to work with django rest serializer and django models My model: class Produto(models.Model): prod_codigo = models.AutoField(db_column='prod_codigo', primary_key=True) prod_alias = models.CharField(db_column='prod_alias', max_length=50, null=False) prod_descricao = models.CharField(db_column='prod_descricao', max_length=255, null=False) prod_valor_venda = models.DecimalField(db_column='prod_valor_venda', max_digits=13, decimal_places=2) prod_valor_compra = models.DecimalField(db_column='prod_valor_compra', max_digits=13, decimal_places=2) prod_peso_b = models.DecimalField(db_column='prod_peso_b', max_digits=13, decimal_places=2) prod_peso_l = models.DecimalField(db_column='prod_peso_l', max_digits=13, decimal_places=2) My serializer: class ProdutoSerializer(serializers.Serializer): prod_codigo = serializers.IntegerField(read_only=True) prod_alias = serializers.CharField(required=False, allow_blank=True) prod_descricao = serializers.CharField(required=True, allow_blank=True) prod_valor_venda = serializers.DecimalField(max_digits=13, decimal_places=2) prod_valor_compra = serializers.DecimalField(max_digits=13, decimal_places=2) prod_peso_b = serializers.DecimalField(max_digits=13, decimal_places=2) prod_peso_l = serializers.DecimalField(max_digits=13, decimal_places=2) class Meta: model = Produto def create(self, validated_data): return Produto.objects.create(**validated_data) def update(self, instance, validated_data): instance.prod_codigo = validated_data.get('prod_codigo', instance.prod_codigo) instance.prod_alias = validated_data.get('prod_alias', instance.prod_alias) instance.prod_descricao = validated_data.get('prod_descricao', instance.prod_descricao) instance.prod_valor_venda = validated_data.get('prod_valor_venda', instance.prod_valor_venda) instance.prod_valor_compra = validated_data.get('prod_valor_compra', instance.prod_valor_compra) instance.prod_peso_b = validated_data.get('prod_peso_b', instance.prod_peso_b) instance.prod_peso_l = validated_data.get('prod_peso_l', instance.prod_peso_l) instance.prod_peso_q = validated_data.get('prod_peso_q', instance.prod_peso_q) instance.save() return instance -
How to correctly implement save() input data method from a contact form to Django SQLITe DB?
How to correctly implement save() to Django SQLITe DB method when taking data from a contact form input ? Last method tries to save input but it is not working. I have used codes from tutorial on Django contact form sending email. Need to add saving to database functionality. # view from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm from .models import SendEmail def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['bioinformatics_bel@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def success(request): return HttpResponse('All right! Thank you for your message.') def savedata(request): # want to save data input into the SQLIte database!! here is something wrong if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] message_object = SendEmail(from_email = from_email, subject = subject, message = message) message_object.save() return HttpResponseRedirect('success') #else: form = ContactForm() # unbound form return render(request, "email.html", {'form': form}) # template <h1>Submit identifier for the data processing</h1> <form method="post"> … -
How to insert a button in a dropdown selected option in Django?
I would like to insert a dropdown in Django that will return me to a page, and I am inserting a button that will lead to that page, but when I do this I return to the page I am currently in. index.html {% if lista_de_provas %} <form method='post' action=''> {% csrf_token %} <select class="form-control" name="prova_selecionada" id="prova_selecionada"> {% for prova in lista_de_provas %} <option id="{{prova.idProva}}" name="listaProvas" value='{{prova.idProva}}' desabled>{{prova.tipoProva}} {{prova.anoProva}}</option>Mdjss.199 {% endfor %} </select> <input id="selProva" type="button" value="Confirma" onclick = "location.href ='{{prova.idProva}}';" /> </form> {% endif %} views.py def index(request): lista_de_provas = Prova.objects.all() cprova = request.POST.get('idProva') if request.method == 'POST': sprova = Prova.objects.get(cprova = cprova) sprova.select() return redirect('polls/detalhes.html') else: form = ProvaForm() return render(request, 'polls/index.html',{'form':form,'lista_de_provas': lista_de_provas}) -
Django how to time user actions
I code something like www game and I have a problem. How can I time user actions? For example - User do action A. And he can't do this action again for one hour. After that he can again. -
django not able to load static file
I am trying to go though Django tutorial which explains about static files but when I am trying implement that I am getting following error: [08/Oct/2017 23:08:27] "GET / HTTP/1.1" 200 365 [08/Oct/2017 23:08:27] "GET /static/polls/sytle.css HTTP/1.1" 404 1658 My Django project structure: (removing irrelevant files and folders). rehman@linux-desktop ~/django_proj/my_site $ tree . ├── db.sqlite3 ├── manage.py ├── my_site │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── polls │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── static │ │ └── polls │ │ ├── images │ │ │ └── background.jpg │ │ └── style.css │ ├── templates │ │ └── polls │ │ ├── details.html │ │ ├── index.html │ │ └── result.html │ ├── tests.py │ ├── urls.py │ └── views.py └── templates settigs.py (partial contents): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' url.py: urlpatterns = [ url(r'^', include('polls.urls')), url(r'^admin/', admin.site.urls), ] index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Polls</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static … -
How to setup Django silk profiler
I am completely new to Django and profiling. I have completed all the steps mentioned in the document for setting up the silk profiler. https://github.com/jazzband/silk I did not find any error when I ran the manage.py run server command But when I open the browser and call the necessary api, I don't find anything related to silk. I have no idea where to find the results. Any help is greatly appreciated -
Django form doesn't show up
I'm working on some project and ended up with some issues. So my form doesn't display itself at all in my template. But I've created another form before and it works as it should! So my code: models.py class Project(models.Model): class Meta: db_table = "project" COLORS = ( ('R', 'Red'), ('B', 'Blue'), ('G', 'Green'), ('Y', 'Yellow') ) project_title = models.CharField(max_length=200) project_color = models.CharField(max_length=1, choices=COLORS) def __str__(self): return self.project_title forms.py class ProjectForm(ModelForm): class Meta: model = Project fields = ['project_title', 'project_color'] views.py def addproject(request): if request.POST: form_p = ProjectForm(request.POST) if form_p.is_valid(): form_p.save(commit=False) return HttpResponseRedirect('/') else: form_p = ProjectForm() context = { 'projects': Project.objects.all(), "form": form_p, 'username': auth.get_user(request).username, } context.update(csrf(request)) return render(request, 'index.html', context) urls.py urlpatterns = [ url(r'^addproject/$', views.addproject, name='addproject'),] index.html <form action="/addproject/" method="post"> {% csrf_token %} {{ form_p.as_table }} <button type="submit" class="btn btn-primary">Add Project</button> </form> -
Passing a Primary Key to a form template
This is an update from this questions, which I will amend if I find a complete answer for this issue - How do I 'Autofill' a CreateView field I have a Artist model, and I'm now trying to add a comment feature to the DisplayView using an ArtistComment modal and a CreateView form on a modal div. I think I'm really close to getting this to work, but I'm having a little issue passing the primary key from my artistdetail.html page to my artistcomment_form.html template. Any help with this, or tips for documentation pages to read would be greatly appreciated. urls.py: url(r'^artist-(?P<pk>[0-9]+)/$', login_required(views.ArtistDetailView.as_view()), name='artistdetail'), url(r'^artist-(?P<pk>[0-9]+)/artistcomment/add/$', login_required(views.ArtistCommentCreate.as_view()), name='artistcomment-add'), views.py: class ArtistCommentCreate(CreateView): model = ArtistComment fields = ['message',] def get_success_url(self): return reverse('events:artistdetail', kwargs={'pk': self.object.artist_id}) def form_valid(self, form, *args, **kwargs): form.instance.author = self.request.user form.instance.artist = get_object_or_404(Artist, id=self.kwargs.get('pk')) return super(ArtistCommentCreate, self).form_valid(form) artistdetail.html: <p id="commentfooter"><a href="{% url 'events:artistcomment-add' artist.id %}">Add A New Comment</a></p> artistcomment_from.html: {% block body %} <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="{% url 'events:artistcomment-add' pk %}" method="post" enctype="multipart/form-data" onSubmit="CloseModal();"> {% csrf_token %} {% include "events/form-template.html" %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> As far as I can tell, where I've entered … -
Django on apache io error
My day-old django project is already running on Apache 2. This is the general structure: root/apps/django/django_projects/Project ├── autocache │ ├── cache.py │ └── cache.txt ├── conf ├── manage.py ├── Project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ └── ... ├── myapp │ ├── __init__.py │ ├── apps.py │ ├── views.py │ ├── urls.py │ └── ... When myapp is shown, I simply show the contents of cache.txt. This is what I have to do that: from django.shortcuts import render from django.http import HttpResponse from django.conf import settings import os def index(request): cache_path = os.path.join(settings.CACHE_DIR, 'cache.txt') with open(cache_path, 'r') as cache: return HttpResponse(cache.read()) return "Could not open file" The problem is that an exception is being thrown: Request Method: GET Request URL: http://myip/Project/subwayapp/ Django Version: 1.11.5 Exception Type: IOError Exception Value: [Errno 13] Permission denied: '/root/apps/django/django_projects/Project/autocache/cache.txt' Exception Location: /opt/bitnami/apps/django/django_projects/Project/myapp/views.py in index, line 8 Python Executable: /opt/bitnami/python/bin/python Python Version: 2.7.13 However, this is the output of ls -l for cache.txt: -rwxrwxr-- 1 root root 17 Oct 8 16:06 cache.txt As I understand it, this means that It is a file The owner can read, write, and execute it The group can read, write, and execute it … -
Django Rest Framework - Get details from another model with Reverse Lookup
I have 3 models book, language, book_language. when i try to get list of books i am unable to get associated languages with django_rest_framework models.py class Book(models.Model): title = models.CharField(max_length=200) year = models.IntegerField() class Language(models.Model): language_name = models.CharField(max_length=100) class Book_language(models.Model): book = models.ForeignKey(Book) language = models.ForeignKey(Language) serializers.py class BookLanguageSerializer(serializers.ModelSerializer): class Meta: model = Book_language fields = ('id', 'language',) class BookSerializer(serializers.ModelSerializer): languages = BookLanguageSerializer(source='language_set') class Meta: model = Book fields = ('id', 'title', 'languages') desired ouput: [{ id: 1, title: 'some book 1', languages: [ { id: 1, language: 'english' }, { id: 2, language: 'chinese' } ] }, { id: 2, title: 'some book 2', languages: [ { id: 1, language: 'english' }, { id: 2, language: 'chinese' } ] }] Instead of above output, i am only getting list of books without languages array like below. [{ id: 1, title: 'some book 1', }, { id: 2, title: 'some book 2', }] Also guide where can i find better examples, I tried to read the DRF doc but its not beginner friendly. -
Django: Query involving Foreign Key
I have models.py class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc=models.CharField(max_length=5,choices=LOCATION) manager_id=models.ForeignKey('self',null=True,blank=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P') ltype=models.CharField(max_length=2,choices=LEAVE_TYPE) class notify(models.Model): sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') date_time=models.DateTimeField(auto_now_add=True) viewed=models.CharField(max_length=2) I want the employee id of receiver_id as receiver_id is a foreign key... When I query notify.objects.filter(receiver_id__employee__emp_id=1) I am getting empty queryset but I want the tuples with emp_id=1. -
Pass request as a parameter to Model class
[1] I am trying to implement credentials authentication by storing it in the session request. Is there any way I can get it to my model Class? [2] I am also trying to get dropdown from Courses class but I am getting it as a box to enter text. What am I doing wrong? urls.py from django.conf.urls import url import views urlpatterns = [ url(r'^$', views.auth, name='Authenticate'), url(r'^courses', views.showCourseList.as_view(), name='GetCourses'), url(r'^assignments/', views.showAssignmentsList, name='GetAssignments'), ] models.py def getCourses(): http = credentials.authorize(httplib2.Http()) service = discovery.build('classroom', 'v1', http=http) results = service.courses().list().execute() return map(lambda x: (str(x['name']), str(x['name'])), results.get('courses', [])) class Courses(models.Model): List_Of_Courses = models.CharField(choices=getCourses(), max_length=10) views.py class showCourseList(CreateView): http_method_names = ['get', 'post', 'head', 'options', 'trace'] def get(self, request, *args, **kwargs): pass model = Courses fields = ['List_Of_Courses'] template_name = 'CourseList.html' CourseList.html <form action="/assignments/" method="get"> {{ form.as_p }} <input type="submit" value="Select Course" /> </form>