Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Delete an specific record
I need your help please I'm trying to delete an specific record in my table that I already created, I have trying some codes but not working in my django version 1.10.4, Can someone help me? Here's what I have: Views.py from django.shortcuts import render from django.conf import settings from .forms import regForm from .models import registro from registro.forms import regForm from django.shortcuts import get_object_or_404 from django.core.urlresolvers import reverse def test_reg(request): form = regForm(request.POST or None) queryset = registro.objects.all() # query_delete = queryset.delete() context = { "form": form, "queryset": queryset, } if form.is_valid(): instance = form.save() return render(request, "registro.html", context) def delete(request, id): note = get_object_or_404(registro, pk=id).delete() return HttpResponseRedirect(reverse('/')) Template <form method="POST" action="">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Registrame" /> </form> <style> table, th, td { border: 1px solid black; } </style> <table> <tr> <th>Name</th> ... <th>Age</th> ... <th>Delete</th> </tr> {% for item in queryset %} <tr> ... <td>{{ item.name }}</td> ... <td>{{ item.age }}</td> ... <td> <a href="{% url 'delete' pk=registro.id %}">Delete</a> </td> </tr> {% endfor %} </table> urls.py from django.conf.urls import include, url from django.contrib import admin from myselect import views from registro import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^select/', include('myselect.urls')), url(r'^delete/(?P<id>\d+)/$',views.delete, name='delete'), url(r'^$', views.test_reg, … -
Error installing Django CMS
I'm very new to Django/Python. I just installed Django 1.8 yesterday. The client needs a Django CMS setup. I followed the necessary steps on the Django CMS website to install it on my Mac and it keeps erroring out: http://d.pr/i/dAyw The help guide talks about library dependencies. And I don't even understand the error well enough to know if that's the problem. I installed Pillow, not sure if that was necessary.. https://djangocms-installer.readthedocs.io/en/latest/libraries.html I don't understand what any of this means and if this is related. Do I need any of these libraries to make it work? None of those commands look like the install commands I'm used to. -
Why do I always start an application in Django I do not see the CSS style?
I would like to know what the problem is with the CSS style of my applications. Every time I start a new application this never appears and I check the configurations with my colleagues and they are practically the same. Does anyone know why this is due? We use the same version of Python and Django. Thank you for all your contributions. -
Is it possible to create a Django model's managed attributes (@property) with the parameter
I have a model with a function that depends on an external parameter class MyModel(models.Model): some_filed = ... @property def my_property(self, user=None): try: qs = OtherModel.objects.get(field1=self, user=user) except OtherModel.DoesNotExist: return None return qs.field2 So I need annotate with my_property like this MyModel.objects.all().annotate(field2=my_property(user=user)) -
In Django, how do I access template values in the views.py?
I'm fairly new to Django and I'm working on a page that takes in user information. If all of the information is correct, it will proceed to the next page. However, if the user does not provide all given info, it will to refresh the page. My problem is that there are quite a bit of fields the user has to fill out and if the person misses any fields, I don't want them to have to re-type everything out. So my workaround for it is that in the views.py I created a dictionary and it populates it with the input names in the template. However, when I go to run the code, it gives me an error saying that the values in my dictionary do not exist. I'm now thinking that my dictionary is not actually accessing any of the template values. Here is my template: <!DOCTYPE html> {% extends "Checklist/base.html" %} {% block main_content %} {% load static %} <html> <body> <form action="{% url 'Checklist:signin_check' %}" method="post"> {% csrf_token %} <ul style="list-style-type:none"> <li> <label for="driver_first_name">Driver First Name:</label> <input type="text" name="driver_first_name" value="" id="driver_first_name"> </li> <li> <label for="driver_last_name">Driver Last Name:</label> <input type="text" name="driver_last_name" value="" id="driver_last_name"> </li> <li> <label for="driver_wwid">Driver WWID:</label> … -
Django paginator page range for not displaying all numbers
I have a pagination in my site but it shows me every page like 1-19, i only want to display only 5 pages. How can i do this? views.py paginator = Paginator(object_list, new_number_of_list) page = request.GET.get('page') try: Items = paginator.page(page) except PageNotAnInteger: Items = paginator.page(1) except EmptyPage: Items = paginator.page(paginator.num_pages) variables = RequestContext(request, {"Items": Items, "ForItemCount": ForItemCount, "page": page, }) return render(request, 'templates/Core/resource_base.html', variables) my pagination.html <div class="pagination p1"> <span class="step-links"> <ul> {% for l in Items.paginator.page_range %} <li><a href="?page={{forloop.counter}}">{{forloop.counter}}</a></li> {% endfor %} </ul> </span> </div> -
filling an existing instance of a model from a form without creating a another one
How can I fill some of the fields of a model instance from a form without creating a new instance of it. I have this view below but does not work so far, it creates a new instance after the save() method. ? def form_data(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = Post(request.POST) if form.is_valid(): post = form.save() return redirect('/post/') -
Group by two columns, distinct by one, and order by the count
Struggled quite allot with the title of the question :) I'm a beginner in python & django and i have a query i'm trying to make My (simplify) model is: users, trips, countries. User can create many trips he wants with whatever country he wants. He can create multiple trips to the same country as well. My goal is to fetch the top 15 countries with the most trips created by different users + the count. Means that if one user created 10 trips to the same country it considers as one. What I've achieved so far is hottest_countries = models.Event.objects.values('country')\ .exclude(creator=None) \ .annotate(count=Count('country'))\ .distinct() \ .order_by('-count')[:15] this will return the countries and the count for each country but not by different users. So I've changed my code to this hottest_countries = models.Event.objects.values_list('country', flat=True) .exclude(creator=None) \ .annotate(count=Count('country'))\ .distinct() \ .order_by('-count')[:15] # Getting all the creators of each country creators_for_country = [models.Event.objects.values_list('creator', flat=True).filter(Q(country=country_id)).distinct() for country_id in hottest_countries] # Sorting again to make sure hots_events_sorted = [{"country_id": country_id, "count": len(creators_for_country[idx]), "creators": creators_for_country[idx]} for idx, country_id in enumerate(hottest_countries)] hots_events_sorted.sort(key=itemgetter('count'), reverse=True) It is working, but: A. I think it is to complicated. and must be easier way. B. Can be that the top 15 … -
Django Template: using double curly brace in template tag
What I am trying to do is allow different, but very similar views to use the same template. There is a url reference, where the only thing that differs between them is the second half of the reverse call. Using the example below, I get a NoReverseMatch, which makes sense if the code below is not accepted. {% url outer:{{suffix}} %} What is the correct way to achieve this? or do I have sacrifice conciseness, and write out the url? -
Django how to wait for asynchronous MQTT message within REST request
I am developing a REST service in Django, when request is received in server a MQTT message is published and response is received in a topic. MQTT communication is asynchronous, but REST is synchronous, I am wondering how can I wait inside REST request for a MQTT asynchronous event. I was thinking about registering all MQTT responses in a database and inside REST make a polling to DB during a maximum of 30 seconds for example, but I dont now whether this is the best solution. @require_http_methods(["GET"]) def getvalue(request): topic = "send/784980/566734/9227445/foo/foo/01/send" msg = 'SJDUEHRYT756' logger.info('Topic: ' + topic + ", msg: " + msg) if connected == False: errorMsg = '{ "error":"No MQTT connection available" }' logger.error(errorMsg) return HttpResponse(status=500, content=errorMsg, content_type="application/json") mqttResult = client.publish(topic, msg, 0, False) logger.debug("MQTT request published with id " + str(mqttResult[1])) // here I should get MQTT response for sending it back return HttpResponse(json.dumps({}), content_type="application/json") def on_message(client, userdata, msg): logger.debug(msg.topic + " " + str(msg.payload)) -
Django Admin Inline returning empty extra instances
First time posting, having a bit of a weird issue with Django's Admin TabularInline. Couldn't seem to find the problem in any searches. When I add a value - in this case a Financial Quote - and save the entry, the page will refresh having added the instance and an additional 2 entries that have empty values in every field. The same happens if I flag them for deletion from the admin page. It deletes all entries and then adds 3 more in the place of the previous ones. The same happens with the Invoice model (which is a similar model) but not with the Purchase models which behaves as expected. This leads me to think i've done something odd when I've written the models. Image attached to show the result. Hopefully someone can see where i've gone wrong Thanks! models.py class Quote(models.Model): job = models.ForeignKey(Job, related_name="quotes", on_delete=models.CASCADE) number = models.AutoField(primary_key=True) currency = models.ForeignKey(Currency, blank=True, null=True) amount = models.DecimalField(max_digits=20, decimal_places=2, default="0.00", verbose_name="Amount Invoiced") created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey(Profile, related_name='quoted', blank=True, null=True, on_delete=models.SET_NULL) sent = models.BooleanField(default=False) superceded = models.BooleanField(default=False) tax = models.DecimalField(max_digits=20,decimal_places=2,default=20.00, verbose_name="Tax Rate") def __unicode__(self): return self.created.strftime("%B %d, %Y") + " | " + u'%s' % (self.currency) + … -
Django File object saved to model not showing up in form
I have an issue where I'm copying a file from one model instance to another model instance (They are different models). In a nutshell, I do something along the lines of: model1_instance = Model1.objects.first() model2_instance = Model2() model2_instance.pic = model1_instance.pic model2_instance.save() Now after I do this, if I do model2.pic it shows up. When I look at the instance in Django admin, it shows that there is a pic for model2. The problem is that on a form that uses that model2_instance as the initial data does not pick up that there is a file and has the "No File Chosen" text from the FileUpload Input, which shows normally when there is no file. When I save the model2_instance through the form it shows up like normal and has been fully functional. It's just the initial save from the model1_instance where it's not showing up. I've tried many different ways of accessing the model1_instance.pic such as with File, ContentFile, model1.instance.pic.file, model1_instance.pic.open() and model1_instance.pic.read(). I'm guessing the form does some magic that I'm not doing when programatically copying the file to the new model. -
redirect with primary key django {% url %}
I want make blog, where i have categories and posts inside. Categories should be despayed and when you click on it, redirects to another site where articles of this category are shown. models.py class Category(CMSPlugin): title = models.CharField(max_length=20, default='category') def __unicode__(self): return self.title class Blog_post(CMSPlugin): category = models.ForeignKey(Category) style = models.ForeignKey(Blog_style) title = models.CharField(max_length=200, default='title') description = models.CharField(max_length=200,default='description') image = models.ImageField(upload_to='static', null=True, blank=True) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __unicode__(self): return self.title views.py def Blog_list(request): posts = Blog_post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') category = Category.objects.all() return render(request, 'blogspot.html', {'posts': posts, 'category':category}) def post_detail(request, pk): post = get_object_or_404(Blog_post, pk=pk) return render(request, 'post_detail.html', {'post': post}) def show_category(request, category): articles = get_object_or_404(Blog_post, category=Category) return render(request, 'articles.html', {'articles': articles}) blogspot.html {% for post in posts %} <h1><a href="{% url 'post_detail' pk=post.pk %}">{{post.title}}</a></h1> {{ post.category }} {{post.title}} {{ post.description }} {{ post.image }} {{ post.text }}{{ post.published_date }} {% endfor %} So far works all ok. I can click on {{post.title}} and im redirected to post_detail. Now i want to make same logic with categories. When i click on {{post.category}} i want redirect to articles.html where u can see all articles in specific category. And url … -
Currency switching in Django
Is there a way to switch currency globally? I'm working on a web where users has stored many products with two different currencies. I want to allow user to switch between currency1, currency2 or let original currencies for products (so one price is in currency1, another in currency2). My way is to create a radio buttons or a dropdown with options and when user choose one of them, the value is sent to the view. def products(request): cur = request.POST.get('currency') if cur: context['cur'] = cur return render.... And in template do something like: {% for product in products %} {% if cur=='eur' %}product.eur_price{% elif cur=='czk' %}product.czk_price{% else %}product.original_price{% endif %} {% endfor %} Now, to make it work "globally", I can assign currency choice to user in the view: request.user.userprofile.preferred_currency_choice='eur' I'm curious if there is a more simple or straighforward way to do such thing. -
How to create label_command ind django1.10
I am moving to Django1.10 from django 1.6.11 (I know this is very old. But finally moving to latest version) My management commands are breaking. class Command(LabelCommand): label = 'filename' def add_arguments(self, parser): parser.add_argument('filename', nargs='+', type=str) def handle_label(self, filename, **options): print filename Is this the correct way ? The above is not working as expected i.e. -
Bringing Information from django.contrib.auth.models.User into View
I have the following model in my Django project: from django.contrib.auth.models import User class Project(models.Model): project_title = models.CharField(max_length=200) project_description = models.CharField(max_length=200, default="") created_date = models.DateTimeField('date created') owner = models.ForeignKey(User) def __str__(self): return self.project_title This view uses the Project model as follows: class ProjectView(generic.edit.UpdateView): model = Project fields = ['project_title','project_description'] template_name = 'steps/project.html' success_url = reverse_lazy('steps:index') My question is how can I bring the User's fields into my ProjectView so I can then use them in templates? In particular, I would like to display the logged-in user's name and email. -
Django : Re open form pop up if errors
I'm newbie in javascript. In my page I have a form opened in a popup when user clic on register ("inscription" in french) : <header> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="block"> </div> </div> <div class="col-md-6"> <div class="block align-right"> <a href="#">Demander de l'aide</a> <!-- Register Section --> <a href="#" data-toggle="modal" data-target="#registerModal" data-whatever="@mdo">S'inscrire</a> <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerlLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="registerlLabel">Inscrivez-vous !</h4> </div> <div class="modal-body"> <form class="rex-forms" method="post"> {% csrf_token %} <div class="form-group"> {{ form.username }} </div> {% if form.email.errors %} {% for error in form.email.errors %} {{ error|escape }} {% endfor %} {% endif %} <div class="form-group"> {{ form.email }} </div> <div class="form-group"> {{ form.password }} </div> <div class="form-group"> {{ form.re_password }} </div> <div class="modal-footer"> <button type="submit" class="rex-bottom-medium rex-btn-icon"> <span class="rex-btn-text">inscription</span> <span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span> </button> </div> </form> </div> </div> </div> </div> ... But when I send form's data, if I have errors, the popup is not opened, and I need to reclick on register for seen errors... I think i need to recall a js function for reopened the popup. I search in my file script.js but with no results... This is the … -
Django - Creating an if statement based on the request path : not working
I'm trying to create a div within my view that should only be generated if both the words 'org' and 'dashboard' are in the page URL. I've looked at other similar questions on SO but they the solutions don't seem to work for me. I have also tried putting the phrases org and dashboard within quotation marks which will actually display the div on the page; however this will be displayed on the page regardless of whether those phrases are in the page URL. HTML: {% if org and dashboard in request.path %} <div id='url-req-brn'> <div class='max margins'> <h4 id='url-req-brn-h4'>You must be logged in to view the requested page.<h4> </div> </div> {% endif %} Thanks -
Image is not displaying Django + Angular
Earlier I was facing problem when I refresh the page. With this Solution I manage to solve the problem. But after applying this to url pattern, image is not loading properly. If I try to open the source of image in new tab , it redirects me to index page. When url pattern is url(r'^.*$', IndexView.as_view(), name='index'), image is not displayed but page is refreshed properly . When url pattern is url(r'^$', IndexView.as_view(), name='index'), image is displayed but page is not refreshed properly (Page not found) error How to solve this. -
Zeromq PULL in Django
I am trying to make a ZeroMQ PUSH-PULL event management in Django. Based on this link, I will be creating a PUSH client as : context = zmq.Context() zmq_socket = context.socket(zmq.PUSH) zmq_socket.connect("tcp://127.0.0.1:5557") for num in xrange(20000): work_message = { 'num' : num } zmq_socket.send_json(work_message) and a PULL server as: context = zmq.Context() consumer_receiver = context.socket(zmq.PULL) consumer_receiver.bind("tcp://127.0.0.1:5557") work = consumer_receiver.recv_json() data = work['num'] print data Implementing PUSH/PULL in a separate file works fine. But I want the PULL server functionality in Django views. That is, whenever a message is received, I want it to be received on Django and I can operate Django ORM. How do I handle this? Thanks. -
Django OAuth Toolkit Resolving Scopes
I would like to use the Django OAuth Toolkit to authorize users for a SPA (single page application) I am developing. I want to host my own authorization server to authorize my own application (not social login). I followed the excellent tutorial located at https://yeti.co/blog/oauth2-with-django-rest-framework/. Everything is working correctly, however, I don't seem to understand how I would allow a certain user to have certain scopes. The documentation details the default read and write scopes where a user can request a given scope. What I can't seem to find is how to disallow certain scopes to certain users. For example, as an administrator I would like to request some arbitrary scope, i.e. admin, and the system would recognize my credentials and allow the scope for my token. Obviously, if a regular user tried to request the admin scope, they should be denied. Placing this in the configuration file makes the application aware of a new scope, but what method do I implement to decide what scope a user can request. OAUTH2_PROVIDER = { 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'admin': 'Admin access.'} } Thank you very much for your time! -
Django CreatView not saving
I am having trouble using CreateView here. My UpdateView works, and my parameters are the same as my class for CreateView, but when I submit the form, it doesn't save. Since I'm not trying to customize the GET or POST, I'm not sure why this shouldn't work. views.py class ModelFormWidgetMixin(object): def get_form_class(self): return modelform_factory(self.model, fields=self.fields, widgets=self.widgets) class MyDateTimePicker(DateTimePicker): js_template = """ <script> (function defer() { if (window.jQuery) { $(function(){ $("#%(picker_id)s:has(input:not([readonly],[disabled]))").datetimepicker(%(options)s); }); } else { setTimeout(function() { defer() }, 50); } })(); </script>""" class JobCreate(ModelFormWidgetMixin, CreateView): model = Job template_name = 'jobs/job_form.html' success_url = '/jobs/' fields = [ 'customer', 'employee', 'salesperson', 'vehicle', 'type', 'description', 'address', 'city', 'state', 'zip', 'scheduled_time', 'estimated_completion_time' ] widgets = { "scheduled_time": MyDateTimePicker(options={"format": "YYYY-MM-DD HH:mm a"}), "estimated_completion_time": MyDateTimePicker(options={"format": 'YYYY-MM-DD HH:mm a'}), } models.py class Job(models.Model): customer = models.ForeignKey(Customer) employee = models.ForeignKey('employees.Employee', null=True, blank=True) salesperson = models.ForeignKey('employees.Employee', null=False, blank=False, related_name='salesperson') vehicle = models.ForeignKey(Vehicle, null=True, blank=True) type = models.ForeignKey(JobType) description = models.TextField(verbose_name="Full Description", null=True, blank=True) address = models.CharField(max_length=100, verbose_name="Job Address", null=False, blank=False) city = models.CharField(max_length=100, verbose_name="City", null=False, blank=False) state = models.CharField(max_length=2, verbose_name="State", null=False, blank=False) zip = models.CharField(max_length=5, verbose_name="Zip Code", null=True, blank=True) scheduled_time = models.DateTimeField(verbose_name="Scheduled Time", null=True, blank=True) estimated_completion_time = models.DateTimeField(verbose_name="Estimated Completion Time", null=True, blank=True) completion_time = models.DateTimeField(null=True, blank=True) final_price = … -
'WSGIRequest' object has no attribute 'user'
I, for the life of me, can't get this to work. I've researched what this error means and have really only received a response close to "change MIDDLEWARE to MIDDLEWARE_CLASSES". This did not work. I've tried rearranging Middleware Classes, however, this too did not work. Is there anything in my code i should be concerned with that is causing this error? Methodology: When a user logs in, the user is directed to .com/user/ which will determine which dashboard to display based on the is_userA or is_userB attribute. However, when I log in, im presented with the 'WSGIRequest' object has no attribute 'user'. traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/user/ Django Version: 1.10.3 Python Version: 2.7.11 Installed Applications: ['django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'allauth', 'allauth.account', 'allauth.socialaccount', 'userprofiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/*/Desktop/*env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/*/Desktop/*env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/*/Desktop/*env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/*/Desktop/*env/*/userprofiles/views.py" in logged_in 5. if request.User.Profile.is_userA: Exception Type: AttributeError at /user/ Exception Value: 'WSGIRequest' object has no attribute 'User' views.py from django.shortcuts import render def logged_in(request): if request.User.Profile.is_userA: return render(request, "userA_dashboard.html") if … -
Error after installing crispy form
I'm new to django but after installing django crispy form with pip install django-crispy-forms and having added 'crispy_forms' in my settings.py, I still have an Unresolved reference when I add from crispy_forms.helper import FormHelper in my forms.py -
how to trigger the clear checkbox in an ImageField in django
in my models I have a class: class Location(models.Model): name = models.CharField(max_length=200) image_file = models.ImageField(upload_to=get_filename,null=True, blank=True) This gives me an image field with an additional "clear" checkbox. I was wondering how I could trigger this clear function from shell. After creating a location with an image I tried: ./manage.py shell from myapp.models import Location l = Location.objects.all() l[0].image_file.save(clear=True) l[0].image_file.clear=True But none of them worked. Is there any way to manually trigger this clear checkbox? It has nothing to do with the delete function, that much I was able to figure out.