Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tutorial part 2 Field Error
I got a field error when I was trying to run the tutorial of Django Part 2. I'm using Python 3.6 and Django 1.11. models.py import datetime from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Working with the tutorial, step by step. I was running the python manage.py shell: >>> from polls.models import Question, Choice >>> Question.objects.all() <QuerySet [<Question: What's up?>]> >>> Question.objects.filter(id=1) <QuerySet [<Question: What's up?>]> >>> Question.objects.filter(question_text__startswith='What') I got the following error after Question.objects.filter(question_text__startswith='What'): django.core.exceptions.FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text I don't know what to do to repair this error, maybe I put something wrong at models, that's why I share models.py with You. I hope you can help me -
Django: How to import CSS libraries in Ajax template
I am using Ajax in my Django project to implement some simple searching. In my template folder, I have created an html file called "ajax_search.html" where I write how I want my objects to be displayed on a page. Right now it looks like this: {% if puzzles.count > 0 %} {% for puzzle in puzzles %} <a href="{% url 'puzzle' puzzleID=puzzle.id %}"> {{puzzle.title}} </a> <br> {% endfor %} {% elif search_len < 3 %} {% else %} No puzzles match the search {% endif %} This works fine, but I wanted to style it to look better. Is there any way I could import some CSS into this template? Thank you! -
Number of forms in js don't reset after page refresh, django and django-dynamic-formsets
I have a django formset in which a form is dynamically being added and removed using jquery.formset.js. It keeps track of number of forms that are currently in a formset. But when I refresh the page, the number of forms in a formset doesn't get rest to 1, and due to min and max number of forms that can be added in the formset, it doesn't allow more forms to be added. Initial form: With Two forms: After Refresh: I should not have the choice to remove the form but I can see it, because the number of forms still is stored as 2. And I can add only 1 more form, because maximum number of forms that can be added is 3. Please help me handling this issue. -
django.db.utils.ProgrammingError: column cms_page.path does not exist
I just upgraded my djangoCMS environment to the versions listed below. When I'm trying to access the page I get this error: Traceback (most recent call last): File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/admin/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin/.local/lib/python3.5/site-packages/cms/views.py", line 48, in details page = get_page_from_request(request, use_path=slug) File "/home/admin/.local/lib/python3.5/site-packages/cms/utils/page_resolver.py", line 120, in get_page_from_request page = get_page_from_path(path, preview, draft) File "/home/admin/.local/lib/python3.5/site-packages/cms/utils/page_resolver.py", line 76, in get_page_from_path return get_page_queryset_from_path(path, preview, draft).get() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get num = len(clone) File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 238, in len self._fetch_all() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/query.py", line 54, in iter results = compiler.execute_sql() File "/home/admin/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/admin/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in exit six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/admin/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/admin/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column cms_page.path does not exist LINE 1: SELECT DISTINCT "cms_page"."id", "cms_page"."path", "cms_pag... I did run … -
What is difference between instance namespace and application namespace in django?
I am referring https://www.webforefront.com/django/namedjangourls.html to understand django urlconfs. I have encountered terms instance namespace and application namespace. I know about namespaces in urlsconfs. But I don't know the difference between them. I referred django docs for it. It mentions that instance and app namespaces, comes into picture, when multiple instances of same app is used in django project. But still, I am not able to understand it. I have googled out, but couldn't find any help on it. Thanks in advance. -
Django Division in models return integer only
good morning, Trying to do a weighted average with some values in my models. def get_resultavg(self): return Result.objects.filter(employee_id=self, eval_at__isnull=False).exclude(evaluation_value=0).aggregate(average=Sum(F('evaluation_value')*F('question__question_weight')/100, output_field=FloatField())) and In my template <td class="text-center align-middle">{% with averagecalc=employee.get_resultavg %} {% if averagecalc %} <small> {{ averagecalc.average|floatformat:"-2"|default:"-" }} </a> </small> {% endif %} {% endwith %}</td> The result in template should be 4.2 based on numbers for question_weight and evaluation_value. But it brings me 4.00, I know the problem is when I include the division. I tried with float(100), mutiplying * 0.01 but nothing. What am I doing wrong here guys? Thanks -
Django Admin. Disable `list_editable` fields for editing after date?
Django 2.0.3, Python 3.6.1 I have standard Django admin panel. For one of my model I create list_editable for some fields (price and provider_price on screenshot). Question is: How to disable this list_editable fields for edit after some date? For example, if now is March 11, 2018 and older, fields price and provider_ price are disabled and doesn't edit in list view. -
Django: <ul> inside help_text of field
I would like to have a inside the help_text of a django form field. Unfortunately django renders the help_text inside a . According to the HTML spec a must not contain a . At least that is what my validation tool says. Here is the source of django: https://github.com/django/django/blob/master/django/forms/forms.py#L283 def as_table(self): "Return this form rendered as HTML <tr>s -- excluding the <table></table>." return self._html_output( normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>', error_row='<tr><td colspan="2">%s</td></tr>', row_ender='</td></tr>', help_text_html='<br><span class="helptext">%s</span>', errors_on_separate_row=False) What can I do to get in the help_text and valid html. -
Getting tracks from a playlist using Spotipy is slow
I'm interacting with the Spotify Web API for a django project that allows users to upload their playlists for them to be ranked according to certain parameters, namely audio features spotify assigns to all tracks. I'm using the Spotipy library to query the spotify API with python. It's lightning fast for user and playlist data, but following the Spotipy tutorials on how to get tracks from a playlist, I'm finding the response is extremely slow. The wait time for tracks is about proportional to the length of the playlist in tracks.. I'm thinking it has something to do with an inefficiency in how the spotipy library packages up and sends requests. Has anyone ever come across a similar bottle neck with regards to getting tracks and speed? I'd be very grateful.. our project kind of hinges on it at this point. -
Listening to django channels channel_layer from outside of a consumer
The docs explain that it is possible to publish to the channel layer from outside of a consumer: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#using-outside-of-consumers I need to do the opposite. I have a fairly complex python script that reads live data from pubnub, processes it, and pushes it to consumers via groups on the channel_layer. This works fine, but I need consumers to be able to announce their presence to this script so that it can push them data (it currently pushes to the channel layer only when it gets new data from pubnub, which could be every 24 hours). I've decided to solve this by having the consumers publish to a 'presence' channel on connect. I now need the pubnub source script to listen to this channel. I've tried adding the below to the script, and it no longer throws errors, but it doesn't actually respond to messages, because it fails to join the channel layer: from channels.generic.websocket import JsonWebsocketConsumer class channelConsumer(JsonWebsocketConsumer): def __init__(self): self.channel_name = 'source' def join(self): async_to_sync(channel_layer.group_add)('presence', self.channel_name) def receive_json(self, message): print("Presence Detected") # do some stuff Further on in the code: global channel_layer channel_layer = get_channel_layer() global listener listener = channelConsumer() listener.join() As I said, there are no explicit errors, … -
How to use temporary in memory database and diff on same schema on disk
I'll try to explain... My need is load data from text file and import in different Models If import is Ok check against existent instances of Models already into the db to find differences. Sometime I need all data are equals sometime I need data from file are new and then import into disk sometime I need to know differences between loaded data and persistent data and ask user what to do with data on disk. After checks, loaded data do not need, so must be deleted My idea is to create in memory db and load data into it so no problem with primary key duplicated an unique constraint ( and no load on disk ) Then query objects with same key in different db and do stuff How can I do that ? There is a better way without touching unique constraint ? Some sample ? Regards, Mauro -
Store file on several hard drives with Django
I'd like to use several hard drives at the same time with django to store my files. My goal is to store big files on a server and share it (on local network). I would like to know how to proceed in order to store my files in several disk and how would react django when the first disk is full. The idea would be to fill the first one and then switch to the second one. Obviously, if we remove a file in the first one, we re-use it. Unfortunately, I didn't find anything about it. thanks in advance. -
How to properly runserver on different settings for Django?
I have a basic django rest API. I want to separate some of my settings for dev and prod just for organizational purposes. I'm also just learning about separating environments. I've read a few things, but I can't seem to get it working the way I want it to. The hierarchy looks like this: - djangorest - api - __init__.py - models.py - views.py - urls.py - etc.. - djangorest - __init__.py - settings.py - urls.py - wsgi.py Right now, when I run the server, I do a simple: python3 manage.py runserver That command reads the settings from settings.py and runs it appropriately but I've looked around on how to separate the settings into prod vs dev and it doesn't work right. I want to be able to have: commonsettings.py dev.py prod.py In commonsettings, it'll just have whatever's in both dev and prod. I've tried running: python3 manage.py runserver --settings=settings.dev But it gives me an error saying there is no module named 'setting'. Please help. Thank you! -
Serializer of 2 objects from 2 models, that do not have relationships
I have 2 modules in 2 different apps that are not in relationship of any kind: class Table(models.Model): name = models.CharField(max_length=32, unique=True) columns = JSONField() class Company(models.Model): name = models.CharField(max_length=32, unique=True) I need to create Serializer, that first of all serialize only 1 specific object (always the same) in Table class. For example it musk have Table.obejects.get(id=1). And then I serialize Company according to content in View funtion, that I posted bellow. That scenario is very important, because in Table I explain how to build table, and in Company I get data, that I'll put in pre-build table. Serializer class for Company: class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name',) View class for Company: class CompanyList(APIView): def get_queryset(self): return Company.objects.all() def get(self, request, format=None): companies = self.get_queryset() serializer = CompanySerializer(companies, many=True) return Response(serializer.data) Of course I want to use the same logic for scenario, when I render just 1 Company object. -
if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'
when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i run that programm it show if self.max_length is not None and not widget.is_hidden: AttributeError: 'EmailField' object has no attribute 'is_hidden'. when i … -
how to use my html in Django in a secure way?
I have made my html pages now I want to use them in Django but don't want to lose the design what I have made. Any secure way? -
Populate table entries in models.py
I am new with databases so maybe my thinking is flawed, but I would like to define a table with fixed entries. These entries would once be defined and then not changed. I thought it would make it easier in the development period, where I have to set up the whole database from scratch several times, that some fixed data is populated automatically from models.py. Is there a way in models.py to already populate the table with these entries? class Field(models.Model): name = models.CharField(max_length=200) created_timestamp = models.DateTimeField(auto_now_add=True) -
Property field in a django model is not serialized. How to fix?
I have the following model: def get_file_path(instance, filename): return 'files/{0}/{1}'.format(instance.user.username, filename) class File(models.Model): fid = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.ForeignKey(settings.AUTH_USER_MODEL) file = models.FileField(upload_to=get_file_path) when I try to serialize this model using for example serializers.serialize('json', File.objects.all()) I get: u'[{"model": "app_name.file", "pk": "45f616b4-d028-488e-83c5-878ce1028018", "fields": {"user": 1, "file": "files/username/filename.txt"}}]' I want the serialized json to also include the file field's url which file_obj.file.url returns so I added a property field like so: class File(models.Model): fid = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.ForeignKey(settings.AUTH_USER_MODEL) file = models.FileField(upload_to=get_file_path) def _get_file_url(self): "Returns file's url" return self.file.url url = property(_get_file_url) However property field url is still not serialized. So I tried to write a custom serializer for the model by extending serializers.ModelSerializer like so: class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('fid', 'user', 'file', 'url') which doesn't work and I get 'module' object has no attribute 'ModelSerializer'. is it because django doesn't have ModelSerializer class and only django rest_framwork does ? if so how do I solve this if I am using django only and not django rest framework ? Thanks. -
Python requests.POST is failing in Django
I have to make a redirection layer in Django. So any get or post request comes needs to be redirected to another server. Since Django Redirect doesn't allow for POST redirection, so we are using python requests module to make post request. So the Django request structure is : requests.post('http://localhost:8080/user/?query=1', auth=('user', 'pass'), data={'key':'value'}) It will be processed in the class based view of post request. class Redirect_Conf(View): def post(self, request, *args, **kwarfs): headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} res = requests.post('http://localhost:8000/configuration/?query=2', auth=('user', 'pass'), data={'key':'value'}) return HttpResponse("Data Received") However, I am getting ConnectionError: ('Connection aborted.', error(111, 'Connection refused')) Please remember that localhost:8080 and localhost:8000 are different servers running. What am I missing here? -
Django form post(AJAX) direct to somewhere else
i know my question is quite vague and also has been asked so many times(but i can't understand any of the solutions).what i want to go is to url search_res/save_tweet and pass data from template show_tweets.html in json format using AJAX. i think my ajax is not working. and when i press button it goes to somewhere http://127.0.0.1:8000/search_res/? I am new to both django and ajax. show_tweets.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tweets Result</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> save_tweets = function(tweet_id,created_at,text,lang){ alert(tweet_id,created_at,text,lang); $.ajax({ type : 'POST', url : '/search_res/save_tweet/', dataType : 'json', data: { 'tweet_id' : tweet_id, 'created_at' : created_at, 'text' : text, 'lang' : lang }, success: function(data) { alert(data); } }); } </script> </head> <body> <h1 align="center">Tweets Results</h1> <ul> {% for k,v in json_d %} <div> {{ k }} : {{ v.full_text }} <form onsubmit="save_tweets('{{ v.id_str }} , {{ v.created_at }} , {{ v.full_text }} , {{ v.lang }}')">{% csrf_token %} <input type="submit" value="Toxic"/> </form> </div> {% endfor %} </ul> </body> </html> views.py def show_tweets(request): if request.GET['hashtag'] and request.GET['user']: template = loader.get_template('error.html') return HttpResponse(template.render({},request)) else: if request.GET['hashtag']: hashtag= request.GET['hashtag'] try: all_tweets = tweepy.Cursor(api.search, q=hashtag + ' -filter:retweets', tweet_mode='extended').items(100) except: print("error") d = {} cnt = 0 for … -
django clean_data.get is None
I want to make some fields of thwe form required based on the "is_seller" dropdown list . but seller = cleaned_data.get("is_seller") returns None ! these are my codes : models.py class UserProfileInfo(models.Model): user=models.OneToOneField(User,related_name='profile') companyname=models.CharField(blank=True,null=True, ],max_length=128,verbose_name=_('companyname')) phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit.")) cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone')) tel = models.CharField(blank=True,null=True,validators=[phone_regex], max_length=17,verbose_name=_('tel')) state=models.CharField( max_length=128,verbose_name=_('state')) city=models.CharField( max_length=128,verbose_name=_('city')) address=models.CharField(blank=True,null=True, max_length=264,verbose_name=_('address')) is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller')) def __str__ (self): return self.user.username class Meta: verbose_name=_('UserProfileInfo') verbose_name_plural=_('UserProfileInfos') forms.py : class UserProfileInfoForm(forms.ModelForm): CHOICES = (('0','buyer'), ('1','seller'), ('2','both')) is_seller = forms.CharField(widget=forms.Select(choices=CHOICES),label=_('title')) companyname=forms.CharField(required=False,widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%', 'white-space':'nowrap'}),label=_('companyname')) cellphone = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('cellphone')) tel = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('tel')) state=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('state')) city=forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('city')) address=forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:100%'}),label=_('address')) class Meta(): model=UserProfileInfo fields=('companyname','tel','cellphone','state','city','address','is_seller') def clean_companyname(self): cleaned_data = super(UserProfileInfoForm, self).clean() seller = cleaned_data.get("is_seller") print(">>>>>>>>>>>>>>>>>>"+ str(seller)) if seller!=0: raise forms.ValidationError(u"Required.") return cleaned_data -
How can I display a TemporaryUploadedFile from Django in HTML as an image?
In Django, I have programmed a form in which you can upload one image. After uploading the image, the image is passed to another method with the type TemporaryUploadedFile, after executing the method it is given to the HTML page. What I would like to do is display that TemporaryUploadedFile as an image in HTML. It sounds quite simple to me but I could not find the answer on StackOverflow or on Google to the question: How to display a TemporaryUploadedFile in HTML without having to save it first, hence my question. All help is appreciated. -
Django: File is only saved when created in admin page
I have a very odd problem: When I create an object for my Custom model in the admin page everything works fine. However, when I fill in the same input in my custom Form in the website it does not work. The problem is the file field: When I input a valid file in the form in the website, it is not saved and so I get a validation error (see clean() function below). Because there is no self.file even when I upload a file. In the admin page it works. Where is the error? Background: Here is my Custom model: # In my models.py class Custom(models.Model): file = models.FileField(max_length=45, upload_to=get_filepath, blank=True) file_info = models.CharField(max_length=50, blank=True) ... def clean(self): if self.file_info and not self.file: raise ValidationError("...") And here is my custom CreateView: class CustomCreate(CreateView): model = Custom form_class = CustomForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
Accessing to Odoo data with Django REST API
I'm trying to build a Django REST API e-commerce by retrieving data from Odoo, for that I need first of all to connect to odoo database. Any idea of how to do that !? PS: with XML-RPC it was easy but I want to to work with REST Thanks a lot. -
Djano celery for long running task and download the file
I am developing a django app and my app need to user to upload the urls in excel files. On server side i am reading the excel file by each cells, extracting the news article of the urls and generating the summary of article. this process can take upto 5-10 minutes for the long list of urls.I am using celery for managing the long running task but somehow server is giving me error 500 - Internal server error after 2 min without completing the task. enter code here Setting.py BROKER_URL = 'django://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery_app.py from __future__ import absolute_import import os import django from celery import Celery from django.conf import settings from kombu import serialization serialization.registry._decoders.pop("application/x-python-serialize") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings') django.setup() app = Celery('news') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) summary.py @shared_task from celery import shared_task def WritesummaryfromArticleToExcel(input_file,noofline,lang): try: data=False wb = xlrd.open_workbook(file_contents=input_file.read()) wb_sheet=wb.sheet_by_index(0) df=pd.DataFrame(columns=['Full Article','Summary']) for rownum in range(0, wb_sheet.nrows): # for colnum in range(0,1): try: rw=wb_sheet.cell_value(rownum,0) if type(rw)==float or type(rw)==int: rw= str(rw) # if len(rw)>15000: data=True articletext=rw # nooflines=request.data["numberofline"] lantext="" lantexttemp= articletext.split('\n')[0:2] for l in lantexttemp: lantext=lantext +"\n" +l lan=detect(lantext)