Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration error-Manager object has no attribute 'name'- Error on Migration
I was trying implement staff management project in DJango, I created custom user and added that one to one field in my staff model. I created manager class for Staff. But when I am trying to migrate my model it says manager object has no attribute 'name'. If I add a field name in manager this error will be disappeared. Can any one please help me why this error? class CustomModelManager(models.Manager): """ customised foam of model manager """ def __init__(self): # this can be overriden on child class self.ARG={ 'status':int, 'app_label':str, 'model_name':str, 'content_type_id':int, 'detailed':bool, 'pk':int, 'codename':str, 'name':str, 'id':int } # if any user argument having another label that model relation # will replace the smame with replacement values""" self.REPLACING_VALUES={ 'model_name':'content_type__model_name', 'content_type_id':'content_type__id', 'app_name':'content_type__app_label' , 'app_label':'content_type__app_label' } self.DEFAULT_PARAMETERS={ 'content_type__status__active':True } self.VIEW_PARAMETERS_LIST=[ ] from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from branch.models import Branch from django.contrib.auth.models import Group from common.managers.custom_manager import CustomModelManager from django.contrib.auth.models import Permission class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email … -
Keeping annotated rank when filtering Django
I have a filtered Queryset where I have annotated the rank of each object according to a specific order. When I then perform other filters like changing the order by the rank stays the same. The problem comes when perfoming a new .filter() I have a search function on the page that filters the results after the title of the objects. But when I do this the annotated rank value changes depending on how many results are in the new query instead of keeping its original value. To illustrate: This is my original query: choices_filter = Choice.objects.filter(tournament=pk).annotate (rank=RawSQL("RANK() OVER(ORDER BY winrate DESC, pickrate DESC, times_played)", [])) This returns a queryset like this: Rank Title Winrate 1...........Apple...........55% 2...........Pear............47% 3...........Banana..........44% 4...........Orange..........35% 5...........Watermelon......31% If I perform a .order_by('title') I get the expected result of: Rank Title Winrate 1...........Apple...........55% 3...........Banana..........44% 4...........Orange..........35% 2...........Pear............47% 5...........Watermelon......31% But if I instead perform a .filter(title__icontains='an') I get this: Rank Title Winrate 1...........Banana..........44% 2...........Orange..........35% Instead of the desired: Rank Title Winrate 3...........Banana..........44% 4...........Orange..........35% I am still not experienced enough with Django and python (and databases) to navigate through this on my own. It took me a while to figure out how to annotate the rank and have it working with … -
EveryTime the runserver Reload why this warning Shows up in my Terminal can anyone help please
Everytime i make changes in the code when runserver is automatically reloaded it shows the below warning. and its in all my projects. Please if anyone can suggest something it would be a great help Thanks Im using postgres as database /Users/chip/Documents/Git/test_project/cart/api/v1/serializers.py changed, reloading. Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/Users/chip/Documents/Git/apis_gifola/venv/lib/python3.8/site-packages/IPython/core/history.py", line 780, in writeout_cache self._writeout_input_cache(conn) File "/Users/chip/Documents/Git/apis_gifola/venv/lib/python3.8/site-packages/IPython/core/history.py", line 763, in _writeout_input_cache conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 123145399545856 and this is thread id 4726091200. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 28, 2020 - 05:53:02 Django version 2.2.3, using settings 'test_project.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. -
Django: within html reference foreign key from user
models.py: class Banking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) available_credits = models.PositiveIntegerField() base.html: {{ user.banking.available_credits }} Can I use the user object to reference the available_credits in the banking table? I'm using this base.html as a template which all other templates extend and ideally don't want to pass the specific instance in. I was hoping there was a way to reference it in a similar way to {{ user.username }} -
Django: Why does a migration pass a None value to a custom field in which I haven't set null=True?
This is a custom field I defined to represent a time duration because I wanted a field that I could create with a single float type (seconds) and have that same value when I access the object's attribute, but that I could render in my HTML as a string with the format hh:mm:ss. I tried with DurationField() but this doesn't work for me because it's rendered as hh:mm:ss.ffff, and I had to do too many things to get rid of the decimals. I defined this field following the example in the documentation. There were some things I didn't understand completely, but I managed to make it work initially when I wasn't passing any arguments to the field (like blank=True) and when I was only passing a constant value to this model attribute in my view, after save(commit=False) and before save(). I did this first because I hadn't written the code that calculates its value. Note that the value for this field is not to be entered by the user in a form, this is the result of a calculation that's based on user-entered data. The thing is now that, to make this calculation, I need the model instance to be … -
Add a field to the Django admin for a custom user model
I have a custom user model: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_happy = models.BooleanField(default=False) I'm referencing it within AUTH_USER_MODEL. And I've generated an admin for it based on the UserAdmin from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): pass But the is_happy field doesn't appear in the user admin page. How/where do I tell this UserAdmin about additional fields that I'd like it to display? Further details Django v3.1.3 Python v3.8.5 -
How to return raw query result in django
How to return the raw query result in django. Following is my code join = Books.objects.raw({'$lookup': { 'from': 'titles', 'localField': 'title', 'foreignField': 'title', 'as': 'join_array' }}) return HttpResponse(join) -
Django Bootstrap Accordion needs double click to expand
When I click the accordion the first time nothing happens. When I click it a second time, it opens and then closes immediately! It's like the second click sends both. Here's my template: {% for category in challenges_by_category_list %} {% if category %} <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high </div> </div> {% endfor %} </div> {% endif %} {% endfor %} I wondered whether it's something to do with including bootstrap twice? But here's my base.html includes: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> I've also installed crispy_forms which uses bootstrap, I don't know if that's relevant. -
How do you select a random element out of list, in django template?
I have a list of links generated in my views, now i want to redirect my page to a random link in this list. Is there a way to select a random element out of the list in the django template? I don't want to redirect the view to another view where the generation happens then redirection etc because every press of the button will lead to generation...instead simply selecting a random element out of the list so it's very fast.. Couldn't hack it via google template <div class="container-fluid center"> <a class="btn waves-effect waves-light" href={{ random_link }}>Redirect me to a cute pic <i class="large material-icons left">favorite</i> <i class="large material-icons right">favorite_border</i> </a> </div> views.py reddit = praw.Reddit(client_id='L685-1uBBrLbKQ', client_secret='_Fk5nW1L2h3VRR6BVnkusMh43QQ_gg', user_agent='Shivam Anand') top_natureismetal = reddit.subreddit('natureismetal').top(limit=100) # generator only generated once for loop run nature_links = [] for post in top_natureismetal: nature_links.append(post.url) import random random_link = random.choice(nature_links) #the part i want html to do... -
How to get data of Post.user not the logged in User
I am currently working on a blog project for learning purposes, I am trying to get the total number of posts made by a specific user. In my model I have set the User who makes a Post as Author. In the Post detail page I am trying to show the total number of Posts made by this specific author but I am getting the data of the logged in User who is viewing the page. The reason for this is using self in the get context data but I am not sure how to fix it so I need some explanation on how to amend this error in code. Here is the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) num_post = Post.objects.filter(author=self.request.user).count()#<--- No. of Posts made by an author context["num_post"] = num_post #<--- No. of Posts made by a user return context My question: How to show the data of the post detail author not the logged in user Thank you -
how to move images from one table to another table in Django
I am trying to build a website which shows one image at a time in frontend from the database and move the displayed image from the existing table to another table. my website is in Django -
How to pass active user to Django ModelForms
In my form, I must filter the "tenant" choice field so that it displays only tenants associated to the active user's organization. So I'm simply passing an extra argument to the form constructor. This works as expected when I load (GET) the form. But when I submit (POST) the form, I keep getting the following error: AttributeError: 'NoneType' object has no attribute 'organization_profile' Any idea what's provoking this? Views.py def create_booking(request): if request.method == "POST": form = BookingCreateForm(data=request.POST) if form.is_valid(): data = form.cleaned_data booking = Booking.objects.create( status=data['status'], tenant = data['tenant'], apartment = data['apartment'], check_in = data['check_in'], check_out = data['check_out'], rent = data['rent'], ) booking.save() return redirect('dashboard:dashboard') else: form = BookingCreateForm(user=request.user) return render(request, 'accounts/booking_form.html', {'form': form}) Forms.py class BookingCreateForm(forms.ModelForm): class Meta(): model = Booking fields = '__all__' def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(BookingCreateForm, self).__init__(*args, **kwargs) organization = self.user.organization_profile self.fields['tenant'] = forms.ChoiceField(choices=[ (tenant.id, tenant.name)) for tenant in TenantProfile.objects.filter(organization=organization) ]) -
Is it possible to add values to context into a for loop?
I have a for loop to iterate a list. In every iteration i have a different value, and i want to add this value to my context. I'm trying using context.update, but every time this returns an empty context. def get_context_data(self, **kwargs): context = super(Board_dets_view, self).get_context_data(**kwargs) id_board = self.object.id context['column_list'] = Column.object.filter(board_id=id_board) clist = Column.object.values_list('id', flat=True).filter(board_id=id_board) cCard = Card.object print(clist) for i in range(0, clist.count()): print('i=%s',i) cCard = Card.object.filter(column_id = clist[i]) print('cCard=%s',cCard) context.update({'card_list': cCard}) print(context) return context cCard returns correct data. The only thing I need is to store what come from cCard to context['card_list'], but evert attempt i made, was an empty result. -
What is the best method to change an img src using javascript with django?
I can get the img src to change using onclick and a hard path without django template tags. It's my impression this is bad practice. How can I get "{% static 'indv_proj\Metron Pres\Slide3.JPG' %}" format injected/changed into the html img src everytime I click the image? JavaScript: $(document).ready(function(){ $("#indv-ppt").click(function(){ // Change src attribute of image $(this).attr("src", "{% static 'indv_proj\Metron Pres\Slide3.JPG' %}"); }); }); HTML: <div class="ppt-slides"> <img id= indv-ppt src="{% static 'indv_proj\Metron Pres\Slide1.JPG' %}" alt="Error"> </div> -
How do I get django "Data too long for column '<column>' at row" errors to print the actual value?
I have a Django application. Sometimes in production I get an error when uploading data that one of the values is too long. It would be very helpful for debugging if I could see which value was the one that went over the limit. Can I configure this somehow? I'm using MySQL. It would also be nice if I could enable/disable this on a per-model or column basis so that I don't leak user data to error logs. -
Does Django have a Migration History separate from the django_migrations DB table?
I'm in the process of changing an app name in Django and running into this InconsistentMigrationHistory exception. The first thing I did, described in this SO answer, was change the name of the app directory and all references to the app. I made some SQL statements to rename account to authentication in the django_content_type table and the django_migrations table. After doing these things, I try python manage.py makemigrations and get the InconsistentMigrationHistory exception shown below. Traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/db/migrations/loader.py", line 306, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency authentication.0001_initial on database 'default'. Here, account is the old app name and authentication is the new app name. With this exception, my first idea was that there must be a migrations file in account that uses the authentication.0001_initial migration as a … -
I have Syntax Error When I edit django messages
I want to edit django error mesages like class error mesages.But when I add if controller in HTML documents, I meet syntax error Note: (just when I use if controller I have syntax error) Views content; from django.contrib import messages if request.method=="POST": form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("passowrd") newUser = User(username = username) newUser.set_password(password) newUser.save() login(request,newUser) messages.success(request,"Kayıt Başarılı") messages.warning(request,"DANGER") return redirect(index) context ={ "form":form } return render(request,"register.html",context) Note: I added 2 messages for try when I don't add if controller its working Layout content; {% if messages %} {% for message in messages %} {% if message.tags=="warning"%} <div class="alert alert-danger">{{ message }}</div> {% else %} <div class="alert alert-{{ message.tags }}">{{ message }}</div> {% endif %} {% endfor %} {% endif %} Error output: Could not parse the remainder: '=="warning"' from 'message.tags=="warning"' -
Gunicorn and django - Multiprocessing issue
I am running a django instance through Gunicorn. in this Django project, I have a view that starts a multiprocessing task in background that is fetching some data every x milliseconds, and stops after x seconds if no new request have been received. Using runserver, I have no problem, my multiprocessing continues to work as expected and my view fetch the data from this multiprocessing without any problem. but when I switch to Gunicorn, it seems that when I request my view, it doesn't detect that the process is already running and tries to start a new one in parallel, returning wrong values. Do you have any clues where the problem could come from? no. of workers? no. of threads? thank you, -
Django auth permissions
How can I make the Django model available by default, for users (Staff = True), to make available CRUD actions in the admin panel? I wrote some code based on the Django authentication system: from django.db import models from django.contrib.auth.models import AbstractUser from .manager import CustomUserManager from django.urls import reverse from pytils.translit import slugify class CustomUser(AbstractUser): username = None # removing username field email = models.EmailField(unique=True) is_staff = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class _TimedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta(object): abstract = True class Post(_TimedModel): title = models.CharField(max_length=100) body = models.TextField() slug = models.SlugField(null=False, unique=True) author = models.ForeignKey('blog.CustomUser', on_delete=models.CASCADE, related_name="post") objects = models.Manager() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta(object): verbose_name = 'Post' verbose_name_plural = 'Post' def str(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) Then I created a user registration, added the Post model to the admin panel. This is the admin.py file from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser, Post class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( … -
Broken images in Django
I have a problem with my images, which started when I changed a part of my code in view.p (API) from: class PostListView(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer to: @api_view(['GET']) def PostListView(request, *args, **kwargs): queryset = Post.objects.all() username = request.GET.get('username') if username != None: queryset = queryset.filter(author__username__iexact=username) serializer = PostSerializer(queryset, many=True) return Response(serializer.data, status=200) I did this because I wanted to pass "username" into it and I dont know how to do that using APIView, so i used this, but then my images are broken and i notice with the APIView, the images url starts from "127.0.0.1/8000/..." but with this new view the url is "localhost/...." which i think is the problem. How do i go about it please -
how to run python/djanjo shell as a script
In a tutorial on django we create a simple table run migrations and then go into a shell with the command: python manage.py shell from there, in the shell we run the following: from flights.models import Flight f = Flight(origin="New York", destination="london", duration=415) f.save() I'm trying to figure out how to run these commands from a py file so I created test.py: from django.apps import apps from flights.models import Flight apps.get_model('flights', 'Flight') f=Flight(origin="New York",destination="London", duration=415) f.save() but get the error Models aren't loaded. How to resolve? -
why the sentence if form.is_valid(): never pass. i have tried many thing, changing the python version for example and always is the same
When I run the code, it never pass the sentence if form.is_valid(): I have changed the version of python, but it is still the same views.py def login_page(request): form = Loginform(request.POST or None) context = { "form": form } print("User logged in") if form.is_valid(): # print("form is validated") print(form.cleaned_data) # print("form cleaned data") username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") forms.py from django import forms class Loginform(forms.Form): username = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) view.html <div class='container'> <div class='row'> <div class='col'> <p>{{ content }}</p> <div class='col-sm-6 col-12'> <form method='POST'> {% csrf_token %} {{ form }} <buttom type='submit' class='btn btn-default'>Submit</buttom> </form> </div> </div> </div> </div> # The form looks well, same the submit. I do not see the error please help me to undertand what happens with this sentence of form_is_valid -
How can I save a model instance that references itself in django?
I have the following code: from django.db import models class MyModel(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='parent') In some cases, I would like the model to be its own parent. This may be done by saving the model and then assigning the parent, but I need this to be done before saving, since there is some code that depends on post_save signal and that needs the model's parent info. -
Django 3.1 How to solve template mapping in settings.py
As you can see in the below Django code of settings.py I'm trying to map the templates with it, but I can't be able to that. When I am running the server it is showing the error. Terminal: It is showing look like.. IndentationError: unexpected indent. -
Django Rest Framework - returning raw bytes image from view
I have a view that returns an image (I'm aware that it might be a bad practice. But it's necessary in my case). Using normal Django HttpResponse I just return: # img is bytes response = HttpResponse(img, content_type="image/jpeg") response['Access-Control-Allow-Origin'] = '*' return response I want to use DRF since most of my views use it as well. I tried to just replace HttpResponse with Response but it crashed with 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Is there another way to do that? Should I even use DRF for returning this kind of data or should I stick to raw Django HttpResponse? One last thing, I have the same problem with other buffer types. E.g HttpResponse(content_type='text/csv') and response = HttpResponse(content=excel, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'inline; filename=filename.xlsx' return response Is there some general solution for these cases?