Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vectorized ways to write pandas dataframe rows to django model objects
Seeking guidance on vectorized solutions to create Django model objects from a pandas dataframe with one per row. I've looked at the following responses to other questionss https://stackoverflow.com/a/34431482/2193381 but don't want to hardcode the database connect string, etc as the answer suggests. The best I can come up with still uses .apply and looks like: def qux(row): return MyDjangoModel( foo=row['foo'], bar=row['bar'] ) data['obj'] = data.apply(bar, axis=1) MyDjangoModel.objects.bulk_create( list(data['obj']), ignore_conflicts=True ) Is there a better way? -
How would one implement a registration form that only accepts emails of a certain domain?
Say I want only people who have a Microsoft email account (email@microsoft.com) to be able to register. How would I implement that? I am using crispy-django-forms. <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today </legend> {{ form|crispy }} </fieldset> -
Creating a row from get_or_create
I have 2 models. A Topic and TopicPost model. If a user is creating a post, they will enter a tag that represent their post. That is what TopicPost is. It shows all the topics that are related to the post. We first check if the tag is in the Topic model, if not we create a new topic. We then get the id of the topic we just created and use it for TopicPost. Here's how my models look like: class Topic(models.Model): name = models.CharField(max_length=25) class TopicPost(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) I know I can do this to create a Topic obj = Topic.objects.get_or_create(name=tag) but is there way to combine this and create also a TopicPost with the post id and the topic id of the topic that was just created or retrieved? Something like a subquery or similar? -
How to collect extra information in DetailView (CBV) from URL path?
Using FBV it is easy to grab information from the url, but I have no clue how to do the same thing with CBV. with FBV: 1) urls.py: urlpatterns = [path('test/<int:test_number>/', views.testing, name='testing'),] 2) views.py: def testing(request, test_number): context = {'test_number': test_number} return render(request, 'testing.html', context) 3) template: 'testing.html' ... <p>Test #{{ test_number }}</p> ... and the test number, which is written in url is shown on html page. The question is, how can I do the same with CBV (DetailView in particular)? -
Multiple celery workers pointing to different brokers on same Django project
I want to run 2 celery workers on same Django project. This can easily be done using command line tool. But I want both the workers to have separate rabbitmq broker running on 2 separate hosts. Out of the 2 brokers one broker is local and resides on the same host. The other broker is a central server which pushes periodic messages to a queue. My question is how can I have such kind of configuration to be able to spawn 2 different workers, both pointing to 2 different brokers. Any help is appreciated. -
Stripe Payments Plan ID Error - No Such Plan
I'm using python 3.6 with django 10.5.1 and djstripe. I've added 5 new subscription plans to my 4 existing subscription plans. The new plans have been added exactly the same as the existing plans. The existing plans are tested and working. However, when I test any of the the new subscription plans I receive the following error. The following error is for the plan 30 days - $15: InvalidRequestError at /subscription/subscription/ Request req_eAeuagv4g4M2cd: No such plan: 30days_15 Here are my settings.py code for the particular plan: DJSTRIPE_PLANS["30days_15"] = { "stripe_plan_id": "30days_15", "title": _('30 Days'), "name": _('30 Day - USD$15'), .... } Here is my stripe product page for the new plan: I exported the plan details to a CSV and noticed that the plan ID's are different for the new plans I have added. Here is the screenshot of the CSV: Assuming that this is the cause of the error for the plan "30 Days - $15", how do I change the plan id in the stripe details from plan_EhxlviZWnK8r4r to 30days_15 so that this error is resolved? I've tried changing the planid in the settings.py code from plan_EhxlviZWnK8r4r to 30days_15, but this does not correct the issue. -
Django how to use array in template within a forloop
Im trying to use an array inside an html file within a loop views def noticia(request, noticia_id): noticia = get_object_or_404(Noticia, pk=noticia_id) user_like = False likes = [] dislikes = [] x = 0 for comentario in noticia.comentario_set.all().order_by('-pub_data'): likes.append(0) dislikes.append(0) for comentario in noticia.comentario_set.all(): for like in comentario.like_set.all(): if like.like: likes[x] += 1 elif like.dislike: dislikes[x] += 1 if like.user == request.user: user_like = True return render(request, 'Bola/Noticia.html', {'noticia': noticia, 'user_like': user_like, 'likes': likes, 'dislikes': dislikes}) Html {% for comentario in noticia.comentario_set.all|dictsortreversed:"pub_data"%} {% for like in comentario.like_set.all %} <p>{{ likes.forloopcounter0 }} {{ dislikes.forloopcounter0 }}</p> Any idea how to make this work? -
How to set Authorisation header(JWT)
I am working on JWT authorisation and I'm not able to figure out how to send the JWT as a request header for every request, so that I can use it to check if the user is authorised. Right now, I am generating the JWT immediately after login, and setting it as a cookie. I want to use header instead of cookie. How can I achieve this? I am using django 1.6, if it is relevant information. -
How would I make a Django form with confirming password backwards?
I’m using Django-registration’s one-step workflow. I’m adding a third form field, pw3, so that the user must confirm his/her password by typing it backwards. How would I go about that? -
ValueError. save() prohibited to prevent data loss due to unsaved related object 'filiere'
When validating my form I get an error that says: valueError, save () prohibited to prevent data. loss die to unsaved related object 'filiere' Here is an excerpt from the code: fil = Filiere(nom_filiere=filiere) niv = Niveau.objects.create(niveau=niveau, filiere=fil) I don't want to create or save fil(fil.save()) because "filiere" already exists in the database, I just want make the link between "niveau" and "filiere" -
Django nested serialization: how to catch null object?
I am requesting data through the django rest api from table1, which has a primary key pointed to table2. The primary key pointer is nullable. I have managed to have a nested serializer to be able to send the data of both tables in one get request. When the primary key is Null, I would like to send a default object instead of Null. Here is an example of a serializer file: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=False, read_only=True) if tracks is None: tracks = some default data to prevent Null class Meta: model = Album fields = ('album_name', 'artist', 'tracks') The reasoning is that the data from table2 will be used in the view and currently breaks the template if tracks is null (in this example). Having default values would fix that issue. It is my first time programming in django and also the first time implementing an api. Any help would be greatly appreciated! -
Django+Ajax: Updating content without refesh
I am currently trying to develop a facebook clone for a uni project. I want to make a "like" button (here called "Give lasanha") and make it update without refreshing the page. So far I have been successfull in doing so, but it only updates my first post, it doesn't work for any of the other posts. [Image of how it looks: https://i.gyazo.com/0e239fc05b401e5d1d96b6a1e08063e1.png ] I have already tried a bunch of things, but nothing has led me to a resolution, so that is why I am writing here. So here are my templates: home.html (where we call the ajax script) {% for post in posts %} {% if post.content is None %} <script> var x = '{{ post.id }}'; $(document).ready(function (event) { var x = '#lasanha'+'{{ post.id }}' $(document).on('click', '#lasanha'+'{{ post.id }}', function (event) { console.log( "e."+x); event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "give_lasanha" %}', data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(response){ $('#lasanha_section').html(response['form']) }, }) }) }) </script> {% endif %} {% endfor %} <div id="lasanha_section" class="form-group"> {% include 'space/lasanha_section.html' %} </div> lasanha_section.html {{post.lasanhas.count}} Lasanha{{post.lasanhas.count|pluralize}} <form action="{% url 'give_lasanha' %}" method="submit"> <p id="er" value="{{post.id}}"></p> {% csrf_token %} {% if is_liked %} … -
How can I import data for my Django choices parameter?
I'm creating a model that has a character field, called 'country'. I scraped the web and created a tuple (in another python file) with the countries that I would like the user to have the option of selecting. The tuple in the other file is exactly in the form that Django requires to, such as (("BR", "Brazil"), ("US", "The United States")). Now, how can I import this tuple of countries in the 'choices' parameter (for example myfile.COUNTRIES)? I simply don't know how to do it. How can I import this data in my Django project? Are there any best practices or recommendations for production? class Profile(models.Model): COUNTRIES = ??? user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") countries = models.CharField(max_length=100, choices=COUNTRIES, blank=False, null=True) -
Django: how to create a content_type Object for a Permission?
I'm trying to create in the backend Groups and Permissions. Now I'm trying to understand what is the content_type argument and how to use it when creating a Permission. Documentation for Permission model says: content_type¶ Required. A reference to the django_content_type database table, which contains a record for each installed model. How can I get this content_type? Where should I look for it? According to this other question, one can do this: from django.contrib.auth.models import User, Group, Permission from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get(app_label='app_name', model='model_name') permission = Permission.objects.create(codename='can_create_hr', name='Can create HR', content_type=content_type) # creating permissions group = Group.objects.get(name='HR') group.permissions.add(permission) But again, what is app_label='app_name', model='model_name' inside: content_type = ContentType.objects.get(app_label='app_name', model='model_name')? -
Inline formset with 3 foreign keys?
I'm trying to make a form that displays a poll. It'll be the question, the choices, and the tags. Both choices and tags have a relationship with question. I know if I had just the choices I could use an inline formset, however, what can I do to display all 3 in one form (question, choices, and tags)? class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class Tag(models.Model): topic= models.ForeignKey(Topic, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) How do I make it so I can have a form with the status, two choices, and a tags section where whatever the user submits it will all be linked to the single question? -
django rest framwork and websockets
I do the implementation of web sockets in DRF, here is a video on which it. https://www.youtube.com/watch?v=HzC_pUhoW0I I did everything the same, and it seems to work for me, but I do not understand how the client will listen to the server. The client must listen to the server on the port, and in certain events the server must notify the client. How can a client listen to the port by socket? here is my code # binding class AutoSerializer(serializers.ModelSerializer): class Meta: model = ClientCallTaxi fields = ['id', 'user_id'] read_only_fields = ['slug', ] class AutoBinding(bindings.ResourceBinding): model = ClientCallTaxi stream = 'auto' serializer_class = AutoSerializer queryset = ClientCallTaxi.objects.all() # routing channel_routing = [ route_class(ExampleConsumer), route('auto', AutoBinding.consumer) ] -
how to fix "MultiValueDictKeyError " in django 2.1.3'
i am trying to retrieve the 'name' value from : <input type="text" name="fullname" value=""> and display it on another page, but i keep getting MultiValueDictKeyError when i call request.GET["fullname"], but if i use request.POST.get('fullname', False) it returns None. views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request): return HttpResponse('Hello World') def index(request): fn= request.GET["fullname"] crs= request.GET["course"] st='your welcome to first_app/index.html' return render(request,'first_app/index.html',{'st':st,'fn':fn,'crs':crs}) def courses(request): string= 'my name is ibi' return render(request,'first_app/courses.html',{'st':string}) urls.py from django.urls import path from first_app import views urlpatterns =[ path('',views.index, name='index'), path('courses/', views.courses, name='courses'), ] Traceback -
Apply django queries in template
Can I write Django queries in the HTML page and then pass it to view to use it as Django raw query? or tell me how can I update my table data according to dropbox selected value ''' $(document).on('Change','#sub_select',function(e){ e.preventDefault(); $.ajax({ type:"POST", url:"{% url 'dashboard_app:group_page' %}", data:{ sub_team_val:$("#sub_select").val(), csrfmiddlewaretoken:$('Input[name=csrfmiddlewaretoken]').val() }, success:function(){ console.log("Values Updates!") } }) }) ''' I had tried this but no use kindly give me some good tutorials or documentation -
Django template html file can't find WebGL Build and TemplateData folders
To practise my Django skills, I want to try to host a game on my website. The game was made in Unity and packaged using WebGL. I used the index.html created by WebGL as a Django template and created the URL path and view in the relevant locations. WebGL creates two folders, Build and TemplateData that are referenced in index.html. I have tried putting these folders in with the html templates, and on every level in my Django folder structure. The outcome is the same wherever I put the folders. The GET command is sent but a "Not Found: /TemplateData/filename...." is shown for a few files Does anyone know how to see where the GET command is looking, or just where the folders should go? Thanks, Sophie -
How to display the search result score as percentage in the frontend?
I've recently set up Elasticsearch on my Django project using Django-haystack and I want to display the search results' scores as percentages in my templates (html). So I am wondering if there's a way to achieve this? A quick example of the final result would be this: <div> {% if page_obj.object_list %} <ol class="row top20"> {% for result in page_obj.object_list %} <div class="showcase col-sm-6 col-md-4"> <!-- Matching score to be displayed in the h5 below --> <h5>{{result.object.matching_score}}</h5> <a href="{{ result.object.get_absolute_url }}"> <h3>{{result.object.title}}</h3> <img src="{{ result.object.image }}" class="img-responsive"> </a> </div> {% endfor %} </ol> {% endif %} </div> I'm still new to this but maybe an If - Else statement, the Elasticsearch default _score value or even some Javascript might do the job. I'm not sure, so what do you think I should do? -
how to get the value of an attribute (pk) using QuerySet
I tring to get the value of the primary attribute (pk). How to do it ? Equivalence for this SELECT id FROM User WHERE username="Fokoa" -
Error: Page not found (404) django createview with inline formset
Django 2.1 Python 3.6 I am trying to use Django's CreateView to create and save three forms. Then I want to be redirected back to the parent model's detailview. However, when I submit the form, I am being redirected to the recipes/, instead of recipes/test. I get a page not found (404) error because recipes/ does not exist. There is no traceback to help me figure out what is going on. Can someoneone please show me what I am doing wrong in my code? models.py from django.db import models from django.utils.text import slugify from django.urls import reverse class Recipe(models.Model): title = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(default='') def save(self, *args, **kwargs): self.slug = (slugify(self.title)) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('recipes:RecipeDetail', kwargs = {'slug': self.slug}) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete = models.CASCADE) description = models.CharField(max_length=255) class Instruction(models.Model): recipe = models.ForeignKey(Recipe, on_delete = models.CASCADE) number = models.PositiveSmallIntegerField() description = models.TextField() views.py from django.http import HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.views.generic import CreateView, DetailView from .forms import IngredientFormSet, InstructionFormSet, RecipeForm from .models import Recipe class RecipeCreateView(CreateView): model = Recipe form_class = RecipeForm template_name = 'recipes/recipe_add.html' def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of … -
The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
I can not filter the same slug values. The problem is that I need to have two identical slug kind and I don't understand how fix it. I have two product with slug (kind) > 'silikonovyj-chehol' and I try filtering it, but have this The QuerySet value for an exact lookup must be limited to one result using slicing. views.py def product_list(request, category=None, subcategory=None, kind=None): if category: category = Category.objects.get(slug=category) categories = Category.objects.all() subcategories = Subcategory.objects.filter(category=category) products = Product.objects.filter(category=category, available=True) kinds = None if subcategory: subcategory = Subcategory.objects.get(slug=subcategory) kinds = Kind.objects.filter(kind=subcategory) products = Product.objects.filter(category=category, subcategory=subcategory, available=True) if kind: kind = Kind.objects.filter(slug=kind) # ERROR IT'S HERE products = Product.objects.filter(category=category, subcategory=subcategory, kind=kind, available=True) context = { 'categories':categories, 'category':category, 'subcategories':subcategories, 'subcategory':subcategory, 'products':products, 'kinds':kinds, } return render(request, 'shop/product/product_list.html', context) else: categories = Category.objects.all() products = Product.objects.filter(available=True) context = {'categories':categories, 'products':products} return render(request, 'shop/product/product_list.html', context) product_list.html {% if subcategory %} {% for kind in kinds %} <a href="{% url 'shop:lst_by_knds' category.slug subcategory.slug kind.slug %}">{{ kind.name }}</a> {% endfor %} {% endif %} Below {% for product in products %} <div> <a href="{% url 'shop:product_show' product.slug product.id %}">{{ product.name }}</a> <br> {{ product.price }} &#8381; <a href="{% url 'cart:cart_create' product.id %}"><button>Добавить в корзину</button></a> </div> {% endfor … -
Exclude fields for Django model, only on creation
I am building a notification system for a company, where admin users can create Projects and add users to them. The Project model has 9 attributes but I only want to show 3 or 4 fields when a Project is created, but show them all when an existing Project is updated. This change will only need to be reflected on the Django admin site, so I have extended the ProjectAdmin with my own ProjectForm, where I extend the init method to check if it is a new instance and if so remove certain fields. # models.py class Project(models.Model): project_number = models.IntegerField() name = models.CharField(max_length=100) permit = models.CharField(max_length=100, blank=True, default='') is_active = models.BooleanField(default=True) users = models.ManyToManyField(CustomUser, blank=True, related_name='project_users') # add a default levels = models.ManyToManyField('Level', blank=True, related_name='project_levels') total_contract_hours = models.IntegerField(default=0, blank=True, verbose_name='Total Design Hours') hours_used = models.IntegerField(default=0, blank=True, verbose_name='Total Design Hours Used') notes = models.ManyToManyField('notes.ProjectNote', related_name='core_project_notes', blank=True) history = HistoricalRecords() def __str__(self): ret_str = "{} {}".format(self.project_number, self.name) if self.permit: ret_str += " | Permit: {}".format(self.permit) return ret_str # admin.py class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) attrs = {'class': 'form-control', 'required': True} if self.instance and self.instance.pk is None: # creating project exclude = ['is_active', 'users', 'levels', 'hours_used', 'notes'] for … -
Error in creating new instance of a model in django admin.py
I have a problem with admin.py in users app. I've tried to create a new user in admin panel of django but I got this error: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin. But the field username doesn't exists actually. and I've created custom user manager and set REQUIRED_FIELDS = "email" in model. As you can see I've added add_fieldsets down below. the error gone but the admin panel still requires a username instead of email. UserAdmin: class UserAdmin(UserBaseAdmin): list_display = ["email", "first_name", "last_name", "is_active"] list_filter = ["is_active", "is_admin", "is_staff"] search_fields = ["first_name", "last_name", "email"] ordering = ["email"] add_fieldsets = ( (None, {"fields": ("first_name", "last_name", "email", "password")}), ("Permissions", {"fields": ("is_admin", "is_staff", "is_active")}) ) fieldsets = ( (None, {"fields": ("first_name", "last_name", "email", "password")}), ("Permissions", {"fields": ("is_admin", "is_staff", "is_active")}) ) filter_horizontal = [] admin.site.register(User, UserAdmin) Model: class User(AbstractBaseUser, UserTimeStamp): first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) email = models.EmailField(unique=True, blank=False, null=False) is_admin = models.BooleanField(default=False, blank=False, null=False) is_staff = models.BooleanField(default=False, blank=False, null=False) is_active = models.BooleanField(default=True, blank=False, null=False) objects = UserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, perm_label): return True User manager: class UserManager(BaseUserManager): def get_queryset(self, *args, **kwargs): return UserQueryset(self.model, using=self._db) …