Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Postgres django.db.utils.ProgrammingError
I know similar questions have been asked many times, but none of those solutions have worked. Recently I have been trying to connect to an AWS RDS database. However, now whenever I try to run a server through manage.py migrate my database I always get the following: Traceback (most recent call last): File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "employee_employeeprofile" does not exist LINE 1: ..."employee_employeeprofile"."additional_info" FROM "employee_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/debug_toolbar/apps.py", line 15, in ready dt_settings.patch_all() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/debug_toolbar/settings.py", line 228, in patch_all patch_root_urlconf() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/debug_toolbar/settings.py", line 216, in patch_root_urlconf reverse('djdt:render_panel') File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 568, in reverse app_list = resolver.app_dict[ns] File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 360, in app_dict self._populate() File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 293, in _populate for pattern in reversed(self.url_patterns): File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/somil/Documents/Twine/venv/lib/python3.4/site-packages/django/utils/functional.py", line 33, in __get__ res … -
Python Django HTML csrf token not working
I am trying to put in a csrf token in my post form but I keep getting an error that I cant quite debug {% extends 'base.html' %} {% block title %}Data Services{% endblock %} {% block content %} <h1>{{ deal_name }}</h1> <a href="http://127.0.0.1:8000/pick/">Return to Deals here</a> <p>Which lender do you need to send an email to? </p> {% if unpaid %} <form action="/pick/{{ type_id }}/lenders/" method="post">{% csrf token %} <select name="email_name"> {% for l in unpaid %} <option value="{{ l.name }}">{{ l.name }}</option> {% endfor %} </select> <input type="submit" value="Email"> </form> {% endif %} <div> <ul> {% if lender %} There are {{ lender|length }} lenders who have paid. {% for l in lender %} <li> {{ l.name }} </li> {% endfor %} {% else %} <li> As of now no Lenders have been recorded as paid. </li> {% endif %} </ul> </div> {% endblock %} my error: Invalid block tag on line 10: 'csrf', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Like am i missing something here? I have done attempts like these multiple times with success. -
Generate audio waveforms for mp3 using python
What I am trying to achieve is that I have an audio file (.mp3) which I want to play on my browser with its waveform. What I have tried is a frontend library wavesurfer.js which worked well with small audio files but caused problems with large size audio files. As I will be having large audio files to be processed here, I will be doing the processing at the backend as doing this in frontned will be very laggy. So, I am now looking for some solutions in backend using Python (Django Framework). WHAT I HAVE TRIED ? After searching for possible solutions, I came across a project by BBC http://www.bbc.co.uk/rd/blog/2013-10-audio-waveforms which is very close to what I want to achieve. This project makes use of Peaks.js library to show waveforms in frontend based on JSON data for the audio. This JSON data for audio is generated by their C++ Library. I tried to follow on similar path and made use of Python's Library PyDub to generate waveform data for the audio file. I have used following code: song = AudioSegment.from_mp3("static/podcasts/sample.mp3") samples = array.array(array_type, song._data) samples = samples.tolist() waveform_data = {} waveform_data['data'] = samples with open('static/podcastdata/data.json', 'w') as outfile: json.dump(waveform_data, … -
Create "static" HTML Pages For Each Product
Problem: I have 10k+ products that need their HTML Page and the stuff within is to be static (thus searchable). I am trying to find a way to do the following using django: Loop over all the items. Get the matching information. Fill a model template. Save such template with the information now static. As much as I tried looking here on Stack Overflow and in the web, I did not find any instructions to do so. Please suggest any possible solutions. -
django admin doubles added item
I have 2 classAdmin (with many to one relationship). here is the code of models.py: class Category(models.Model): cname = models.CharField(max_length=200) cdate = models.DateTimeField('date published') def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.cdate <= now def __str__(self): return self.cname class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) sname = models.CharField(max_length=200) def __str__(self): return self.sname when i add a item in Category in django admin interface, it works fine. but when i add a item in subcategory, it adds double of my added item and I will have 2 items with same name instead of 1. what is the problem? my admin.py code: from django.contrib import admin from .models import Category,SubCategory class CategoryAdmin(admin.ModelAdmin): list_display = ('cname', 'cdate') class SubCategoryAdmin(admin.ModelAdmin): list_display=['sname'] admin.site.register(Category,CategoryAdmin) admin.site.register(SubCategory,SubCategoryAdmin) -
Allow some users to do CRUD in one Model Django?
There is a website with many users on it. There is a news section in it and also a NEWS MODEL. I want to allow some of the users that they go to website.com/admin (django's admin panel), login with there credentials, they should only see the NEWS MODEL ( they should not be able to see other models such as USER, PROFILES, etc) and they can create a new instance of that model ( NEW NEWS). So basically, whenever these elite users login in from the admin panel and add a new instance of a the NEWS model, it should appear on the website. PS. I do not have much knowledge on DJANGO's groups and permission. Users should only see the NEWS Model. Only superuser should be able to see all the models. -
how do i select data from two tables in django?
i am using django and i did create this two classes, i have a problem in relation between tables and selecting rows : class ayoub (models.Model): name=models.CharField(max_length=200) sname=models.CharField(max_length=200) class sabri(models.Model): a=models.ForeignKey(ayoub, on_delete=models.CASCADE) name=models.CharField(max_length=200) sname=models.CharField(max_length=200) i want to display all the attributes of sabri with the attribute name from class ayoub not the primary key (id) -
Django S3 Boto Cache Static File
I have some troubles with Django and collectstatic. I Use Django + AWS + S3 + ElasticBeanstalk Here my class for static from django.contrib.staticfiles.storage import CachedFilesMixin from storages.backends.s3boto import S3BotoStorage class StaticRootS3BotoStorage(CachedFilesMixin, S3BotoStorage): pass So, when i collectstatic i have : Post-processed 'font/font-awesome-4.7.0/less/rotated-flipped.less' as 'font/font-awesome-4.7.0/less/rotated-flipped.a8476cdc50c2.less' Post-processed 'font/font-awesome-4.7.0/less/variables.less' as 'font/font-awesome-4.7.0/less/variables.be3f6eed38aa.less' Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 415, in handle return self.handle_noargs(**options) File "/opt/python/run/venv/local/lib/python2.7/site-packages/collectfast/management/commands/collectstatic.py", line 186, in handle_noargs collected = self.collect() File "/opt/python/run/venv/local/lib/python2.7/site-packages/collectfast/management/commands/collectstatic.py", line 68, in collect ret = super(Command, self).collect() File "/opt/python/run/venv/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 125, in collect raise processed ValueError: The file 'font/font-awesome-4.7.0/fonts/fontawesome-webfont.eot' could not be found with <project.settings.storage.static.StaticRootS3BotoStorage object at 0x7f6230e82310>. (ElasticBeanstalk::ExternalInvocationError) All of that is for versioning my static like for Browser user Cache: Like file.css to file.15az5e11z5.css And {% static 'path/file.css' %} -> /path/files.15az5e11z5.css Any ideas how achieved that ? Thx ;) -
Django Many To Many Field Causing Me Grief
I am trying to list players who may belong to multiple teams. I set up my code for users to be able to select multiple teams, and that is working fine. However, now that I have done this, the automatic population of fields is no longer working. It worked fine with a foreign key but once I changed the model field reference to ManyToManyField, the auto population of the dropdown fields I set up no longer works. Please help! I'm a newbie, so if there's a better way to go about what I'm trying to accomplish I'm open to other thoughts. Here is my code: Models.Py class UserProfile(models.Model): user = models.OneToOneField(User) users = User.objects.select_related('userprofile').all() team = models.ManyToManyField(Team,related_name='teamprofile') def __str__(self): return self.user.get_full_name() class Team(models.Model): team = models.CharField(max_length=264,unique=True) user = models.ForeignKey(User,null=True,on_delete=models.CASCADE) class Meta: ordering = ["team"] def __str__(self): return self.team Views.Py def view_byteam(request): form = ViewByTeam(request.user, request.POST or None) if request.method == 'POST': if form.is_valid(): department = form.cleaned_data['dropdown'] return HttpResponseRedirect(team.get_absolute_url1()) return render(request,'/view_byteam.html',{'form':form}) Forms.py class ViewByTeam(forms.Form): dropdown = forms.ModelChoiceField(queryset=Team.objects.none()) def __init__(self, user,*args, **kwargs): super(ViewByDepartment, self).__init__(*args, **kwargs) qs = Team.objects.filter(team=user.userprofile.team) self.fields['dropdown'].queryset = qs self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' The above works with a foreignkey field reference on team but when I change it … -
Overriding social_auth login function
I installed social_django for my project and it all works fine but I would like to add some user profile attributes, when the user is successfully logged in through fb/twitter/github and I'm not sure how to do it. Inside the package I found the views.py with a function called _do_login which looks like this: def _do_login(backend, user, social_user): user.backend = '{0}.{1}'.format(backend.__module__, backend.__class__.__name__) enable_session_expiration = backend.setting('SESSION_EXPIRATION', False) max_session_length_setting = backend.setting('MAX_SESSION_LENGTH', None) print("this is a expensive test") # Log the user in, creating a new session. login(backend.strategy.request, user) try: max_session_length = int(max_session_length_setting) except (TypeError, ValueError): max_session_length = None .... And I think that is the view which is called after a successful Social login. So naturally I would simply put some code there like: g = Group.objects.get(name='someGroup') g.user_set.add(user) user.profile.someAtt = True user.profile.save() .... but I'm a bit afraid to do so since its the login part and I don't want to "play around" because of security issues. I thought about writing an Ajax call which checks the respond of fb/github and calls a own view function which adds the attributes but this seems to be tricky. So is there a proper way of doing this? Could not find anything, all posts I … -
Performing raw sql query inside a model function?
I have a raw sql query that belongs to the Student model so i would like to create a function named get_student inside of our Student class and perform the query there instead of my view. How do i go about doing this? With a view i would have done it this way: view.py: def index(request): query = "..." # complex query students_list = Student.objects.raw(query) # more code model.py: class Student(models.Model): name = models.CharField(max_length=255) I tried doing the following: view.py: def index(request): Student.get_students() model.py: class Student(models.Model): name = models.CharField(max_length=255) def get_students(): query = "..." # complex query students = models.Manager.raw(query) return students Error: unbound method get_students() must be called with Student instance as first argument (got nothing instead) view.py: def index(request): Student().get_students() model.py: class Student(models.Model): name = models.CharField(max_length=255) def get_students(self): query = "..." # complex query students = self.objects.raw(query) return students Error: Manager isn't accessible via Student instances view.py: def index(request): Student.get_students() model.py: class Student(models.Model): name = models.CharField(max_length=255) def get_students(self): query = "..." # complex query students = models.Manager().raw(query) return students Error: unbound method get_students() must be called with Student instance as first argument (got nothing instead) view.py: def index(request): Student().get_students() model.py: class Student(models.Model): name = models.CharField(max_length=255) def get_students(self): query … -
Launching several applications in Django
I want to write a web service for which to need to use a proxy. Earlier was written a proxy-checker application that runs every ten minutes and records the proxy address in to file. Proxy address information is required to process user requests. How can I integrate my proxy-checker in a Django project? So that it works independently -
DRF PrimaryKeyRelatedField, AttributeError: 'QuerySet object has no attribute parameter'
I'm trying to get a REST-backend up and running, my first in Python. An incident can have many UnderWays but an UnderWay may only have one Incident(ManyToOne). I'm now trying to get the serializer for the UnderWay model to work, it should do both POST and GET requests with the following parameters['incident', 'phonenumber', 'time']. It feels as if I've tried everything but all I get is an AttributeError saying 'QuerySet' object has no attribute 'incident'. models.py: class Incident(models.Model): active = models.BooleanField(default=False) message = models.TextField(max_length=200, blank=True) time = models.TimeField(auto_now=False, auto_now_add=False) created_at = models.DateTimeField(auto_now=True, auto_created=True) updated_at = models.DateTimeField(auto_now=True) class UnderWay(models.Model): id = models.BigAutoField(primary_key=True) incident = models.ForeignKey(Incident, null=True) telephone = models.CharField(max_length=30, blank=True) time = models.CharField(max_length=30, blank=True) created_at = models.DateTimeField(auto_now=True, auto_created=True) views.py class LastIncidentApiView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" queryset = [Incident.objects.order_by('created_at')[0]] serializer_class = IncidentSerializer def perform_create(self, serializer): """Save the post data when creating a new incident.""" serializer.save() class UnderWayApiView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" # active = Incident.objects.latest('created_at').pk queryset = [UnderWay.objects.all()] serializer_class = UnderWaySerializer def perform_create(self, serializer): """Save the post data when creating a new incident.""" serializer.save() serializers.py class IncidentSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model … -
Sending SMS with django_q efficiently based on start date of project
This is an advisory application. The idea is this, basically: the company advises on home brewing. There are three advisors: default and two professionals. If a member didn't sign up for a professional advisor, he gets advises from the default advisor available to all members. So far, the models look like this: class Advisor(models.Model): name=models.CharField(max_length=10) is_default=models.IntegerField(default=0) class MemberAdvsior(models.Model) member=models.ForeignKey(User) advisor=models.ForeignKey(Advisor) The advises are based on day such as on day 1, do this, on day 2 do this. An advisor can draft his/her own days so: class Tip(models.Model): advisor=models.ForeignKey(Advisor) day=models.IntegerField() action=models.CharField(max_length=200) Now a member will basically state the date he has started brewing: class Brews(models.Model): member=models.ForeignKey(User) startedon=models.DateField() class TipsSent(models.Model): brew=models.ForeignKey(Brews) deliveredon=models.DateField() So based on his startedon field, I need to send him daily tips or actions of what to do on that day. I have googled and found django_q to do a scheduled task but I am still wondering if there are efficient ways to see if the member belongs to an advisor or not, get the advise for the day and email him plus add to to TipsSent model. While we are at it, is my database approach good enough? -
Django: 'NoneType' object has no attribute 'user', although it is defined
I'm new to django, and trying to use this code to get an image url and save it to the database: @login_required def image_create(request): if request.method == 'POST': #form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): #form data is valid cd = form.cleaned_data new_item = form.save(commit=False) #assign current user to the item: new_item.user = request.user new_item.save() messages.success(request, 'image added successfully') #redirect to the new created item detail view: return redirect(new_item.get_absolute_url()) else: #build the form with the data provided by bookmarklet via GET: form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form}) but when I try to add an image using this url: localhost/images/create/?title=IMAGE_NAME&url=SOME_URL i get the following error: AttributeError at /images/create/ 'NoneType' object has no attribute 'user' and it points to line 17 of the view, which is: new_item.user = request.user I'd be grateful of your help! -
Django Application's Dynamic Menu From Database
How to make a dynamic menu(url) like wordpress or any cms by Django. When i will create a new menu from django admin then auto add a menu item on my webapp. Please give me solution .... -
Django: How to disable Database status check at startup?
As far as I know Django apps can't start if any of the databases set in the settings.py are down at the start of the application. Is there anyway to make Django "lazyload" the initial database connection? I have two databases configured and one of them is a little unstable and sometimes it can be down for some seconds, but it's only used for some specific use cases of the application. As you can imagine I don't want that all the application can't start because of that. Is there any solution for that? I'm using Django 1.6.11, and we also use Django South for database migrations (in case that it's related somehow). -
Why JsoneResponse does not return data
Why JsoneResponse does not return anything, it just reloads the page, and everything does not give out the information I gave him! this is usrls.py url(r'^api/data/$', get_data, name="api-data") this is views from django.http import JsonResponse def get_data(request): data = { "sales": 100, "customers": 10, } return JsonResponse(data) if i go through this url http://127.0.0.1:8000/api/data he just reload page and nothing return why? just reload page, and all! -
Django 1054, "Unknown column 'emp_id' in 'field list"
I am trying to add related field emp_id using django admin username field. emp_id: was presented in Employee Table common name between Django admin and table Employee is username i am using DRF - SerializerMethodField but still it says above error.. how do i solve this? -
Redirect user to another url after POST request
I'm working on a django app and I need to redirect user to another url after processing the POST request in views. How can I redirect? something like return redirect('user:deploy'). Help me, please! Thanks in Advance! -
Django count in model
I have a simple model to register if any user like an article in my blog. class Like(models.Model): articles = models.ForeignKey(Articles, verbose_name="Article", null=True, blank=True) user = models.ForeignKey(User, verbose_name="Auteur", null=False) I just record the user ID and the article ID. This is the model of Articles : class Articles(models.Model): title = models.CharField(max_length=50, null=False, verbose_name="Titre") text = HTMLField() image = models.FileField(upload_to='media/articles/', validators=[validate_file_extension], blank=True, null=True, verbose_name="Image de présentation") games = models.ForeignKey(Games, verbose_name="Jeux", blank=True, null=True) author = models.ForeignKey(User, verbose_name="Auteur") is_statut = models.BooleanField(default=True, verbose_name="Statut") date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création") update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification") I wonder how to do to count for each articles how many "likes" are there ? I would like to return a list[] like this list[(id_article, number_of_like), ] if possible ? Thanks -
Execute shell script with sudo inside Django view
Am trying to execute a script subprocess.check_call(["sudo","/home/user/test.sh", username+".domain.xyz",username]) Here is what I have added to my /etc/sudoers www-data ALL = NOPASSWD: /home/user/test.sh %www-data ALL = NOPASSWD: /home/user/test.sh Am still receiving the following error sudo: no tty present and no askpass program specified How do I fix this? -
auto update many to many field
i have following database model class Author(models.Model): choices=['Mr.','Mrs.','Er.','Dr','Prof',] name=models.CharField('Authors Name',max_length=50) dob=models.DateField('Birth Date',null=True) addr=models.CharField('Address',max_length=100,null=True) email=models.EmailField('Email',null=True) salutation=models.CharField('Salutation',max_length=4) headshot=models.ImageField(upload_to='authors/',null=True,blank=True) books=models.ManyToManyField(Book,null=True,blank=True) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __str__(self): return self.name class Book(models.Model): title=models.CharField(max_length=100) authors=models.ManyToManyField(Author) publisher=models.ForeignKey(Publisher) publication_date=models.DateField() pages=models.IntegerField(blank=True,null=True) price=models.FloatField() cover=models.ImageField(upload_to='books/',null=True,blank=True) def __str__(self): return self.title The Book, Author and Publisher objects will be created from django administration. For every Book object created and selected an Author from authors list the books attribute of Author should be automatically updated with book that are contributed by that author. i.e if there are authors named Ram, Shyam, Hari and if new book object is created with authors Shyam and Hari and another with Shyam and Ram. The requirement is that books field of Shyam should be automatically updated with Two Book objects. How can it be done? -
django.contrib.auth.base_user import AbstractBaseUser ImportError: No module named base_user
django error when migrating the second project on the same from django.contrib.auth.base_user import AbstractBaseUser ImportError: No module named base_user. this error is driving me crazy. somebody else asked the same question here -
Customize the Django Swagger Framework
I'm looking for how to make a GET in django swagger framework by refClient (a unique CharField in my client's model). I found on the internet that I have to customize the routers, I have that as routers : from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer schema_view = get_schema_view( title='Swagger documentation', renderer_classes = [OpenAPIRenderer, SwaggerUIRenderer], ) # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter(trailing_slash=False) router.register(r'clients/{refClient}', ClientViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), # To show the swagger documentation url(r'^swagger/', schema_view, name="docs"), url(r'^api/v1/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] But I got this error ValueError: invalid literal for int() with base 10: 'refClient' [21/Jul/2017 15:25:22] "GET /swagger/ HTTP/1.1" 500 133494 Should I add something to my serializers's configuration class ClientSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Client fields = ('refClient', 'nom', 'prenom') Or to my views ? class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer def get_queryset(self): """ GET : get all clients """ return Client.objects.all() def create(self, request): """ POST : Create a Client object """ return super(ClientViewSet, self).create(request) def retrieve(self, request, pk=None): """ GET : …