Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
exclusion of two different querysets
I am making a GK test interface with django. In this, the questions once submitted to a user should not appear again. This table stores all the questions once submitted, and all other data related to that. class UserLog(models.Model): session = models.ForeignKey(to = UserTestSession, default = None) question = models.OneToOneField(to = MCQuestion) user = models.ForeignKey(to = User) selected_option = models.IntegerField(blank=True,null=True) answer_status = models.BooleanField(default = True) quest_submit_time = models.DateTimeField(blank=False) ans_submit_time = models.DateTimeField(blank = True,null=True) def getDiff(self): diff = self.quest_submit_time - self.ans_submit_time return divmod(diff.days * 86400 + diff.seconds, 60) time_elapsed = property(getDiff) def __str__(self): return str(self.user) + " " + str(self.question) class Meta: unique_together = ('question','user',) I tried this line to exclude. unsubmitted_questions = list(all_questions.exclude(question__in = submitted_questions)) -
Shall I delete unused files created automatically?
Django==1.11.5 In the project there are unused files. For example, I use Django login/logout function's but I have created a special login template. I don't use: models.py, views.py, tests.py. But I did register the app for Django to find templates. Could you tell me whether I should delete these unused files? Django style guide keeps silent on this matter. Deleteing seems logical. But I decided to ask you just to be on the safe side. -
Django form doesn't runs form.is_valid
I'm working on a Django custom form: I have debugged that form.is_valid function is not running even all the data comes in the view. models.py choices = ( ('yes', 'Yes'), ('no', 'No'), ('not sure', 'Not Sure'), ) class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') relevant_feedback = models.TextField(blank=True) created_at = models.DateTimeField(default=timezone.now, editable=False) forms.py class TagForm(forms.ModelForm): class Meta: model = TaggedArticle fields = ('user', 'category_fit', 'article', 'relevant_feedback') widgets = { 'category_fit': forms.RadioSelect() } views.py def post(self, request, *args, **kwargs): if request.method == 'POST': post_data = request.POST.copy() post_data.update({'user': request.user.pk}) form = forms.TagForm(post_data) print('request recieved') if form.is_valid(): tag = TaggedArticle() tag.user = request.user article = Article.objects.all().filter(id=form.cleaned_data['article']) tag.category_fit = form.cleaned_data['category_fit'] tag.article = article tag.relevant_feedback = form.cleaned_data['relevant_feedback'] tag.save() return HttpResponse('Tagged Successfully!', status=200) Help me, please! Thanks in advance! -
I cannot access http://localhost:8000/accounts/profile
I cannot access http://localhost:8000/accounts/profile.When I access this address,it send to http://localhost:8000/accounts/login/?next=/accounts/profile/ .I really cannot understand why.I wrote in urls.py urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^login/$', views.login,name='login'), url(r'^profile/$', views.profile, name='profile'), ] in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return redirect('profile', context) if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return redirect('profile', context) context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) def profile(request): context = { 'user': request.user, } return render(request, 'registration/accounts/profile.html', context) in html <main> <div class="container"> <div class="detailimg col-xs-12"> <img class="small_img" src="{% static 'detail.jpg' %}" alt="Detail" /> <div class="absolute-fill vertical-center-container"> <p class="hthree">XXX <span class="hthree_small"> <br>YYY <br>ZZZ</span> </p> </div> </div> <div class="bodyele col-xs-12"> <a class="button-primary" href="{% url 'accounts:profile' %}">Profile</a> <a class="button-primary" href="{% url 'accounts:kenshinresults' %}">See</a> <a class="button-primary" href="{% url 'accounts:kenshinresults' %}">Know</a> </div> </div> </main> When i put Profile tag, this happens.What is wrong in my code?urls.py&views.py&html are in accounts. -
API for live news headlines
I am working on an application in Django and Angular frontend associated with stock prices. I need to have access to the world news. Currently, I am looking for headlines API. I would like to use it in production. It is important for me to have a possibility to add historical data to my database and after that I would like to add every day data to table to have current data in it. I found newsapi.org but I am not sure whether I can use it for commercial pursposes? Or maybe can you recommend anything else? -
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>