Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AuthenticationForm 'The view account.views.login_view didn't return an HttpResponse object. It returned None instead.'
i have problem with AuthenticationForm(), when login and passwords are correct everything work fine, but when i want to cause an error with wrong password or login instead geting 'incorrect login or password' error, i get page errorenter image description here My views.py code: def login_view(request): if request.method == 'POST': form =AuthenticationForm(data=request.POST) if form.is_valid(): #log in the user return redirect('Product_list') else: form = AuthenticationForm() return render(request, 'account/login.html', {'form': form}) My template code: {%block content%} <form class="login-form" method="POST"> {%csrf_token%} {{ form.as_p }} <input type="submit" value="Logowanie"> </form> <div id="signup"> <a href="http://127.0.0.1:8000/account/signup/"> Jeżeli nie masz jeszcze konta zarejestruj się: <input type="submit" value="Rejestracja"> </a> </div> {%endblock%} -
Easiest way to update model values using Django with an AJAX form
I have a django model which contains some fields with associated choices: class Product(models.Model): CONDITION_CHOICES = ( ("GOOD", "Good"), ("BAD", "Bad"), ("UNKNOWN", "Unknown"), ) name = models.CharField(max_length=200, blank=True, null=True) colour = models.CharField(max_length=200, blank=True, null=True) condition = models.CharField(max_length=20, choices=CONDITION_CHOICES, blank=True, null=True) condition_source = models.CharField(max_length=20, blank=True, null=True) condition_last_updated = models.DateTimeField(blank=True, null=True) I also have a bootstrap driven form that looks like: <div class="form-group"> <label class="control-label"><strong>Condition</strong></label> <br/> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-outline-primary"> <input type="radio" name="condition" value="GOOD" autocomplete="off"> Good </label> <label class="btn btn-outline-primary"> <input type="radio" name="condition" value="BAD" autocomplete="off"> Bad </label> <label class="btn btn-outline-primary"> <input type="radio" name="condition" value="UNKNOWN" autocomplete="off"> Unknown </label> </div> </div> I am trying to make it so that when a user clicks on one of the buttons in the UI, the Product model is updated (specifically the condition, condition_source and condition_last_updated fields). The actual model has multiple fields with associated with choice options so I'd like the model to get updated in real time without a page reload as a user works through the form. Any guidance would be appreciated here - I have looked at intercooler.js but unsure if this is the right tool for the job. -
How do I Build a Dropdown List Using a Filter on a ForeignKey within a Model as Choices
I am build a model with a dynamic list based on record options that are available (List below will be in a separate table) I have tried several option and continue to get the following error: "CategoryCodes.active_ID: (field.E004) 'choices' must be an iterable (e.g., a list or tuple)." ALL = '0000' SYSTEM = '9000' BUSINESS = '9002' INDIVIDUAL = '9005' PROJECT = '9006' PREFIX_TYPE_CHOICES = ( (ALL, '- All -'), (SYSTEM, 'System'), (BUSINESS, 'Business'), (INDIVIDUAL, 'Individual'), (PROJECT, 'Project') ) class TypeOptions(models.Model): type_ID = models.UUIDField(default=uuid.uuid4, editable=False) type_code = models.AutoField('Code', primary_key=True, editable=False) type_code_name = models.CharField('Code name', max_length=200, default="") type_code_default = models.BooleanField('Code default', default=False) datastructure_prefix_name = models.CharField('Segment', max_length=4, choices=PREFIX_TYPE_CHOICES, default=ALL) datastructure_name = models.CharField( 'Table name', max_length=50, default="") datastructure_element_name = models.CharField( 'Table element', max_length=50, default="") # # Date/Time records was created createDateTime = models.DateTimeField(auto_now_add=True) # # Date/Time records was updated updateDateTime = models.DateTimeField(auto_now=True) # # Active options the owner list active_ID = models.CharField('Active state', max_length=3, choices=ACTIVE_TYPE_CHOICES, default=ACTIVE) # # This defines the sorting order class Meta: ordering = ('datastructure_prefix_name', 'type_code') class CategoryCodes(models.Model): SCCID = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) state_code = models.CharField(max_length=5) state_code_name = models.CharField(max_length=100) state_code_description = models.CharField(max_length=100) # # Date/Time records was created createDateTime = models.DateTimeField(auto_now_add=True) # # Date/Time records was updated updateDateTime = … -
User Authentication taking a long time in DRF
I'm using a ModelViewSet with the IsAuthenticatedOrReadOnly permission class, like so: class PostViewSet(viewsets.ModelViewSet, MarkdownToHTML): permission_classes = (IsAuthenticatedOrReadOnly,) When I call this view in the browsable API, the data returns in about 1100 ms (already too long), but when I call it from my frontend UI, the call takes 6000-7000ms! The only difference between these two methods of calling the same view is that I am passing along a json token from my frontend UI app. When I comment out the token header, the response returns in about 1 second, the same time as in the browsable API. How could this simple authentication step take over 5 seconds? Here is the authentication class: class IsAuthenticatedOrReadOnly(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view): return ( request.method in SAFE_METHODS or request.user and request.user.is_authenticated ) -
Upgrade to Django 2.x, javascript_catalog removed
I'm currently adapting my application to support the upgrade to Django 2.x I've seen that the javascript_catalog() function isn't supported anymore. Does someone know you could I do to translate .js file using i18n, as I was previously doing with the javascript_catalog function? Thank you for your help. -
Wagtail customize PageChooserPanel page explorer view
I’m looking for a way to customize the Explorer that pops-up when using the PageChooserPanel, ideally I would like to add two more columns there. I’ve found this http://docs.wagtail.io/en/v2.2/reference/hooks.html#choosers but that only covers generating a custom queryset not adding columns, is that even possible? Alternatively I can live with only changing the default title shown on the pagechooserpanel explorer but so far adding a __str__ method to the class hasn’t worked Here a graphic representation to my question -
Django, Apache2 on Google Kubernetes Engine writing Opencensus Traces to Stackdriver Trace
I have a Django web app served from Apache2 with mod_wsgi in docker containers running on a Kubernetes cluster in Google Cloud Platform, protected by Identity-Aware Proxy. Everything is working great, but I want to send GCP Stackdriver traces for all requests without writing one for each view in my project. I found middleware to handle this, using Opencensus. I went through this documentation, and was able to manually generate traces that exported to Stackdriver Trace in my project by specifying the StackdriverExporter and passing the project_id parameter as the Google Cloud Platform Project Number for my project. Now to make this automatic for ALL requests, I followed the instructions to set up the middleware. In settings.py, I added the module to INSTALLED_APPS, MIDDLEWARE, and set up the OPENCENSUS_TRACE dictionary of options. I also added the OPENCENSUS_TRACE_PARAMS. This works great with the default exporter 'opencensus.trace.exporters.print_exporter.PrintExporter', as I can see the Trace and Span information, including Trace ID and all details in my Apache2 web server logs. However, I want to send these to my Stackdriver Trace processor for analysis. I tried setting the EXPORTER parameter to opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter, which works when run manually from the shell, as long as you supply … -
Parsing RSS XML with python django
I'm trying to parse 3 different RSS sources, these are the sources. https://www.nba.com/bucks/rss.xml http://www.espn.com/espn/rss/ncb/news http://rss.nytimes.com/services/xml/rss/nyt/ProBasketball.xml For the most part the structure of all these three sources are similar, except for the url I'm trying to parse these into the following Feed object, class Feed(Base): title = models.CharField(db_index=True, unique=True, max_length=255) link = models.CharField(db_index=True, max_length=255, ) summary = models.TextField(null=True) author = models.CharField(null=True, max_length=255) url = models.CharField(max_length=512, null=True) published = models.DateTimeField() source = models.ForeignKey(Source, on_delete=models.CASCADE, null=True) This is the source object, class Source(Base): name = models.CharField(db_index=True, max_length=255) link = models.CharField(db_index=True, max_length=255, unique=True) This is the code that I use to parse, import logging import xml.etree.ElementTree as ET import requests import maya from django.utils import timezone from aggregator.models import Feed class ParseFeeds: @staticmethod def parse(source): logger = logging.getLogger(__name__) logger.info("Starting {}".format(source.name)) root = ET.fromstring(requests.get(source.link).text) items = root.findall(".//item") for item in items: title = '' if item.find('title'): title = item.find('title').text link = '' if item.find('link'): link = item.find('link').text description = '' if item.find('description'): description = item.find('description').text author = '' if item.find('author'): author = item.find('author').text published = timezone.now() if item.find('pubDate'): published = maya.parse(item.find('pubDate').text).datetime() url = '' if item.find('enclosure'): url = item.find('enclosure').attrib['url'] if item.find('image'): url = item.find('image') if not Feed.objects.filter(title=title).exists(): logger.info("Title:{} Link:{} Summary:{} Author:{} Published:{} Url:{}".format(title, link, description, … -
How to get and use HTTPResponse message from a DJANGO server
How can I get the response message returned from my DJANGO view and place it into a textview? Most of the answers talk about using Httpresponse but as I've read, it has be deprecated. I'm using SDK v28. Java code in Android Studio: private class HTTPAsyncTask_wdgt extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { try { try { return HttpPost_wdgt(urls[0]); } catch (JSONException e) { e.printStackTrace(); return "Error!"; } } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } } private String HttpPost_wdgt(String myUrl) throws IOException, JSONException { URL url = new URL(myUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); JSONObject jsonObject = buildJsonObject_wdgt(); //Just takes some data from the app and returns JSON to be posted. setPostRequestContent_wdgt(conn, jsonObject); conn.connect(); return conn.getResponseMessage()+""; } private void setPostRequestContent_wdgt(HttpURLConnection conn, JSONObject jsonObject) throws IOException { OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(jsonObject.toString()); writer.flush(); writer.close(); os.close(); } Django view: (Right now it just returns 'mac' from the posted JSON) @csrf_exempt def req_exec(request): ret = request.POST data = json.loads(request.body) return HttpResponse(data['mac']) -
Django: access a model's `related_name` values for all its related models
I have a model queryset for which I need to perform caching for O2M and M2M relationships, using prefetch_related. The same goes for O2O relationships, using select_related accordingly. I want to do this as a generic implementation, in which I will locate all related_name values of the related models and unpack them like this: def cache_related(): related_names = [...] # the related_name values for the prefetchable related models cached_queryset = queryset.prefetch_related(*related_names) return cached_queryset I currently access those values by using: related_models = deepcopy(queryset.model._meta.related_objects) related_names = [m.related_name for m in related_models] The problem is that I really don't want to access the protected _meta values directly. Is there a utility in Django that returns the list of all related_name values of a model's O2O, O2M and M2M relationships? I found references to django.db.models.lookups and the Lookup class, but it doesn't seem to fit my case. Thanks! -
How to create a custom error message in Django log in form?
I am making a login page for my Django app. At the moment, if I enter the wrong username or password the following error message shows up: . Is there a way that I could customise this message to get rid of the "___all____" and the bullet points? Perhaps just saying "Please enter a correct username and password. Note that both fields may be case-sensitive."? A simplified version of my code is below: views.py: from django.contrib.auth import authenticate,login,logout html: <div class="form_container"> <form class="log_in_form" action="{% url 'inventory_management_app:login' %}" method="post"> <p> {% csrf_token %} {{ form.username }} </p> <br><br> <p> {{ form.password }} <br> {{ form.errors }} </p> <p> <br><br> <input id="search-button" class="btn btn-dark" type="submit" value="Login"> </form> </p> </div> forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class CustomAuthForm(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'class':'validate','placeholder': 'Email'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password'})) urls.py url(r'^login/$', auth_views.login, name='login', kwargs={"authentication_form":CustomAuthForm}), -
APIView can't recognise Custom Queryset
I have created a custom QuerySet for my Budget model. I try to call it from my APIView but it returns an AttributeError message. When I call the QuerySet using python manage.py shell it is well recognized and it returns me the correct response. Does anyone know how to solve this ? This is custom QuerySet class BudgetQueryset(models.query.QuerySet): """ Create a custom queryset that will be called by views """ def get_budget_per_period(self, by="month"): [...] # Get objects from database and perform action return dict # return a dictionary This is the Budget Model class Budget(models.Model): [...] # Fields truncated objects = BudgetQueryset.as_manager() And this is how I call it in my views.py class BudgetReportAPIView(APIView): def get(self, request): [...] # Perform some validation return Response(Budget.objects.get_budget_period()) I get the following error message: AttributeError: 'ManagerFromBudgetQueryset' object has no attribute 'get_budet_per_period' -
From Django 1.4 to Django 2.1.5 : custom field to_python() not called anymore
I am migrating an application from python 2/Django 1.4 to python 3/Django 2.1.5. I have a strange behaviour with a custom JSON field : class JSONField(models.TextField): """JSONField is a generic textfield that neatly serializes/unserializes JSON objects seamlessly. Main thingy must be a dict object.""" def __init__(self, *args, **kwargs): if 'default' not in kwargs: kwargs['default'] = '{}' super().__init__(*args, **kwargs) def to_python(self, value): """Convert our string value to JSON after we load it from the DB""" if not value: return {} elif isinstance(value, str): res = loads(value) assert isinstance(res, dict) return res else: return value def get_db_prep_save(self, value, connection): """Convert our JSON object to a string before we save""" if not value: return super(JSONField, self).get_db_prep_save("", connection=connection) else: return super(JSONField, self).get_db_prep_save(dumps(value), connection=connection) With Django 1.4, JSONField.to_python() is called when I read an object from database, but not with Django 2.1.5 : do you known why ? -
Dynamically chosen nested serializer
I have Kit model and Product which is related to Kit with foreign key. Also there are several serializers for product - ProductASerializer and ProductBSerializer. class KitSerializer(serializers.ModelSerializer): products = ProductASerilaizer(many=True) class Meta: model = Kit fields = ['type', 'products', ...] How can I dynamically choose serializer for product, depending on type of Kit. For example If type == 1 I use serializer A, else B. So finally It could be Kit with several serializer of which type within. Thanks! -
How to slice a string value that will be displayed in a HTML tag?
How do I slice a string passed from Django context that will be displayed in a HTML tag? -
Django model - how to add order index annotation?
How can I annotate a queryset in django, to add additional field that will represent and index (place) of each row within the ordered result? I need to retrieve users in an ordered way with addition of a field (annotate) that will specify an absolute index (place) of each object within the order. That's the code I have: users = User.objects.all().annotate(total_points=Sum('score_earnings', distinct=True)).order_by('-total_points') users = users.annotate(place, /* how to get an index of each ordered? */) This is the related Scores model: class Score(models.Model): user = models.ForeignKey('users.CustomUser', related_name='score_earnings', on_delete=models.CASCADE) points = models.DecimalField(max_digits=8, decimal_places=1) So this place field should represent an index of each row in the result: 1, 2, 3, ... Later I will have to select a range from the result and expect to get the value of place field absolute: users[3:6] Result: [{ "total_points": 100.0, "place": 3 }, { "total_points": 70.0, "place": 4 }, { "total_points": 50.0, "place": 5 }] -
How to force a celery task to exactly execute under 0.5 seconds?
I'm working on a celery project. There is a module(function) which accepts requests only if the last request is less than 0.2 seconds. knock..knock..knock.. I have to knock the function always. Else the function rejects any further requests. But before knocking there is a key need to be generated based on the objects in my database and this key is sent with the request. Normally my algorithm to generate this key takes 0.09(approx) seconds. The whole point is designing the algorithm as well as learning celery. The algorithm is fine. I was able to place the requests(no need to wait for a result) for a maximum of 1 hour(it's random. sometimes 20 minutes, 30 minutes, 2 hours, etc..) Then it stops. I have been trying for days to find the bug. One thing I found in my logs is sometimes it takes 0.5 to 1 to 2.0 seconds to generate the key and place request. Also, I am not able to understand soft_time_limit and hard_time_limit. Though I tried soft_time_limit as: @task(queue="knocker", soft_time_limit=0.2) def knocker(): #generate_key based on objectsin db and current time. knock_knock(key) I'm using Redis and Celery(latest versions). And my settings are: CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER … -
How to pass user object to a Modelform using CreateView
NOT NULL constraint failed: blog_post.author_id Hi, I'm fairly new to django and can't fix this error. I'm building a blog app and I want the author to be the current user. I know that I'm not passing the user object to the form properly, but none of the solutions I found worked for me. Thank you in advance! models.py class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return '@{}'.format(self.username) class Post(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) forms.py class UserForm(UserCreationForm): class Meta: fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text',) views.py class SignUpView(CreateView): form_class = UserForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' class PostCreateView(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post -
Django Database_Router class falls on 'default' database
I'm facing an issue with the Django models database routing. I've done a fair share of research already but with no luck. First some information about the application relevant to the problem. I've chosen to use database routing to seperate the models in the application. The application is meant for n number of companies (e.g foo1) and they all have their own django application, including a near identical models.py file. The schema routing is being done by the user in the db connection. -The purpose of the 'default' db connection is to handle the models that comes with auth and contenttype. This is the same schema as foo0 as this connection is meant for an application that handles an extention of the django auth AbstractUser. My settings.py looks like this. DATABASE_ROUTERS = ['django_project.database_router.django_projectDatabaseRouter'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER' : 'foo0_user@django_projectdatabase', 'PASSWORD' : 'x', 'HOST' : 'x', 'PORT' : '5432', }, 'foo0': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER' : 'foo0_user@django_projectdatabase', 'PASSWORD' : 'x', 'HOST' : 'x', 'PORT' : '5432', }, 'foo1':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER' : 'foo1_user@django_projectdatabase', 'PASSWORD' : 'x', 'HOST' : 'x', 'PORT' : '5432', }, 'foo2':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER' : 'foo2_user@django_projectdatabase', … -
How to read Django text area input in views
I have text area input type in Django template I need to read that value in Django view Templatecode view code value = request.POST['message'] how to read textarea value in django view -
Django "Duplicate entry '' for key 'auth_user_email_b41_uniq'"
I'm having a problem that should be simple but I've been unable to solve. We have a Django (1.8) app, using MySQL as the database using the standard User object. This Object, through its inheritance of the AbstractUser model has the following email field: email = models.EmailField(_('email address'), blank=True) Note how the field has the blank=True option set while lacking a unique = True setting. Yet we keep running into the following scenario: Using the admin, we create User1 with the ```email`` field left blank We then, again using the admin, create User2 with the email field left blank This crashes the program, throwing a "Duplicate entry '' for key 'auth_user_email_b41_uniq'" error. We are at a loss of whats causing this problem, as all of the fields are set to values that should prevent this bug from occurring. Does anyone know what we are missing / doing wrong? -
Change appearance of crispy_forms file field
I know it is generally tricky to change the appearance of a file input field and I've seen tutorials how do it with css and javascript, where you hide the actually input and overlay it with a nice button. But I really want to use form.file|as_crispy_field for nice error highlighting and form validation with crispy_forms. What would the best way to make file input look more "bootstrapy"? -
Django: queryset "loosing" a value
I have 2 models, one with a list of clients and the other with a list of sales. My intention is to add sales rank value to the clients queryset. all_clients = Contactos.objects.values("id", "Vendedor", "codigo", 'Nombre', "NombrePcia", "Localidad", "FechaUltVenta") sales = Ventas.objects.all() Once loaded I aggregate all the sales per client summing the subtotal values of their sales and then order the result by their total sales. sales_client = sales.values('cliente').annotate( fact_total=Sum('subtotal')) client_rank = sales_client .order_by('-fact_total') Then I set the rank of those clients and store the value in a the "Rank" values in the same client_rank queryset. a = 0 for rank in client_rank: a = a + 1 rank['Rank'] = a Everything fine up to now. When I print the results in the template I get the expected values in the "client_rank" queryset: "client name" + "total sales per client" + "Rank". {'cliente': '684 DROGUERIA SUR', 'fact_total': Decimal('846470'), 'Rank': 1} {'cliente': '699 KINE ESTETIC', 'fact_total': Decimal('418160'), 'Rank': 2} etc.... The problem starts here First we should take into account that not all the clients in the "all_clients" queryset have actual sales in the "sales" queryset. So I must find which ones do have sales, assign them the "Rank" value … -
How to fix [Errno 13] Permission denied: 'geckodriver.log'
With same django application, same virtual environment, firefox launch with no errors using Django development server: > ./manage.py runserver 8000 so now that my Django project works on Local I wanted to deploy it using Apache and wsgi, but I am facing a problem is that I got an error to launch firefox [Errno 13] Permission denied: 'geckodriver.log' this is a sample of my code to launch firefox: from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('home/borealis/Downloads/firefox/firefox') driver =webdriver.Firefox(firefox_binary= binary) -
Overriding the delete function of BaseInlineFormset
I am looking at doing a soft delete on a record. If 'Website' is not a foreign key (say, for example 'RetailerRatingGroup') then it should be deleted as normal. However, it is the foreign key of another object, I want to cancel the deletion and instead change the Website.active property to false. Can anyone point me in the right direction as to how I might go about that. class Website(models.Model): retailer = models.ForeignKey('Retailer', on_delete=models.PROTECT) url = models.URLField() short_name = models.CharField(max_length=15) active = models.BooleanField(default=True) class RetailerRatingGroup(models.Model): retailer = models.ForeignKey(Retailer, on_delete=models.PROTECT) channel_productcat = models.ForeignKey('ChannelProductcatGroup', on_delete=models.PROTECT) website = models.ForeignKey(Website, blank=True, null=True, on_delete=models.PROTECT) current_rating = models.ForeignKey('Rating', default=None, blank=True, null=True, on_delete=models.SET_DEFAULT)