Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A real example fro virtual environment(Django)
How to run app from virtual to existing environment? -
Django ImportError: cannot import name 'ModelForm'
I am pretty much new for Django and trying to create fields to add a new movie to the existing model. It shows an error : ImportError: cannot import name 'ModelForm' #forms.py file: from django import forms from django import ModelForm from .models import Movie class MovieForm(ModelForm): class Meta: model = Movie fields = ['genre', 'price', 'rent_time', 'flag'] class CustForm(forms.Form): f_name = forms.CharField(label='First_Name', max_length=50) l_name = forms.CharField(label='Last_Name', max_length=50) address = forms.CharField(label='Address', max_length=125) cell = forms.IntegerField(label='Cell') #------------------------------------------------------------------------ #models.py file: from django.db import models from django.forms import ModelForm class Customer(models.Model): f_name = models.CharField(max_length=50) l_name = models.CharField(max_length=50) address = models.CharField(max_length=125) cell = models.IntegerField(blank=True, null=True) class Movie(models.Model): genre = models.CharField(max_length=50) price = models.FloatField(blank=True, null=True) rent_time = models.DateTimeField(auto_now_add=True, blank=True) flag = models.BooleanField(default=True) user_id = models.ForeignKey('Customer', on_delete=models.SET_NULL, null=True) #------------------------------------------------------------------------ #views.py file: from django.shortcuts import render from .models import Customer, Movie # from django.http import HttpResponseRedirect from .forms import MovieForm, CustForm def dashboard(request): customer_data = Customer.objects.all() context = {'Customer_List': customer_data} return render(request, 'movie_renting_app/home.html', context) def movie_list(request): movie_data = Movie.objects.all() context = {"Movie_List": movie_data} return render(request, 'movie_renting_app/all_movies.html', context) def rented_movies(request): rented_movie = Movie.objects.filter(flag=True) context = {"Rented_Movies_List": rented_movie} return render(request, 'movie_renting_app/rent.html', context) def add_movies(request): if request.POST: form = MovieForm() print(request) # return movie_list(request) else: form = MovieForm() return render(request, … -
How to handle request having nested images using Django Writable nested serializers? And how to post them using postman?
I want to make a MCQ Examination Application. I have a models as : Question -> To save question statement. QuestionImage-> To save figures or diagrams related to question. (can be multiple images) Answer -> To save the options and correct answer. Options can be in the form of images (Each option can have only one image). Query: How to save the images for the Answers model? And further if possible to send this data through POSTMAN or should use any other method. My files are as follows: models.py class Question(models.Model): question = models.CharField(max_length=2000, null=False) class QuestionImage(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) image = models.ImageField(null=True) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='Answers') answer = models.CharField(max_length=1000,null=True) is_correct_answer = models.BooleanField(default=False) image = models.ImageField(null=True) views.py class AddQuestionCreateAPIView(CreateAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer serializers.py class QuestionImageSerializer[...] class AnswerSerializer[...] class QuestionSerializer(ModelSerializer): QuestionImages = QuestionImageSerializer(many=True, read_only=True) QuestionAnswers= QuestionAnswerSerializer(many=True , read_only=True) class Meta: model = Question fields= ['question','QuestionImages','QuestionAnswers',] def create(self, validated_data): question= Question.objects.create(**validated_data) #for saving Question related images images_data = self.context.get('view').request.FILES request = self.context.get('request') for image_data in images_data.values(): QuestionImage.objects.create(question=question, image=image_data) #for saving the answers if request.data.get('QuestionAnswers'): QuestionAnswers_data = request.data.get('QuestionAnswers') for QuestionAnswer_data in QuestionAnswers_data: QuestionAnswer.objects.create(question=question, **QuestionAnswer_data) return question Resources: For uploading and serializing multiple images I have taken … -
django summing over values or function values
In a django-project I have the following line: person_lista = Personal.objects.annotate(tjgtid=Sum('personyear__tjgtim')) When the class PersonYear contained the variable tjgtim = models.FloatField(default=0) this worked fine. But now I have changed it so that it is a function: def tjgtim: return ..... and now it does not work. Why is that? What should I do differently? Thanks in advance, -anders -
Django Admin StackedInline Not Loading Add Another model, Uncaught TypeError: Cannot read property 'fn' of undefined
When I add a number of inlines to my django admin as shown below the Add another {model name} disappears. If I check the javascript console I see that I am getting the following error: Uncaught TypeError: Cannot read property 'fn' of undefined at inlines.js:20 at inlines.js:295 Here's my Django admin: @admin.register(models.Paper) class PaperAdmin(BaseLiteratureAdmin): class EditedPaperAdminInline(admin.StackedInline): model = models.EditedPaper extra = 0 class SupplementaryInformationAdminInline(admin.StackedInline): model = models.SupplementaryInformation extra = 0 class PaperNotesAdminInline(BaseNotesAdminInline): exclude = tuple( i for i in BaseNotesAdminInline.exclude if i != 'paper' ) class ReferencedPaperInline(admin.StackedInline): model = models.Paper.referenced_papers.through extra = 0 fk_name = 'from_paper' verbose_name = "Referenced Paper" verbose_name_plural = "Referenced Papers" inlines = ( EditedPaperAdminInline, # problem PaperNotesAdminInline, # ok single/together ReferencedPaperInline, # ok single/together SupplementaryInformationAdminInline, # problem ) Here's what I'd like to see: Here's what I'm seeing: And I found the solution--it's to change the order of the inlines in the inlines list, like so: inlines = ( PaperNotesAdminInline, # ok single/together ReferencedPaperInline, # ok single/together EditedPaperAdminInline, # problem SupplementaryInformationAdminInline, # problem ) The #comments next to each inline note that the PaperNotesAdminInline and ReferencedPaperInline are both 'OK' in that the Add another {model name} link still appears if they are included. The other two … -
Reverse for 'contents-occasion-step-1' with no arguments not found. 1 pattern(s) tried: ['myapp/create/step-1/(?P<current_object_id>\\d+)$']
In my django app I am trying to redirect to a view after user submits the form Error which I am getting Reverse for 'contents-occasion-step-1' with no arguments not found. 1 pattern(s) tried: ['myapp/create/step-1/(?P<current_object_id>\\d+)$'] The function from which I am redirecting view def create_object(request): if request.method == 'POST': form = DataBase(request.POST) if form.is_valid(): form_data = form.save(commit=False) form_data.created_by = request.user form_data.save() # save current object id in the session request.session['current_object_pk'] = form_data.pk manipulation_function(request, form_data) return redirect('contents-occasion-step-1', current_object_id = form_data.pk) else: form = DataBase() return render(request, 'my/create_object.html', { 'form': form }) My urls.py url(r'myapp/create/step-1/(?P<current_object_id>\d+)$', views.contents_occasion_step_1, name='contents-occasion-step-1') My views.py def contents_occasion_step_1(request, current_object_id): """View """ [My code below] return render(request, 'myapp/mytemplate.html', { 'variable_for_template': request.session['variable_for_template'] }) -
How to get model instance instead of name of model instance from values?
I have a model queryset (modela) with a field (modelb) that is a model instance (via a ForeignKey). I am looking for an alternative to calling modela_set.values('modelb') that gives a list of modelbinstance or unicode(modelbinstance) dictionaries (as in [{'modelb': modelbinstance},...] or [{'modelb': unicode(modelbinstance)}]). I can retrieve the values I want with the following, but there are many fields and I don't want to be querying for all of them (for performance reasons): l = [] for x in modela_set.all(): l.append(x.modelb) Doing the above appears to invoke the unicode function on each modelb instance (at least when I print). The following doesn't show the unicode or instance values that all() allows by default, and instead results in dictionaries in the form of [{'modelb': modelb.name},...]: l = modela_set.values('modelb') Since I do not want modelb.name values, this doesn't work for me. How can I get a list of dictionaries with either modelb instance or unicode(modelbinstance) values? Is there some other method I could use instead of values or values_list that doesn't involve selecting all the values? -
python newspaper module - get all the images from an article
By using newspaper module of python , I can get the top image from an article in the following way: from newspaper import Article first_article = Article(url="http://www.lemonde.fr/...", language='fr') first_article.download() first_article.parse() print(first_article.top_image) But I need to get all the images in the article. Their github documentation says : 'All image extraction from html' is possible. But I can't just figure that out. And i do no want to manually download and save the html files in hard drive and then feed the module with the files and get the images. In what way can I achieve that ? -
TypeError: __init__() takes 1 positional argument but 2 were given django
this is the urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^/', include('main.urls', namespace='Home')), ] this is the views.py from django.shortcuts import render,HttpResponse,render_to_response,HttpResponseRedirect from django.views.generic import TemplateView from main.models import * class leaflet(TemplateView): template_name = "file.html" When I wrote this code template not showing, it throws an error: __init__() takes 1 positional argument but 2 were given" could you find the error in my code? -
Trying to implement jsonschema with just filepaths
I've uploaded a json from the user and now I'm trying to compare that json to a schema using the jsonschema validator. I'm getting an error, UnboundLocalError: local variable 'json' referenced before assignment. This is my code so far: from __future__ import unicode_literals from django.shortcuts import render, redirect import jsonschema import json import os from django.conf import settings #File to store all the parsers def jsonVsSchemaParser(project, file): baseProjectURL = 'src\media\json\schema' projectSchema = project.lower()+'.schema' projectPath = os.path.join(baseProjectURL,projectSchema) filePath = os.path.join(settings.BASE_DIR,'src\media\json', file) actProjectPath = os.path.join(settings.BASE_DIR,projectPath) print filePath, actProjectPath schemaResponse = open(actProjectPath) schema = json.load(schemaResponse) response = open(filePath) json = json.load(response) jsonschema.validate(json, schema) I'm trying to do something similar to this question except instead of using a url I'm using my filepath. Also I'm using python 2.7 and Django 1.11 if that is helpful at all. -
extending User model using django-username-email Package
I am quite a beginner in django and I would really need your help.. I am trying to extends the User model provided by Django in order to log in a user only using Email and pass and not a username For that I am using the great package https://pypi.org/project/django-username-email that give a really easy way to do it. However I would like to extend it as well in order to add field such as 'job' I tried to do it that way but it does not help me to progress toward my goal. from django.db import models from django.contrib.auth import get_user_model # Create your models here. User = get_user_model() class CustomUser(User): position = models.CharField(blank=True, max_length=255) Could you please help me extend an extended UserModel ? Thx you -
Compare Substring of Dictionary Value
I want to compare a 'term' to the values of a dictionary, specifically, the substrings of the values. This is necessary because the formatting of the values varies across different modules. For instance: module1='Doe', module2='Jane Doe'. The term to compare in this case would be 'Doe'. How should I go about solving this issue? Thanks! search.html {% if tickets %} Tickets found: <table class="table"> <thead> <tr> <th>ID</th> <th>Company</th> <th>Summary</th> </tr> </thead> <tbody> {% for ticket in tickets %} <tr> <td> {{ ticket.id }} </td> <td> {{ ticket.company.name }} </td> <td> {{ ticket.summary }} </td> </tr> {% endfor %} {% endif %} </tbody> </table> views.py def search_bar(request): term = request.GET.get('term') if term: results = objCW.search_companies(term) + objCW.search_contacts(term) tickets = objCW.search_tickets_by_company(term) + objCW.search_tickets_by_contact(term) context = {'results': results, 'tickets': tickets} return render(request, 'website/search.html', context) else: context = {'': ''} return render(request, 'website/search.html', context) -
How to make an Instagram app with Django
I am brand new to Django. How would I build an app like Instagram and can scale automatically. Please recommend boilerplate code so I can easily create a look alike of it. Should I use txt file for my database? Thanks you If any of you don't know what Instagram is, here is the site: Instagram. It is a very popular photo sharing website. -
How Add language(spanish) in to tesseract
i'm try to install language spanish to tesseract, on this momento dont get error, only dont get the convertion(image to text) this is my code for convert: import pytesseract #from PIL import Image, ImageEnhance, ImageFilter try: import Image except ImportError: from PIL import Image from pytesseract import * #url of image jpg path = 'media/rules/temp.jpg' #get the text from image image = Image.open(path, mode='r') text = pytesseract.image_to_string(image, lang='spa') #temporal file txt text_file = open("media/rules/temporalPdf.txt", "w") text = re.sub("\s\s+", " ", text) text_file.write("%s" % text.encode('utf-8')) text_file.close() the file that i'm using for spanish is: spa.traineddata Link for download the language spanish this is a capture from my folder of tesseract: please a little suggest or link .. thanks !! -
Why am I getting this PicklingError?
I'm working on a Python/Django/Wagtail project, and I have some api to return some paginated articles. It goes like this: In URLs: url(r'^morearticles/', views.get_live_articles), In Views: def get_live_articles(request): context = {'articles': getLiveArticles(request) } return render(request, 'app/components/articles-live.html', context, content_type="text/html; charset=utf-8") The getLiveArticles function looks like this: def getLiveArticles(request): # Articles a = get_articles() #this is getting the articles correctly p = Paginator(a, 4) page_n = request.GET.get('page') try: articles = p.page(page_n) except Exception, e: articles = [] return articles However when hitting the api endpoint I get this: Traceback (most recent call last): File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/john/app/app/views.py", line 90, in get_live_articles context = {'articles': getLiveArticles(request) } File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/cache_utils/decorators.py", line 48, in wrapper cache.set(key, value, timeout, **backend_kwargs) File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/cache/backends/locmem.py", line 75, in set pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) PicklingError: Can't pickle <class 'wagtail.wagtailcore.blocks.base.RichTextBlockMeta'>: attribute lookup wagtail.wagtailcore.blocks.base.RichTextBlockMeta failed I've came upon the Pickling error before, but never quite understood what it is about. Any idea of what could be causing this? Let me know if I should provide … -
My Javascript only works on one element in a python embedded for loop in Django2
I'm iterating these html template cards using Python for loop and I have a javascript to go with it. The problem is that the javascript is only working on the first element (the script is basically getting the seeked position of the audio) and not the rest. I thought it was because I set an id of the template card instead of a class name, but I am still getting the same results. The Javascript is in the for loop. Maybe it shouldn't? Anyways here is my code: {% for song in songs %} <div class="col-md-4"> <div class="card mb-4 box-shadow"> <img class="card-img-top" id="img_size" src="{{ song.song_image.url }}" alt="Card image cap"> <div class="my-header"> <h3 id="song_title">{{ song.song_title }}</h3> <span id="pub_date">{{ song.publishing_date }}</span> </div> <div style="clear:both"></div> <hr /> <div class="card-body"> <p class="card-text">{{ song.song_description }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <audio class="myAudio" controls> <source src="{{ song.song_file.url }}" type="audio/mpeg"> <source src="{{ song.song_file.url }}" type="audio/wav"> Your browser does not support the audio element. </audio> <script> var vid = document.getElementsByClassName("myAudio"); function getCurTime() { alert(vid.currentTime); } function setCurTime() { vid.currentTime=5; } </script> </div> </div> </div> </div> </div> {% endfor %} -
Extract Mustache variable for use in Django template tag
I am implementing Algolia's search API for Django, and I have a certain Mustache variable {{ObjectID}} that corresponds to IDs for search results. I can only use via {% verbatim %} {{ObjectID}} {% endverbatim %} without having Django's template syntax conflicting. However, I also need this variable to construct a url for the ID, but the issue is that I can't easily pass the Mustache variable into a form usable directly with Django's templates. As an example, simply doing {% url "appName:method" {{ObjectID}} %} conflicts with Django's template syntax, but trying to ivnoke verbatim via {% url "appName:method" {%verbatim %} {{ObjectID}} {% endverbatim %} %} does not work either, since calling a template tag in a template tag is disallowed. I am also unable to store {{ObjectID}} as a temporary variable with a method or offshore url to a separate method, e.g. function generate (objectID){ return "{% url 'appName:method' objectID %}" } //usage of method <a href = "generate({% verbatim %}{{ObjectID}} {% endverbatim %})">link</a> since Django will process the url on sight and throw NoReverseMatch since objectID is not defined by Algolia yet. Is there a way to extract {{ObjectID}} such that it can be piped back into Django's url … -
Ayuda con las fechas en Python y django
Tengo una función a la cual quiero pasarle una fecha por parámetros, necesito pasarle en el formato , año,mes,día, hora, minutos, segundos, tengo q crear una función con todos esos parámetros o ahí una manera más sencilla y como quedaría la configuración de la URL en la documentación hablan de los grupos para las URL pero era Django 1.10 en las versiones 2+ no encuentro información -
Django form and internationalisation - wrong language for a label
I have a problem while displaying a form in my Django website. My forms.py form : from django import forms from django.utils.translation import ugettext_lazy class FiltreMonoForm(forms.Form): orth = forms.CharField(max_length=255, required=False, label=_('orth').capitalize()) My view in views.py: from .forms import FiltreMonoForm def monollist(request, page=1): if request.GET: form = FiltreMonoForm(request.GET.copy()) else: form = FiltreMonoForm() return render(request, 'lexics/listemonol.html', locals()) And in my template listemonol.html: {{ form.as_p }} When displaying, my form have the "orth" label in the wrong language. I added a translated variable in my view to verify, this one is in the correct language when I display it in my template. Someone has an idea to have my label in the correct language too ? Thanks -
AttributeError in DeleteView
I'm getting the following error whenever I try to delete an object of class AbstractThing in a DeleteView (e.g. in the admin area): AttributeError: 'OneToOneField' object has no attribute 'model' Relevant models and views: class AbstractThing(models.Model): class Meta: abstract = True color = models.CharField(max_length=6) class ConcreteThing(AbstractThing): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='concrete_things') class ConcreteThingDeleteView(DeleteView): model = ConcreteThing success_url = "…" I don't know what's happening since the error message is not specific at all. Any help is appreciated. -
How to use passport-bitbucket-oauth2 and DjangoREST
I want to add passport to my djangorest api however I'm having trouble finding any documentation to help to accomplish this task. Basically my questions is how to add the passport-bitbucket-oauth2 module into a djano api. -
How do to install geckodriver and chromedriver to your local environment
I am setting up Robot Framework within the same code base as a django app. When I run my sample test case I get the error: WebDriverException: Message: 'geckodriver' executable needs to be in PATH. WebDriverException: Message: 'chromedriver' executable needs to be in PATH. All of this is happening with a vagrant shell with pip system package installed. I'm a newbie and am trying to build in someone elses code so I'm not sure on how the files used to set up the local environment do. I first tried to installing geckodriver while in the virtual environment by running: pip install geckodriver. Fro that I get this error: (vagrant) vagrant@vagrant-ubuntu-trusty-32:/vagrant$ pip install geckodriver Collecting geckodriver Could not find a version that satisfies the requirement geckodriver (from versions: ) No matching distribution found for geckodriver Next tried I've downloaded the executable and placed it in the repository. But I don't know how to point to the executable to have it installed. How would I put the executable 'In Path' and run the executables? -
Django: Custom formset validation + url slug
I created a formset with it's own clean method. This is necessary in order to validate with the entry max_qty_per_ticket in my organiser model. The has these slug fields: path('<slug:organizer>/<slug:event>/', event_detail_view, name='event'), My challenge now is to get the slug:organizer into my BaseReserveFormSet. Currently it says there slug='lorem-2' BUT lorem-2 should be what ever is currently written in the url. Do you know how to get this slug field there? views.py def event_detail_view(request, event, organizer): queryset = Event.objects.filter(organizer__slug=organizer) event = get_object_or_404(queryset, slug=event) tickets = collect_all_tickets(event, organizer) ReserveFormSet = formset_factory(ReserveForm, formset=BaseReserveFormSet, extra=0) formset = ReserveFormSet( initial=tickets, # Example [{'ticket': "Early Bird"}, {'ticket': "Regular Ticket"},] ) if request.method == 'POST': formset = ReserveFormSet( request.POST, initial=tickets, ) if formset.is_valid(): order_reference = unique_order_reference_generator() for form in formset: ticket_name = form.cleaned_data['ticket'].name int_or_empty = form.cleaned_data['quantity'] qty = is_int_or_zero(int_or_empty) if qty > 0: obj = form.save(commit=False) obj.ticket_name = ticket_name obj.order_reference = order_reference obj.save() return redirect('organizers:index', slug=organizer) return render(request, 'events/event_detail.html', {'event': event, 'formset': formset}) My forms.py class BaseReserveFormSet(BaseFormSet): # Change to clean_quantity? Consider that validator error in template will change. def clean(self): if any(self.errors): return # MY PROBLEM: HOW DO I GET SLUG FROM MY URL IN HERE? queryset = Organizer.objects.filter( slug='lorem-2', ) # get_object or xy? max_qty_per_ticket … -
Where I can get payer_id for executing payment (paypal)?
Working with PayPal Python REST SDK. After payment created we need to execute this payment. At https://github.com/paypal/PayPal-Python-SDK/blob/master/samples/payment/execute.py is code sample. But when executing payment if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}): # return True or False print("Payment[%s] execute successfully" % (payment.id)) else: print(payment.error) we need to write payer_id. But how I can take it? Any ideas or code examples? -
React Search Bar , call function from another class
hello guys i am fetching data from my api and i try to set a search bar like this : import React, { Component } from "react"; import ProductsIndex from "./search_bar"; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: "" }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }); } onFormSubmit(event) { event.preventDefault(); ProductsIndex.renderProducts(this.state.term) // this.props.fetchWeather(this.state.term); this.setState({ term: "" }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Get a five-day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } export default SearchBar; In my onSubmit function try to call my function renderProducts from my class ProductsIndex here : class ProductsIndex extends Component { componentDidMount() { this.props.fetchProducts(); } renderProducts(term) { return _.map(this.props.products, product => { if(product.name==term) { return ( <tr key={product.name}> <td>{product.name}</td> <td>{product.product_category.name}</td> <td>{product.price}</td> </tr> ); } }); } render(){ return( <div> <table className="table table-bordered table-hover table-striped"> <thead> <tr> <th>Name</th> <th>Category</th> <th>Price</th> </tr> </thead> <tbody> {this.renderProducts()} </tbody> </table> </div> ); } } function mapStateToProps(state) { return {products: state.products} } export default connect(mapStateToProps, {fetchProducts}) (ProductsIndex); But that is doesn't work i get this error : Uncaught TypeError: _search_bar2.default.renderProducts is not …