Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template static imagens with absolute path
I need to create this tag: <meta name="name" content="{{ request.build_absolute_uri }}{% static 'app/images/my.png' %}"> This print: http://127.0.0.1:8000//static/app/images/my.png I need to print: http://127.0.0.1:8000/static/app/images/my.png How can I remove this "/"? -
How to migrate from custom primary key to default id
I have created a model with email address as custom primary key as follows: email = models.EmailField(max_length=255, primary_key=True,) Now I realized that this is not a good idea in my case and I would like to go back to the automatically generated id field as primary key. How to do this? I tried this in different ways but all failed. I am using Django 1.10.4 with Python 3.4.3 with an SQLite database. I just replaced the primary_key=True option by unique=True. python manage.py makemigrations complains: You are trying to add a non-nullable field 'id' to user without a default; we can't do that (the database needs something to populate existing rows). If I specify 0 as default value, python manage.py migrate fails with django.db.utils.IntegrityError: UNIQUE constraint failed: login_user.id Based on this post Change Primary Key field to unique field I tried to add an Autofield manually, as in: id = models.AutoField() Now python manage.py makemigrations fails with: login.User.id: (fields.E100) AutoFields must set primary_key=True. If I do as suggested by the error message, I get the same issue as in my first try: missing default value. What is the correct way to do this? -
How does django forum app order posts by latest reply submit date?
Post model: class Post(models.Model): replies = GenericRelation(Reply, object_id_field='object_pk', content_type_field='content_type') Reply model: class Reply(models.Model): submit_date = models.DatetimeField() I write this query clause: Post.objects.all().annotate( latest_reply_time=Max('replies__submit_date') ).order_by('-latest_reply_time') This work nicely if post already have a reply. But for new posts which don't receive any reply would not be ordered correctly. Any solution using django ORM query method? Or raw SQL solution? I don't want add a latest_reply_datetime field in my post model. -
make django to handle date and time on database end
Brief ... q = Question.objects.get(pk=1) q.pub_date = timezone.now() q.save() for the above, django will generate the below SQL query for SQLite database. UPDATE "polls_question" SET "question_text" = 'What''s up?', "pub_date" = '2016-12-16 11:58:37.092622' WHERE "polls_question"."id" = 1 note that the value of pub_date is assigned literally rather using datetime('NOW'). Similarly, ... Question.objects.get(pub_date__year=timezone.now().year) will generate SELECT "polls_question"."id", "polls_question"."question_text", "polls_question"."pub_date" FROM "polls_question" WHERE "polls_question"."pub_date" BETWEEN '2016-01-01 00:00:00' AND '2016-12-31 23:59:59.999999' for this also django generating literal values for BETWEEN. Question How can I make date and time to be handled on the database end? In other words, I want django to use literal values of date and time only when I specify it explicitly in all the cases. -
Django Rest Send Data to Django
This is probably a dumb and simple question and it shows I didn't understand the very basics of django-rest but I have been using django-rest with several serializers and viewsets but haven't need such as this. I want to create an end point and send an 'id' to it. Then I want to copy an object with that id like obj = SomeModel.objects.get(pk=id) obj.id = None obj.save() So I don't need to serialize anything or need a view with queryset. How can I achive this? -
table django_site does not exist while deploy to aws elastic beanstalk
I am trying to deploy django rest app to aws elastic beanstalk. I made all configurations. //.ebextensions config file option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "app.settings" "PYTHONPATH": "./src" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: "path_to_wsgi.py" NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" container_commands: 01_makemigrations: command: "source /opt/python/run/venv/bin/activate && python app/manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /opt/python/run/venv/bin/activate && python app/manage.py migrate --noinput" leader_only: true 03_createsu: command: "source /opt/python/run/venv/bin/activate && python app/manage.py createsu" leader_only: true 04_collectstatic: command: "source /opt/python/run/venv/bin/activate && python app/manage.py collectstatic --noinput" However when I do "eb deploy" it gives me the error; django.db.utils.ProgrammingError: (1146, "Table 'ebdb.django_site' doesn't exist"). container_command 02_migrate in .ebextensions/02_python.config failed. I have "django.contrib.sites" in settings.py->INSTALLED_APPS. I have also SITE_ID = 1 in settings.py I couldn't figure out the problem. -
How to keep a form's entered values when the user changes the website language via Django's i18n/setlang?
I use Django 1.9.9 with the i18n set_language view to change website languages. I have some pages with forms on them, e.g. for collecting project-specific user data. When a user enters data into such a form, but changes the language before saving the form, the entered data is lost. Is there a way to prevent this from happening? -
Django app with three tables that need many-to-many fields
I have a Django app that I am working on that has three separate tables. The three tables would be a list of servers, a list of databases, and a list of applications. Each of these tables can reference one or more object from both of the other tables (eg. a database can be used by multiple applications and reference multiple servers if it has been transferred between them for historical purposes). How would something like this be setup with many to many fields in Django (I assume something like two m2m for serverlist and than a single m2m for the databaselist to the application list but I have been unable to find any examples of something like this). -
Arrayfield django unsupported type
I have following in the models question_array = ArrayField(models.IntegerField(blank=True,name='Hi'), blank=True,size=50) Get the following error while adding from admin panel InterfaceError at /admin/comp/user/add/ Error binding parameter 17 - probably unsupported type. Request Method: POST -
How to logout on all browsers if I logout in one browser in Django?
I have a Django application, where users can login/logout using Django's inbuilt authentication system. I am not using any session-concept in the backend to maintain different sessions for logged-in users. I am using a single field in my custom model to store the login/logout state. Now if any user logins from 2 different browsers, login_state will be true. -
No module named ho.pisa - when i run it with wsgi
I'am trying to generate PDF from HTML whith Pisa, Reportlab, etc.. and get: "No module named ho.pisa" - when i run it with wsgi, but on runserver it works fine. Somebody have some versions? -
Django- datetimepicker that's displayed in form.visible_fields only displays certain dates
I have recently taken over the development of a Python/ Django project, and have an issue with a datetimepicker that's used to allow the user to select a date/ time in one of the fields on a form. The view for this page is defined with: def handover(request, project_id): project = Project.objects.get(id=project_id) deposit = Deposit.objects.get_or_create(project=project)[0] survey = Survey.objects.get_or_create(project=project)[0] cdi = Cdi.objects.get_or_create(project=project)[0] context = { 'project': project, 'deposit_overview_form': DepositForm(instance=deposit), 'deposit_form': DepositInfoForm(instance=deposit), 'postdep_meeting_form': PostDepMeetingForm(instance=survey), 'summary_form': PostDepSummaryForm(instance=project), } return render(request, 'projects/handover.html', context) and the part of the template that's displaying this field is: <div> <div class="expand-header"><strong>Post deposit meeting</strong></div> <table class="left"> {% include "projects/includes/stacked_form.html" with form=postdep_meeting_form %} </table> </div> If I open up the stacked_form.html file that's included here, it has the following content: <div class="col-6 col-sm-12 box"> ... {% load utilities %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form.visible_fields %} {% if field|is_checkbox %} <tr><td colspan="1">{{field}}</td><td colspan="6"><label>{{field.label}}</label></td></tr> {% else %} <tr><td colspan="7"><label>{{field.label}}</label></td></tr> <tr><td colspan="7">{{field}} </td></tr> {% endif %} {% endfor %} ... </div> When I 'inspect' the field that's displaying the datetimepicker in the browser, it shows the following HTML structure: <div class="col-6 col-sm-12 box"> <div> ... </div> <div> <div class="expand-header">...</div> <table class="left"> … -
TypeError receive_money() takes exactly 3 arguments (1 given)-Django
I am trying to pass 2 parameters to a view but it gives this type error i dont know if its a problem with the urls or my redirect //urls.py urlpatterns = [ # url(r'^receive/[a-zA-Z]+/[0-9]+/$', receive_money) ] //subtract_money view def subtract_money(request): if request.user: users = User.objects.all() users_ids = users.values_list('id', flat=True) users_list = [] for id in users_ids: user = users.get(pk=id) if user.username != "ravinkohli" and user.username != request.user.username: users_list.append(user) if request.POST and request.POST.get('amount'): username = request.user.username withdraw = request.POST.get('amount') wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id) # if withdraw > wallet.amount: # return render(request, 'send_money.html', {'error': 'Amount can not be greater than balance','users': users_list}) wallet.subtract_money(withdraw) wallet.save() now = datetime.now() trans = Transaction(from_name=username, wallet_id=wallet,to=request.POST.get('receiver'), date=now, amount=withdraw) trans.save() return redirect('/receive/%s/%s/' % (request.POST.get('receiver'), withdraw)) else: return render(request, 'send_money.html',{'users': users_list}) else: return HttpResponseRedirect('/login/?next={}'.format('/subtract_money/')) //receiver view def receive_money(request, username, amount): add_amount = amount wallet = Wallet.objects.get(username=username) wallet.add_money(add_amount) wallet.save() return redirect('user_profile.html', {'user': request.user,'userprofile': Userprofile.objects.get(user=request.user), 'wallet': wallet}) -
How to add two form_class's in FormMixin?
So i've already done my register() form, which is working fine. I'm now trying to do my login() form, however the fields (username and password) are not showing up because i'm unable to add 2 values to form_class in BoxesView(). There is already a value in form_class for the register form, so I need to add another. To be honest, i'm not entirely sure how form_class is working here, or if it's possible to add another one so if someone could explain that would be great. Here's my code: views.py class BoxesView(ListView, FormMixin): template_name = 'polls.html' # extends base.html form_class = UserRegistrationForm def get_context_data(self, **kwargs): context = super(BoxesView, self).get_context_data() question_list = Question.objects.all().order_by('-date') choice = Choice.objects.all() context['question_list'] = question_list context['choice'] = choice q_list = [] returned_list = [] for i in question_list: q_list.append(i) for a, b in CATEGORY_CHOICES: name = resolve(self.request.path_info).url_name if b == name: category = a search = self.request.GET.get('search') posts = Post.objects.all().filter(category=category).order_by('-date') if search: posts = posts.filter( Q(title__icontains=search) | Q(content__icontains=search) ) else: posts = Post.objects.all().filter(category=category).order_by('-date') context['posts'] = posts total = 0 for post in posts: returned_list.append(post) total += 1 if total == 4: total = 0 for i in q_list: returned_list.append(i) q_list.remove(i) break paginator = Paginator(returned_list, 14) page = … -
Styling a generic.edit.CreateView Form in Django Using Bootstrap
I have the following view in my Django app: class TodoCreateView(generic.edit.CreateView): model = Todo fields = ['todo_name','todo_description'] template_name = 'list/todo-create.html' success_url = reverse_lazy('list:index') def form_valid(self, form): form.instance.owner = self.request.user form.instance.created_date = datetime.now() return super(EntryCreateView, self).form_valid(form) This view corresponds to the following template: {% extends 'list/base.html' %} {# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% block content %} <h1>Todo:</h1> <div> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} Obviously, Django composes and outputs the form based on the fields indicated in the View. However, it seems to leave no chance to style the form fields with CSS. How can I do that? -
CherryPy terminates session after $window.location.href
For a Django 1.8 app with Angular.js & Django Rest Framework I'm using CherryPy server to serve the app over WSGI. For this purpose I'm basically reusing this code, which works fine, until I use the following angular.js command in one of my *.js files: url = patientDetailView + response.data.id + '/'; $window.location.href=url; The view this link is pointing to requires (like other views as well) the user to be logged in(authenticated). However, although the user has been already logged in after $window.location.href=url django redirects to the login screen where the user needs to log-in again! My guess is that this may be due to the session being terminated (?). I don't see this problem while running the django dev server (./manage.py runserver) Anybody can point me to why this is happening and how to fix that? I'm running out of ideas... -
Remove ForeignKey relationship
I want to remove the relationship between BUser and Profile: Since the ForeignKey doesn't allow null values I have to iterate (performance is awful!) like this to remove all the relations: for u in user.profile_set.all(): u.delete() class Profile(models.Model): user = models.ForeignKey('BUser') class BUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=40, unique=True) There is another way to delete all the relations [with a better performance]? I've tried with: obj.transparentprofile_set = None obj.transparentprofile_set.clear() obj.transparentprofile_set.empty() but, like I said, since there's not null=True in the ForeignKey I can't use them. -
How to use only pos part of the odoo erp for my own django application
I am developing an django application for billing and inventory management and I recently came over odoo formerly known as openERP which has an excellent POS system. How can I use the POS part of the odoo platform alone with my django application ? -
django cache testing - why FileBasedCache and LocMemCache ignore timeout parameter?
Am I doing something wrong, or FileBasedCache as well LocMemCache are ignoring the timeout parameter passed by set in tests? -
import requests get "No module named django.core.mail"
i import requests,but get an ImportError:No module named django.core.mail how can i fix it... what is the relationship between django and requests? why i import requests must need django? enter image description here -
How can I order a QuerySet in Django by a charfield with numbers?
I want to order a QuerySet by a charfield with numbers in it. I have this code: MyTable.objects.all().order_by('my_char_field') There are some examples of "my_char_field": "ver3", "ver10", "ver4" The result of the order with the code above is: "ver10", "ver3", "ver4" But the order that I want is: "ver3", "ver4", "ver10" How can I get the natural order? -
How to raise JSONified exception from a custom middleware in django?
I am validating JWT token in process_request and if there is any problem it's raising exceptions. For normal exception in any view, it's going through a custom exception handler. The code for the exception handler is given below, exceptions.py def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) if response is not None: if response.status_code == 405: error_code = ERROR_405_CODES_MAPPING[context["request"].method] response.data = {"code": error_code, "message": ERROR_RESPONSE_CODES[error_code]["message"], "description": ERROR_RESPONSE_CODES[error_code]["description"]} elif response.status_code in [400, 404, 403, 409]: response.data = generate_custom_error_response(exc) return response def generate_custom_error_response(exc): error_codes_list = fetch_error_codes(exc) error_response_list = [] for error_code in error_codes_list: error_response_list.append({"code": error_code, "message": ERROR_RESPONSE_CODES[error_code]["message"], "description": ERROR_RESPONSE_CODES[error_code]["description"], "meta": ERROR_RESPONSE_CODES[error_code]["meta"]}) return {"errors": error_response_list} def fetch_error_code_from_error_structure(error_codes_list, exc): regex = re.compile("^(40)([a-zA-Z0-9_]+)(_error)$") for item in exc.values(): if isinstance(item, dict): fetch_error_code_from_error_structure(error_codes_list, item) elif isinstance(item, list): error_codes_list.extend([error_code for error_code in item if re.fullmatch(regex, error_code)]) continue elif isinstance(item, str): error_codes_list = error_codes_list_updation(error_codes_list, item) return error_codes_list def fetch_error_codes(exc): logger.exception(exc.detail) error_codes_list = [] regex = re.compile("^(40)([a-zA-Z0-9_]+)(_error)$") if isinstance(exc.detail, str): error_codes_list = error_codes_list_updation(error_codes_list, exc.detail) elif isinstance(exc.detail, list): error_codes_list.extend([error_code for error_code in exc.detail if re.fullmatch(regex, error_code)]) elif isinstance(exc.detail, dict): error_codes_list = fetch_error_code_from_error_structure(error_codes_list, exc.detail) final_error_codes_list = [ERROR_RESPONSE_MAPPINGS[code] for code in error_codes_list if code in ERROR_RESPONSE_MAPPINGS.keys()] return final_error_codes_list def … -
python3: can't open file : [Errno 2] No such file or directory
I'm deploying my webservice based on Django of python via an ec2 instance on AWS Everything goes well before adding a new module. (I deployed several times with this project without that new module) I just added crontab module to my service But when it is executed, the error occurs with "python3: can't open file '/home/ubuntu/asdf/fdsa/manage.py' : [Errno 2] No such file or directory" I think it's not about the authorization. How can I solve this? -
JavaScript file not loaded in Django custom admin page
I added a custom page containing a form in my Django admin site. To do this, I wrote this code: class MyForm(forms.Form): class Media: js = ('js/foo.js',) my_number = forms.IntegerField( required=True, min_value=1, max_value=10, label='Magic number' ) And this code: form = MyForm() context = self.each_context(request) context.update({'form': form}) return render(request, 'admin/players/foo.html', context) My problem is the JS does not execute/load because if I put the following single line in it, nothing happens: alert('foo'); What's strange is I have a very similar thing somewhere else and it works like a charm: class MyModelAdmin(admin.ModelAdmin): list_display = ('bar1', 'bar2',) search_fields = ('bar1',) class Media: js = ('js/utils/bar.js',) I checked the media property in both cases and I got this: <script type="text/javascript" src="/static/js/utils/foo.js"></script> <script type="text/javascript" src="/static/js/utils/bar.js"></script> So at least, the path to the file is OK. What did I miss? -
Wizard form failed validation on update form
I used Wizard form for Create and Update form. But the Update form failed on unique field name = models.CharField(max_length=255, null=False,unique=True)) Error showing "Book with this Name already exists." Have googling for some times and the answer I got is passing the instance: form = ArticleForm(request.POST, instance=article) The above answer cannot be applied to my code because I am using Wizard form and set the form directly from url. url(r'^admin/myapp/book/add', BookCreateWizard.as_view([BookForm1,BookForm2])) Any idea to fix this?