Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving audio files in django table(model)
I want to store audio files under an attribute 'soundsrc' in the model elementsound. A part of models.py is given below: models.py(code snippet) class elementsound(models.Model): cdid=models.IntegerField() soundsrc=models.FileField() sounddesc=models.CharField(max_length=20) how do i do that? what changes have to be made in settings.py? please explain in detail. -
uwsgi django 500 internal error
I have been operated server in ubuntu 12. I try to deploy aws in ubuntu 14. but show up 500 server error. nginx + uwsgi + django1.8 Rest of all is same setting. The main page is visible but not css. Another page is same but python do not access into urls.py. (Server Error (500)) my setting is below: [uwsgi] project = project base = /home/ubuntu/example chdir = %(base) module = wsgi:application master = true processes = 1 socket = %(base)/%(project).sock chown-socket = ubuntu:www-data chmod-socket = 664 uid = www-data gid = www-data vacuum = true logto = /home/ubuntu/example/uwsgilog.log connect to my main page url : log is below: [pid: 19749|app: 0|req: 9/9] IP () {42 vars in 716 bytes} [Fri Sep 15 23:18:35 2017] GET / => generated 14405 bytes in 39 msecs (HTTP/1.1 200) 4 headers in 141 bytes (1 switches on core 0) connect to my other page log is below: [pid: 19749|app: 0|req: 11/11] IP () {44 vars in 765 bytes} [Fri Sep 15 23:19:56 2017] GET /search => generated 27 bytes in 34 msecs (HTTP/1.1 500) 4 headers in 145 bytes (1 switches on core 0) What is problem ? -
Django - Forloop Undefined
I have been trying to draw a chess board using Django, Python, CSS, and HTML. To do this, I need to keep track of the number of iterations in my for loop. I read through Django's documentation and saw that I should use forloop.counter. When I used forloop.counter in my program, I received a jinja2.exceptions.UndefinedError which stated that forloop was undefined. I uninstalled and reinstalled Django 1.11.5 in my IDE and received the same error. I installed Django's development version and received the same error. I checked my usage of forloop.counter in a separate test program, and I still received an error saying that forloop was undefined. Is there an error with Django itself? Thank you. Here is the test program: <div id="container"> {% block main %} {% for item in length %} <p>{{ forloop.counter }}</p> {% endfor %} {% endblock %} </div> -
Annotate with django-graphene and filters
I would like to sum a field in my resolver of django-graphene using the django_filter. Typically my resolvers would look like: my_model = DjangoFilterConnectionField( MyModelNode, filterset_class=MyModelFilter) def my_resolver(self, args, context, info): return MyModelFilter( data=format_query_args(args), queryset=self).qs Which works fine. However, I would like to provide a custom queryset to the model filter so that I can perform aggregations on fields. I'm trying to do something like this: def my_resolver(self, args, context, info): queryset = MyModel.objects.values( 'customer_id').annotate( cost_amt=Sum('cost_amt', output_field=FloatField())) return MyModelFilter( data=format_query_args(args), queryset=queryset).qs Inspecting the raw SQL in GraphiQL, it looks correct. However, the error message I receive from GraphQL is "message": "Received incompatible instance \"{'cost_amt': 260.36, 'customer_id': 300968697}\"." This is the correct result, but I'm unsure why GraphQL is getting this object from django-graphene. How can I provide a custom queryset and make this work? -
How use Django Cache in view without cache all page
I trying to use Django Cache to make better my views. Works great, 400ms to 8ms is perfect. But when user access page for the first time, Django cache page with user info in header and when I try log out, page continue with user info. I try use cache in template too, but isn't good, my problem come from view, so continue 400ms. -
saving image files in django model
i want to store a lot of images in a table(model of django) under an attribute 'imgsrc'. How do i do that? i have seen a lot of online material but i am not getting the complete information anywhere. What changes do i need to do in settings.py and where do i store my image files?... a part of models.py class elementdetails(models.Model): sid=models.IntegerField() imgsrc=models.ImageField() soundsrc=models.FileField() sounddesc=models.CharField(max_length=20) -
Iterating through json list in Django template
Apologies, if this question is asked earlier also but currently not able to fetch any answers even after Googling this for a while. I am passing the following context in my Django template : context = {'test': custom_json_list} And the output of custom_json_list is this : {'pc_16530587071502': [{'people_count_entry__sum': None}], 'pc_17100675958928': [{'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': 4}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}, {'people_count_entry__sum': None}]} I want to display the data in the following format 'pc_16530587071502' : NONE 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : 4 'pc_17100675958928' : None 'pc_17100675958928' : None 'pc_17100675958928' : None How can I proceed with the syntax so that I can see the data in this format. The only thing I was able to decipher is this : {% for key, value in test.items %} {{ key }} <br /> {{ value }} <br /> {% endfor %} Thanks in advance. -
How can I access sheet in a method?
Unresolved reference 'sheet' error happens. I wrote class User(): def __init__(self, sheet_path): self.file = glob.glob(sheet_path) self.construction_area ={} def read(self): for x in self.file: if "$" not in x: book = xlrd.open_workbook(x) sheet = book.sheet_by_index(0) cells = [('user_id', 0, 9), ('name', 4, 0), ('age', 4, 1),] ・ ・ def save(self): ・ ・ for row_index in range(7, sheet.nrows): row = sheet.row_values(row_index) ・ ・ x = User('./data/*.xlsx') x.read() x.save() In sheet of save method the error happens.I added self in front of sheet, but AttributeError: 'User' object has no attribute 'sheet' error happens.Why can't I access 'sheet' ?Is making instance not enough?How can I fix this? -
Django post_save receiver won't save foreign key
I have three models: User (from django.contrib.auth.models), UserProfile and GameCharacter. I setup the following receivers so when a User is created, a UserProfile and a GameCharacter are automatically created as well. @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: user_profile = UserProfile() user_profile.user = instance user_profile.money = 0 user_profile.save() @receiver(models.signals.post_save, sender=UserProfile) def create_user_profile_character(sender, instance, created, *args, **kwargs): if created: instance.character = GameCharacter() # Doesn't work, `character_id` is NULL in databse instance.character.save() instance.save() As expected, it creates two entries in database, a UserProfile and a GameCharacter, but the foreign key to the GameCharacter is not saved, it's NULL in database. It's as if the line instance.character = GameCharacter() didn't exist. My models: class GameCharacter(models.Model): nickname = models.CharField(max_length=255, null=True, blank=True, default=None) server = models.ForeignKey(GameServer, on_delete=models.PROTECT, null=True, blank=True, default=None) is_bot = models.BooleanField(default=False) position = models.CharField(max_length=255, null=True, blank=True, default=None) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') character = models.ForeignKey(GameCharacter, null=True, blank=True, on_delete=models.SET_NULL) money = models.BigIntegerField() I use MySQL and InnoDB as storage engine. Any idea? -
Getting {% load chartit %} on my browser. Charts are not loading using chartit
I am Displaying graphs using Django Chartit and Cassandra 3.0 is my database. I have tried to render a line chart but it's not showing a graph, instead it's showing {% load chartit %}. Please suggest. I have googled but it's not helpful. I think the code in HTML is correct. But I dont have a clue what is going wrong. There is also a an error when i run sync_cassandra. I am also struggling with this error. Please share if any more info are required. AttributeError: 'module' object has no attribute 'index' Below are supplements: Models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals # -*- coding: utf-8 -*- from django.db import models # Create your models here. from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class PqpModel(DjangoCassandraModel): prd_id = columns.BigInt(primary_key=True) X_01 = columns.Decimal() X_02 = columns.Decimal() X_03 = columns.Decimal() X_04 = columns.Decimal() X_05_1 = columns.Decimal() X_05_10 = columns.Decimal() X_05_11 = columns.Decimal() X_05_12 = columns.Decimal() urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.db import models from cassandra.cqlengine import connection from cassandra.cqlengine.management import sync_table … -
The requested URL /admin was not found on this server
I have a django app and i need to deploy it on Apache. I have configured everything, which is apache and mod_wsgi, but I can't get the app to run. Whenever I go to the url usercentral.com/admin, it gives an error saying "The requested URL /admin was not found on this server". usercentral.com works fine though. It shows my folder containing staticfiles. My configuration files are as follows: httpd.conf is: # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so … -
Issue with import name(conflict app name with python module name) in celery
I have an app in django as social(app name) also using 'social_django' module but 'social_django' django have dependency module python 'social' both having same name as 'social' due to this autodiscover_tasks giving wrong path for django app social installed app for django INSTALLED_APPS = [ 'social_django', 'social' ] Steps to reproduce add social_django in installed app also create django app with same name as social now check path coming in fuction find_related_module at /lib/python3.5/site-packages/celery/loaders/base.py the following line is creating the bug pkg_path = importlib.import_module(package).__path__ Expected behavior expected path : /home/user/workspace/project/social Actual behavior actual path:: /lib/python3.5/site-packages/social -
How to make a condition in subquery based on outer query?
I work on Airbnb like app. I have a Flat model and Price model, prices have different types of priority which allows customers create a flexible price range. I stuck with one complicated query. This query should return Flats by date range and calculate prices for this range. Here the part of my models: class Flat(models.Model): prices = models.ManyToManyField( 'Price' related_name='flats' ) price = models.PositiveIntegerField() ... class Price(models.Model): PRIORITY_CHOICES = ((i, i) for i in range(1, 6)) priority = PositiveIntegerField(choices=PRIORITY_CHOICES) start_date = models.DateField() end_date = models.DateField() price = models.PositiveIntegerField() So far I figure it out how to annotate prices with higher priority by each day. I wrote a custom manager for Flat: class FlatManager(models.Manager): def with_prices(self, start, end): days = get_days(start, end) # utils function return list of days prices = {} for day in days: prices[str(day)] = models.Subquery( Price.objects.filter( flats=models.OuterRef('pk')). filter(start_date__lte=day, end_date__gte=day). order_by('-priority'). values('price')[:1] ) return self.annotate(**price_dict) Here is my problem: Some dates in the Flat can be without price blocks, so Flat have its own price field for cases when customer don't won't to use flexible prices. I don't know where I need to add a condition operator in my query. If I add it in the Price … -
To be an expert at Java EE or a good developer at both Django and Java EE? [on hold]
I have a general question on developer thoughts, I am currently working as a Java EE developer, but I love the Django framework, so in my free time at home I develop projects on Django. What do you think as developers is it good to stick to a framework and learn the most out of it, like say to be a Java EE expert or gain a more spherical view and be a good but not expert developer at many frameworks, like Java EE developer and Django developer the same time? -
How a search inside a website works?
Assume I have a website which contains articles, or blog, whatever. How can I create a search engine for the content in the site? I know that many Wordpress, Drupal and many other CMSs has such a feature. How it works and how it should be implemented in django? -
Form Validation Not Working Django
I'm not sure where I'm going wrong with the form validation... I also want to display error messages wether the for was submitted successfully or not. Currently, I'm using a DetailView, where a person can fill in a BookingForm() forms.py from django.core.validators import RegexValidator class BookingForm(forms.Form): Name = forms.CharField() Postcode = forms.CharField(max_length=8,label='Postcode') phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") Phone = forms.CharField(max_length=15,validators=[phone_regex],label='Phone') Date = forms.CharField(max_length=30,label='Date') Time = forms.CharField(max_length=10,label='Time') In my views.py I defined def post to allow post requests. def post(self,request,**kwargs): # put your own credentials here form = BookingForm(self.request.POST) if form.is_valid(): user_phone = form.cleaned_data['Phone'] postcode = form.cleaned_data['Postcode'] date = form.cleaned_data['Date'] account_sid = "***" auth_token = "***" found = Model.objects.get(id=self.kwargs['pk']) client = Client(account_sid, auth_token) client.messages.create( to=Model.phone_number, from_="+442033225719", body="You have a new booking." + "Call phone number:{}. Address: {}. Date:{}" .format(user_phone,postcode,date)) messages.success(request, 'Your booking was reserved.') else: messages.error(request, 'Error occurred.') return redirect('users:detail', pk=self.kwargs['pk']) And my model_detail.html which handles the form. <form action="" method="post"> {% csrf_token %} <input name="Name" type="text" id="name" placeholder="Name"> <input name="Postcode" type="text" id="location" placeholder="Postcode"> <input name="Phone" id="name" placeholder="07576258829"> <input name="Date" type="text" id="booking-date" data-lang="en" data-large-mode="true" data-min-year="2017" data-max-year="2020"> <input name="Time" type="text" id="booking-time" value="9:00 am"> <button type="submit" class="progress-button button fullwidth margin-top-5"><span>Book Now</span></button> … -
How to get a single object from a related model in django template
I have two models (Item and Album). Album has a foreign key pointing to Item like this class Item(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() and class Album(models.Model): photo = ImageField(upload_to=item_directory_path) caption = models.CharField(max_length=100, blank=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) In my template {% for item in item_tags %} <div class="item-dock"> <a href="{{item.name}}"> <img src="{{item.album_set.photo.filter()}}" class="img-responsive"> <p class="item-name text-center">{{item.name|capfirst}}</p> </a> Now the real issue is. Given that querying on a related model will always return a queryset. How can I retrieve a single object(in this case, a single photo from this queryset) from the Album model for an Item in my template. I know about queryset and related manager! Any help, suggestions will be much appreciated -
Slow response in django
Currently I am inspecting a django queries(django-rest-framework) with django debug toolbar. The postgres database query time is about 100ms which is ok. But the response time took about 6 sec., which is slow. I found that the slowest(takes about 4 sec.) function is this: @transaction.atomic def create(self, *args, **kwargs): response = super(PersonView, self).create(*args, **kwargs) data = response.data product_data = data['packages'][0]['product'] person = Person.objects.get(pk=data['id']) if not person.info: product = Product.objects.get(pk=product_data['id']) PersonItem.objects.create(person=person, product=product) response.data = PersonSerializer(person).data return response Any ideas why the response is so slow or why this function takes so long ? -
How can I get Taggable field values separately in django?
First of all, I take one input from user(Ex: Symptom=fever). Symptoms are stored in database with taggable field and I have also one more taggable field called medicine. Taggable field is not iterable,so,how can I compare user input with database value. If one or more "disease" has symptom(fever) then I want all Other symptoms(stored with fever) with related disease name. example(Disease database): Disease_ | Symptoms | medicine......(other fields) dengue__ | Fever, Headache, Muscle pain, Joint pain, Bone pain, Pain behind Eyes |... flu______ | Fever, Muscles ache, Headache, Dry cough, Fatigue, Weakness, Chills, Sweats |... chickenpox| Fever, loss of appetite, headache, tiredness |... models.py class Disease(models.Model): did = models.AutoField(verbose_name='Disease Id', primary_key=True,auto_created=True) dName = models.CharField(max_length=100,unique=True) symptoms = TaggableManager(verbose_name='symptoms list', through=TaggedSymptoms) symptoms.rel.related_name = "+" medicine = TaggableManager(verbose_name='medicine list',through=TaggedMedicine) medicine.rel.related_name = "+" views.py def patfirst(request): if request.method == "GET": return render(request, 'personal/patfirst.html') if request.POST.get('Next'): newSymp = request.POST.get('newSymptom') args = {'newSymp' : newSymp,'didata':didata} #,'tagdata':tagdata} return render(request, 'personal/patfirst.html',args) patfirst.html <form method="post" action="#"> {% csrf_token %} Enter Symptom: <input type="text" name="newSymptom"/><br><br> <input type="submit" value="Next" name="Next"/> <input type="submit" value="None of these" name="NoneOfThese"/> </form> <div> {% for object in didata %} <ul> {% for tag in object.symptoms.all %} {% comment %} here i got all the symptoms stored … -
Tools for creating migrations without blocking django
I'm wondering - is where some tools for rewriting Django migrations so they will be without large downtime due to locks. I know how to do it by hand, but maybe where are tools for doing this automatically? Example: I add a column testff = models.BooleanField(default=False) By default django will generate sql which looks: BEGIN; ALTER TABLE "table" ADD COLUMN "testff" boolean DEFAULT false NOT NULL; ALTER TABLE "table" ALTER COLUMN "testff" DROP DEFAULT; COMMIT; which cause long blocking time on large tables, i want to get something like: BEGIN; ALTER TABLE "table" ADD COLUMN "testff" boolean; ALTER TABLE "table" ALTER COLUMN "testff" SET DEFAULT false; COMMIT; BEGIN; -- update existings rows, maybe not all together but in batches UPDATE "table" set testff=false ALTER TABLE "table" ALTER COLUMN "testff" DROP DEFAULT; ALTER TABLE "table" ALTER COLUMN "testff" NOT NULL; COMMIT; -
Django append domain name after localhost
I created a django project. when i start server and open 127.0.0.1:8000/admin. I redirect to http://127.0.0.1:8000/www.pxxx-xxxx.com/order/success/admin/ then django show error " Page Not Found(404) why django append url (www.pxxx-xxxx.com/order/success/) after 127.0.0.1:8000. Thanks in advance -
django get value from template.html
I really need help...i ve been asking a lot of times for help and looked on google and i haven't found anything.... I want when the I click on the Table name i want to get the ID and number and obtain the details about the that table. table_base.html {% extends 'base.html' %} {% block content %} <br> <div class="container"> <div class="jumbotron"> <h1> {{ table_name }} List</h1> {% if list_tables %} <table> <thead> <th>Id</th> <th>Name</th> <th>Date</th> </thead> {% for list in list_tables %} <tr> <td><pre>{{ list.id }}</pre></td> <td><pre><a class="btn-link" href="{% url 'tables:details' list.id %}">{{ list.name }}</a></pre></td> <td> <pre>{{ list.date }}</pre></td> </tr> {% endfor %} </table> {% else %} <p> No Records Found</p> {% endif %} </div> </div> {% endblock %} views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: return Crawledtables.objects.get(id=self.kwargs['table_id']) class Details(ListView): model = AllTables template_name = 'tables/table_list.html' context_object_name = 'details' paginate_by = 15 queryset = AllTables.objects.all() tables/urls.py urlpatterns = [ url(r'^$', views.table_base, name='tables'), url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='id-details'), url(r'^(?P<table_id>\d+)/details$', views.Details.as_view(), name='details'),] Basically i want to get the … -
Apache mod_wsgi better configuration
I am deploying my django-based web apps using apache mod_wsgi. This is my virtualhost: <VirtualHost _default_:*> ServerAdmin my_email@emails.com DocumentRoot /var/www/appWSGI/gestioner/gestioner/ Alias /static /var/www/appWSGI/gestioner/static/ <Directory /var/www/appWSGI/gestioner/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess gestioner python-path=/var/www/appWSGI/gestioner python-home=/var/www/appWSGI/env WSGIProcessGroup gestioner WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/appWSGI/gestioner/gestioner/wsgi.py WSGIPassAuthorization On </VirtualHost> This basic configuration is working fine. I would like to know if it is possible to improve this maybe there are other directives that i don't know about.. It is possible to have another configuration that boots performance ? thank you all in advance!! -
TypeError: __init__() got multiple values for keyword argument 'choices'
class StatisticsBaseForm(forms.Form): type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) period = forms.ChoiceField("Period", max_length=20, choices=settings.PERIODS, default='week') # product = models.IntegerField("Product", choices=) def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Statistics fields = '__all__' The traceback is the following File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/urls.py", line 6, in <module> from loanwolf.statistics.views import StatisticsIndexView File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/views.py", line 8, in <module> from loanwolf.statistics.forms import StatisticsBaseForm File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 17, in <module> class StatisticsBaseForm(forms.Form): File "/home/jeremie/Projects/Work_Projects/django/loanwolf/statistics/forms.py", line 18, in StatisticsBaseForm type_choice = forms.ChoiceField(_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, default=0) TypeError: __init__() got multiple values for keyword argument 'choices' I have this error, but I didn't manage to fix it. How could I go ahead on the error? -
Django admin returning whole object not just the FK field
I have searched and found a few answers however all the questions relate to the use of str etc... Im using the django admin module as it is interesting to play with and saves times, im having slight issues with my foreign keys in the sense they are returning all the field values not just the foreign key value. relevant models: class Order(models.Model): Order_ID =models.AutoField(primary_key=True) Dept_ID =models.ForeignKey(Department) Status =models.ForeignKey(Order_Statu) Order_Total =models.DecimalField(decimal_places=2, max_digits=5) def __str__(self): return '%s %s %s %s' % (self.Order_ID, self.Dept_ID, self.Status, self.Order_Total) class Order_Item(models.Model): Order_ID =models.ForeignKey(Order) Itm_Name =models.ForeignKey(Item) Quantity =models.IntegerField() def __str__(self): return '%s %s %s' % (self.Order_ID, self.Itm_Name, self.Quantity) and an example of what i mean: Screenshot im willing to admit that it is probably something i have overlooked in the documentation or it is something simple and obvious.