Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ctypes init fails using local app engine, django and virtualenv with python 2.7
I'm facing an issue with the init of ctypes if int(_os.uname()[2].split('.')[0]) < 8: ValueError: invalid literal for int() with base 10: ' My app is written in Python 2.7 and based on Django, running locally using App Engine SDK and virtualenv. It's been in production for a long time and is running successfully locally on other machines. Meaning this is a local issue for my machine. I'm on Mac OSX 10.15.3 Catalina. The issues arises when I'm loading any page of my app, after starting the app engine local development server. The App Engine server is starting successfully (I can access the app engine admin webpag), but the above exception is being raised (see callstack below), as it seems os.uname() is returning an invalid value. When running os.uname() myself, the result seems legit. Both when the virtualenv is activated or using the os/pyenv python interpeter. Python 2.7.15 (default, Mar 15 2020, 22:00:51) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.uname()[2].split('.')[0] '19' Solutions I've tried: Calling os.uname() inside and outside of the virtualenv, it works correctly. Creating a virtualenv using the system Python 2.7.17 installation Creating … -
DRF reverse cannot find view name
I am working of django rest framework api_root. It cannot find view even though I name it. # board/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from .views import BoardList, BoardDetail, api_root app_name = 'board' urlpatterns = [ path('boards/', BoardList.as_view(), name='board-list'), # board-list path('boards/<int:pk>', BoardDetail.as_view(), name='board-detail'), path('', api_root), ] urlpatterns = format_suffix_patterns(urlpatterns) # board/views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics, permissions, serializers from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from .models import Board from .serializers import BoardSerializer from .permissions import IsAuthorOrReadOnly @api_view(['GET']) def api_root(request, format=None): return Response({ 'boards': reverse('board-list', request=request, format=format) # board-list }) class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(author=self.request.user) It throws error, Reverse for 'board-list' not found. 'board-list' is not a valid view function or pattern name. Why it cannot find view name? -
Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'
I am new to Django and I am trying to implement custom user authentication for my website. When I try to create a new user for the signup view, I get the error 'Manager isn't available; 'auth.User' has been swapped for 'users.CustomUser'. Creation of new users from Admin page works fine. I googled the error, but none of the advised solution is working for me. See the code below. The django app I created to manage users is "users". models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birth_date = models.DateField(null=True, blank=True) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, help_text='Required`.') last_name = forms.CharField(max_length=30, help_text='Required.') email = forms.EmailField(max_length=254, help_text='Required. Please input a valid email address.') birth_date = forms.DateField() class meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email', 'birth_date',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields views.py: from .forms import CustomUserCreationForm from django.urls import reverse_lazy from django.views.generic import CreateView class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = … -
Django. If-statement in template doesnt register when variable changes from False to True
When someone likes a post I want the button to change to 'dislike' instead of 'like'. The action to remove the like is working, but the button doesn't change. In template: <form action="{%url 'like_post' %}" method='post'> {% csrf_token %} {% if is_liked %} <button type='submit' name="post_id" value = "{{ post.id }}" class="btn btn-danger">Dislike</button> {% else %} <button type='submit' name="post_id" value = "{{ post.id }}" class="btn btn-primary">Like</button> {% endif %} In views: def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user.id) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) -
How can I load a fixture so that it appends data to existing records in a model?
I want to load a fixture into my model, but have it add additional rows rather than overwrite the existing ones. Per this answer, I have manually set "pk": null, however when I load this data it still overwrites the existing data in the model. [ { "model": "myapp.mymodel", "pk": null, "fields": { "name": "foo", } }, { "model": "myapp.mymodel", "pk": null, "fields": { "name": "bar", } } ] How can I load a fixture so that it appends data to existing records in a model? -
Linking Django - Postgresql with Standalone Docker
Following the thread of this question, I am trying to run Django in one container, Postgres in another container, and connect them "manually" via user-defined networks. This is my network after launching both containers: [ { "Name": "django-network", "Id": "bbae9d656ea9ccc56c2c0f4db310d53fa135275358b16bc08636cf0c1a56127f", "Created": "2020-03-15T17:21:48.405473202Z", ... "Containers": { "79c7a66a5f4a892486d3c1d3089ff5850e2753af66cc694798015f80021297f3": { "Name": "postgres-10", "EndpointID": "d5fb80edfdf19678890da858e25e8bafd3e56113f82a5c1e39de5ca16f1caf5a", "MacAddress": "02:42:ac:12:00:02", "IPv4Address": "172.18.0.2/16", "IPv6Address": "" }, "8873f054b23bb888b91deb64c819c1bf370db6ddc7b9f638ee60d850ee082da6": { "Name": "betcomm-django", "EndpointID": "e60640ec4dfbc1dd86b3464260ed73446846b8dd33b6e4b173befe26d5ee0738", "MacAddress": "02:42:ac:12:00:03", "IPv4Address": "172.18.0.3/16", "IPv6Address": "" } },... ] And this is the error on the Django container: root@8873f054b23b:/app/backend# python manage.py runserver 0.0.0.0:8000 Running Docker locally, setting env variables... DB: betcomm-dev User: postgres Pass: postgres Host: docker-db Port: 5432 Running Docker locally, setting env variables... DB: betcomm-dev User: postgres Pass: postgres Host: docker-db Port: 5432 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection ... ... connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "docker-db" (172.18.0.2) and accepting TCP/IP connections on port 5432? But docker-db on that IP is indeed connected. These are the … -
Python / Django: Dynamically Changing Function Based on Instance
I have a class where each instance needs to call a separately defined method depending on the configuration. So imagine: class MyClass(models.Model): ... a = MyClass(someData) b.fireFunction() <-- needs to fire some specific function b = MyClass(someData2) b.fireFunction() <-- needs to fire a different function The best example I can think of is a consumables system in a game– they all inherit from some base consumable class, but using the consumable item performs an entirely different action for each item. I know with packages like Celery I can register a set of tasks with a decorator. What's the way to accomplish this? Here is what I'm thinking: Register a set of actions with some kind of ConsumableActions model. For celery these do not appear to be saved in the db. What's a good way to do this? Somehow call that saved action. Perhaps something like this? import foo method_to_call = getattr(foo, 'bar') result = method_to_call() -
model usage history with class diagram
I am modeling a web application for managing depot's materials my question is divided into 02 parts: part 1: I did a 1st modeling of 'use of articles' by the employees. class diagram the article type can be: gloves, hat, boots, etc ... each article has multiple units.(gloves: 50 units, hat: 100units .....) _ an employee can use several articles, but only one unit at a time,, for example: an employee X use (1 gloves, 1 hat, 1 boot, etc.) _ a unit can be used by a single employee. am i in the right way? if not, how can i improve it? part 2: I want to have the history of use of materials by employees. _ an employee can use several articles for a given period (date_deb, date_end) _ an article can be used by a single employee for a given period (date_deb, date_end) -if I ask these two questions: for such an employee, what items have he used over time (usage history)? for such a unit, who are the employees that used this unit? for example the use of unit1: [unit1, (employee1,, date_deb, date_end), (employee2, date_deb, date_end), (), ........] how to do the modeling to answer these … -
How to update two forms in a single view where one form is userform(djangoform) and one is modelform (with model being userextension model)?
This is the user function model. this is the edit profile view where I need to use both forms to save in the database from html template These are the two forms which I need to use in one single view This is the html template on which I need to show the contact number and be able to edit it I apologize if I am not able to present my question properly. I want to be able to show and edit the contact number on the same page as other details like username, last name, and first name. I have tried different methods like using query to call from database and save both form and query on the same function but it was not updating the contact number. Can this be done or do I have to take some different approach if this can be done, please let me know? If I missed some details please let me know in case if there are question as this is my first time asking here at stack -
Visual Studio 2017/Django(v1.11.29) Trouble Installing Python Packages into ENV
I am trying to install(Python 3.6.6) packages into a Django Project env with Visual Studio 2017. I have no trouble installing these packages when the project has been newly initiated. The trouble begins when I try and install packages within a clone from the master in GitHub; I then get errors and the packages are not installed. I have tried cmd into the env, but they still do not want to install: ----- Installing 'django-phone-field==1.8.0' ----- Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\__main__.py", line 16, in <module> from pip._internal import main as _main # noqa File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_internal\__init__.py", line 20, in <module> from pip._vendor.urllib3.exceptions import DependencyWarning File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\__init__.py", line 8, in <module> from .connectionpool import ( File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 11, in <module> from .exceptions import ( File "C:\Users\sean\Source\Repos\scheduler_forms5\scheduler_forms\env\lib\site-packages\pip\_vendor\urllib3\exceptions.py", line 2, in <module> from .packages.six.moves.http_client import ( ModuleNotFoundError: No module named 'pip._vendor.urllib3.packages' ----- Failed to install 'django-phone-field==1.8.0' ----- Any suggestions would be appreciated. -
.values() function breaks datetime field in django queryset
I am trying to import some data from my DDBB in a django3 project. I have been able to retrieve properly some instances of my Order objects but it looks like in some cases the provided timestamps get a delay of whole hours. When I query DateTimeField like this in my view: orders_list = Order.objects.filter(client_id=client_idf) And after that, y pass this as context to my template I get the correct date which is 01-march-2009 00:00. When I query like this: orders_list = Order.objects.filter(client_id=client_idf).values() data = pandas.DataFrame(orders_list) And I ask for the "datetime" it displays 28-February-2009 at 23:00. -
cannot get menu url from database Django
I have one big problem. I created my own menu navigation for Django. simple models which contain menu name, URL,image, and slug. so when I iterate through the database I can get name and everything is fine. but when I want to get URL nothing happening I'm getting no error but when I'm inspecting via browser getting empty space on HTML site version but there is Django code. views.py from django.shortcuts import render from .models import BlogPost from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from slider.models import HomePageSlider from blogmenu.models import Menu def index(request): Post_list = BlogPost.objects.all()[:5] Slider_item = HomePageSlider.objects.all() menu_item = Menu.objects.all() template_name = 'front/index.html' return render(request, template_name, {"Post_list":Post_list, "data_item":Slider_item, "menu_item":menu_item, }) def post_list(request): postlist = BlogPost.objects.all().order_by('-Post_created_on')[:5] menu_item = Menu.objects.all() template_name = 'front/postlist.html' paginate_by = 3 return render(request, template_name, {"postlist":postlist, "menu_item":menu_item, }) def post_detail(request,Post_slug): template_name = 'front/post_detail.html' post_content = BlogPost.objects.all() left_post = BlogPost.objects.all()[:5] menu_item = Menu.objects.all() try: Post = BlogPost.objects.get( Post_slug = Post_slug) except : return render(request,'front/404.html') return render(request, template_name, {'blogpost':Post, 'post_content':post_content, 'left_post':left_post, "menu_item":menu_item, }) # Create your views here. My urls.py from django.urls import path from .import views from django.conf import settings from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap from .feeds import LatestPostsFeed sitemaps = { "post": PostSitemap, … -
Trying to reload a python function from within Java using Django?
I am trying to call this python class from within Java class Testing(models.Model): hello = random.choice([3, 4, 11, 66, 34, 22, 33]) def __str__(self): return hello I call it within my html page using Java var Testing = "{{Testing}}"; document.write(Testing); I made the script to test if random.choice is ran again when calling the function in Java, it's not (it produces the same number if you refresh the page). How would I go about re-running random.choice when java calls for Testing.hello? -
IntegrityError when submit
I am creating this app, where I want to be able to report a film to the admins database. At the moment I can go to a movie, then click report, and then be sent to the report_form template. But when I click the report button on this template, I only get this, and there is no reaction in the database: Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: board_report.reporter_id Does anybody have a solution for this? report_form.html {% extends "board/base.html" %} {% load crispy_forms_tags %} {% load materializecss %} {% block content %} <div class="valign-wrapper row login-box"> <div class="col card hoverable s10 pull-s1 m6 pull-m3 l8 pull-l2"> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="card-content"> <span class="card-title">Jusity why you want to report this film?</span> <div class="row"> {{ form|materializecss }} </div> </div> <div class="card-action right-align"> <input type="reset" id="reset" class="btn-flat grey-text waves-effect"> <input type="submit" class="btn green waves-effect waves-light" value="Report"> </div> </form> </div> </div> {% endblock content %} models.py class Report(models.Model): reason = models.TextField() reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter") reports = models.ForeignKey(Film, on_delete=models.CASCADE) def __str__(self): # pragma: no cover return f"{self.reports.title} reported by {self.reporter.username}" def get_absolute_url(self): # pragma: no cover return reverse("film-detail", kwargs={"pk": self.pk}) views.py class FilmReport(LoginRequiredMixin, CreateView): model = … -
save many to many update form - (forms.form) - django
i can't save new data set to the field (branch) which is many to many relation with another model named 'branch' that i need to save on my current model 'Products' note: every thing works fine except for saving the new branches added to update form model class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, related_name='product_category', on_delete=models.PROTECT) image = models.ImageField(upload_to='images', null=True, blank=True) branch = models.ManyToManyField(Branch, related_name='product_branch') views.py def product_update(request, pk): current_product = get_object_or_404(models.Product, pk=pk) initial_dict = { "branch": current_product.branch.all(), "name": current_product.name, "category": current_product.category, } edit_product_form = forms.EditProductForm(request.POST, request.FILES, initial=initial_dict) if request.method == 'POST': if edit_product_form.is_valid(): try: name = edit_product_form.cleaned_data['name'] category = edit_product_form.cleaned_data['category'] image = edit_product_form.cleaned_data['image'] if models.Product.objects.filter(Q(name=name) & ~Q(id=current_product.id)).exists(): messages.add_message(request, messages.INFO, _('إسم المنتج مضاف من قبل بالفعل')) else: current_product.name = name current_product.category = category current_product.image = image current_product.save() messages.add_message(request, messages.INFO, _('تم تعديل المنتج بنجاح')) return redirect('product_details', pk=current_product.id) except ImageSizeError: messages.add_message(request, messages.INFO, _('حجم الصورة اصغر من المطلوب')) return redirect('product_details', pk=current_product.id) else: edit_product_form = forms.EditProductForm( initial=initial_dict) context = { 'current_product': current_product, 'edit_product_form': edit_product_form, } return render(request, 'product_update.html', context) forms.py class EditProductForm(forms.Form): name = forms.CharField(widget=forms.TextInput) category = forms.ModelChoiceField(queryset=models.Category.objects.all()) image = forms.ImageField(widget=forms.FileInput()) branch = forms.ModelMultipleChoiceField(queryset=models.Branch.objects.all(), widget=forms.SelectMultiple) -
Foriegn key shown as a drop down. Any way to show it as a text value ? (django)
In my application, on page1, I create a Project object and then on page 2, I create a batch object. The "batch" object has a many-to-one relationship with "Project". It therefore needs to display the Project object when batch form is called. I can show the Project object on a batch form but it is shown as a drop down. I would like it to be shown as a field value but it doesnt work. Can you please help. Thanks. models.py Class Project name = models.CharField() Class Batch name = models.CharField() project = models.ForeignKey('Project', on_delete=models.CASCADE) template.py <a href="{% url 'create_batch_url' pk=project.id %}" role="button" >Link to Batch</a> passing the foreign key from urls.py path('batch/new/<int:pk>', batch_views.review_batch, name='create_batch_url'), views.py simple view which calls the model form forms.py class BatchForm(ModelForm): class Meta: model = Batch fields = ('name', 'project',) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") project_id = kwargs.pop("project_id") #Only show the project where the request came from self.fields['project'].queryset = Project.objects.filter(id=project_id) -
How to use a single PostGreSQL while having two Django Apps accessing in Google App Engine and Google App Engine Flex
I have a Django Application (first application) running on Google App Engine. There is another time consuming application (second application) running in Google App Engine Flex. Both applications are connected to the same PostGreSQL Database. When the second application finishes its execution it needs to write the results to the database and first application can access the data. What should be the correct way to do this ? Should I use exact same models and expect everything to be straightforward ? -
Why the object is not deleted?
I am new to SO and Programming. And i found this SO question: How to dynamically delete object using django formset The author says here - https://stackoverflow.com/a/48075686/11523612 that when the user refreshes the page the item is still in the cart. But i dont understand why still stays in the cart when the ajax view is called and the object is deleted? -
How can I create form comatible with my user models in django and how can I convert my admimin page to contain these types of users?
models.py file: from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver class User(AbstractUser): is_taxpayer = models.BooleanField(default=False) is_official = models.BooleanField(default=False) username = models.CharField(max_length=200, unique=True) email = models.EmailField(max_length=200, unique=True) class TaxpayerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='taxpayer_profile') aadhar = models.DecimalField(max_digits=12, decimal_places=0) class OfficialProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='official_profile') aadhar = models.DecimalField(max_digits=12, decimal_places=0) uid = models.CharField(max_length=200) USERNAME_FIELD = 'uid' @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('****', created) if instance.is_taxpayer: TaxpayerProfile.objects.get_or_create(user = instance) else: OfficialProfile.objects.get_or_create(user = instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): print('_-----') # print(instance.internprofile.bio, instance.internprofile.location) if instance.is_taxpayer: instance.taxpayer_profile.save() else: OfficialProfile.objects.get_or_create(user = instance) Here is the forms.py file: from django import forms from .models import User, TaxpayerProfile, OfficialProfile class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email'] class TaxpayerProfileForm(forms.ModelForm): class Meta: model = TaxpayerProfile fields = ['aadhar'] class OfficialProfileForm(forms.ModelForm): class Meta: model = OfficialProfile fields = ['aadhar', 'uid'] Here is the views.py file: from django.contrib.auth import login from django.shortcuts import redirect, render from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import CreateView from .forms import OfficialProfileForm, TaxpayerProfileForm, UserForm from .models import User, TaxpayerProfile, OfficialProfile def taxpayer_profile_view(request): if request.method == 'POST': user_form = UserForm(request.POST) taxpayer_profile_form = TaxpayerProfileForm(request.POST) if user_form.is_valid() and taxpayer_profile_form.is_valid(): user = user_form.save(commit=False) … -
Configure Django application(deployed on GKE) and Google Cloud Storage
I am writing an API ( endpoint: IP/create/user ) which has to upload image files to Google Cloud Storage Bucket. So, I have created a Multi-region and Standard : Storage Class bucket with name eitan_data_storage. While running the application on localhost the endpoint copy the image from source to specified directory. I created docker image and deployed on GKE. The api is working perfectly fine here. But my requirement is to store the media files of the system users to google cloud storage. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) # defing a custome user manager class for the custome user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' view.py class UserAPIViews(APIView): """ This is a create user api view class. """ parser_classes = (FormParser, MultiPartParser) def post(self, request, format=None): serialized_data = serializers.UserSerializer(data=request.data) if serialized_data.is_valid(): … -
DRF TypeError, you may need to make the field read_only
First of all, I have this project structure. foo_project - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - board - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py - accounts - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py Board, # models.py class Board(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='boards') title = models.CharField(blank=False, max_length=255) body = models.TextField(blank=False) image = models.ImageField(upload_to='time_line_photo') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Meta: ordering = ['-created'] # serializers.py from rest_framework import serializers from .models import Board from django.contrib.auth.models import User class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') # views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics from .models import Board from .serializers import BoardSerializer class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer user = serializers.PrimaryKeyRelatedField(read_only=True,) def perform_create(self, serializer): serializer.save(user=self.request.user) class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerialize Accounts, # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from ..board.models import Board class UserSerializer(serializers.ModelSerializer): boards = serializers.PrimaryKeyRelatedField( many=True, queryset=Board.objects.all() ) class Meta: model = … -
How to keep adding divs while there are objects to loop in Django?
I am creating a blog homepage. I basically have two divs. One the first one I only want to show the latest post added. On the second I want to show all other posts. So, I created this template: <div class="row"> {% for post in post_list %} {% if forloop.counter == 1 %} <div class="col-lg-10 mx-auto"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> </div> <div class="row justify-content-center"> {% else %} <div class="col-lg-5"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}')"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> {% endif %} {% endfor %} My problem is that, right, after the {% else %}, it will loop two posts and stop. How can I make it continue to loop as long as there are posts? -
How to style TextField() model in django
I have got a field in my table: description = models.TextField() I would like to be able to decide how the text is display. For example I have a main description of a product and then I want to display some information like that: data1: data1 data2: data2 When I am adding a description in django admin page everything is connected with each other data1: data1 data2: data2 Is there a way to organize it in a different way? Can I choose what text would be bold? -
How do I form a Django query with an arbitrary number of OR clauses?
I'm using Django 2.0 with Python 3.7. I want to write a query that returns results if the fields contains at least one of the strings in an array, so I want to set up an OR query. I have tried this class CoopManager(models.Manager): ... # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): queryset = Coop.objects.all() for type in types_arr: queryset = queryset.filter(type__name__icontains=type) print(queryset.query) return queryset However, this produces a query that ANDs the clauses together. How do I perform the above but join all the clauses with an OR instead of an AND? I'm using MySql 5.7 but I'd like to know a db independent solution if one exists. -
How to improve problem solving skills in python/Django
I can say I am an intermediate programmer in python Django. I am trying to find a website (documents; anything) which hosts good puzzles (or similar) for python. My objective is to experience mind teasers kind of things for python. And certainly not any interview kind of questions. I would want to improve my techniques in python/Django, during a situation to solve a problem, or during implementation of an algorithm, etc. Second, I am also looking into new, simple and innovative problems (just problems, to improve problem solving) which can be practiced in python. For example, implementing shift rotate functionality (this is very basic, but will teach you in-depth bit handling), and to a advanced level like graphs; etc.