Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework ApiView not allowing DELETE
I am new to Django and I am having a issue sending a DELETE request to a class based view which inherits from APIView. Here is my class: class PageDetail(APIView): def get(self, request, pk): page = get_object_or_404(Page, pk=pk) data = PageSerializer(page).data return Response(data) def put(self, request, pk): stream = io.BytesIO(request.body) response = JSONParser().parse(stream) page = Page.objects.get(pk=pk) page.title = response.get('title', page.title) page.content = response.get('content', page.content) user = User.objects.get(pk=response.get('author', page.author)) page.author = user page.save() return HttpResponseRedirect(reverse('pages_detail', args=(page.id,))) def delete(self, request, pk): page = Page.objects.get(pk=pk) page.delete() return HttpResponseRedirect(reverse('pages_list')) When I make the DELETE request, the resource is deleted, but the page responds with the message: {'detail':'Method 'DELETE' not allowed.'} Although in the header I have: Allow: GET, PUT, DELETE, HEAD, OPTIONS Anyone have any ideas? -
Django REST Framework - Saving phone with country prefix to database
Using my creating user endpoint, I want to take 'phone' value from request, and add it with country calling code before. Request data provides me country code, which is foreign key to Country model. Example request body: { ... 'phone':'000111222', 'country':'616', } In this case, '616' is Poland country code. I do following to implement all my logic in my UserViewSet create() method: class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() def create(self, request, format=None): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # collecting country country_code = request.data['country'] country = Country.objects.get(code=country_code) # setting dial code before phone dial_code = country.calling_code #'48' phone = dial_code + request.data['phone'] #'48000111222' # checking if final phone number already exists in database if User.objects.filter(phone=phone).exists(): return Response({'phone': 'Phone number already exists.'}, status=status.HTTP_400_BAD_REQUEST) serializer.save(country=country, phone=phone) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Code works for now, but I have few issues. UserSerializer actually validate my fields before my create function does. It use raw phone value to validate uniqueness in database - in this case 000111222 instead of 48000111222, what can cause an unwanted error. My solution seems a bit too complicated for me, could any of the built-in functionalities help? If not, would it be a good idea to … -
Django framework, crud in grid row
I’ve been developing an app in djanog 3.0 for my wife. Got a nice modal ajax crud up and running for the grid, but she does not like the modal effect, she just wants to edit inside the row and always have an empty row at the bottom for new entries. I’ve looked at table2 and jqgrid but have not been able to find something that works like that. I’ve now been playing around with editablegrid.net js grid and I can display data and edit, but not save the edited data. Editablegrid is a good example of what my wife would like to do, without the empty new row, but should be able to hack that in. Obviously I’ll not be able to make a row a from, so I need to figure out how to make my data serial in something like json. I then also need the CSRF token as part of the json right? I’m way out of my depth as I develop embedded c for a living and this all is self taught as we go. Questions are: What is the best grid for something like this? Is it even possible? Is django even suited for … -
How can I implement this in? I want a employeee to enter a code that connect to the employer table on registration?
I want to create a company and employee relationship. So there going to be two table. The company won't be adding the employee to their list. A employee, on register will enter a company code(like the company primary key) on the form and it will link to the company. I am using django, postgresql -
Django load an imageField in a template
Essentially what I'm trying to do is load the thumbnail image from my Post model in my template. models.py class Post(models.Model): objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') thumbnail = models.ImageField(name="photo", upload_to='thumbnails/', null=True, default='default.png') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 3 template_name = 'blog/post/list.html' def get_context_data(self, **kwargs): obj = Settings.objects.get(pk=1) context = super().get_context_data(**kwargs) context["blog_name"] = getattr(obj, "blog_name") context["footer"] = getattr(obj, "footer") context["description"] = getattr(obj, "description") context["keywords"] = getattr(obj, "keywords") return context I added <img src="{{post.thumbnail.url}}" alt="{{ post.title }}"> to my template to try and load the image but no luck. I can access the image if I load the path manually and i already added MEDIA_URL and MEDIA_ROOT to my settings.py If this question can be improved please let me know as I am knew to django. -
I try to add data from Admin pannel but it fails Django
I try to add data as admin. I go to the url /admin/festival/festival/add and it shows me the form.I complete it, but when i click on save it shows me the IntegrityError, saying that Foreign Key constraint failed. But i have no foreign key in the model. How can i fix this? IntegrityError at /admin/festival/festival/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/festival/festival/add/ Django Version: 3.0.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: /home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages/django/db/backends/base/base.py in _commit, line 243 Python Executable: /home/anamaria/workspace/AllFest2/venv/bin/python Python Version: 3.6.9 Python Path: ['/home/anamaria/workspace/AllFest2/festivals', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/anamaria/workspace/AllFest2/venv/lib/python3.6/site-packages'] here is the models.py: from django.db import models from jsonfield import JSONField class Festival(models.Model): name = models.CharField(max_length=100) start_date = models.DateTimeField(blank=True, null=True, default=None) end_date = models.DateTimeField(blank=True, null=True, default=None) number_of_tickets = models.IntegerField() location = JSONField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name in views.py i have: from .serializers import FestivalSerializer from .permissions import FestivalPermission from rest_framework import mixins, status from festival.models import Festival from rest_framework.viewsets import GenericViewSet class FestivalViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,GenericViewSet): serializer_class = FestivalSerializer permission_classes = [FestivalPermission] queryset = Festival.objects.all() serializer in serializers.py: from rest_framework import serializers from festival.models import Festival class FestivalSerializer(serializers.BaseSerializer): class Meta: model = Festival fields = '__all__' … -
how to save a model that contains self-referential ForeignKey from form
I'm new in django ... I have a model with a self-referential field and i want to get this model from a form. but this self-referential have no value! what should i do?! models.py class agents(models.Model): name = models.CharField(max_length=100) address = models.TextField(blank=True, null=True) phone = models.CharField(max_length=20) is_producer = models.BooleanField(default=False) serial = models.TextField(default='') users = models.ManyToManyField(user_models.users, through='user_agent') def __str__(self): return self.name def get_absolute_url(self): return reverse('agent_detail', args=[str(self.id)]) class user_agent(models.Model): user = models.ForeignKey(user_models.users, on_delete=models.CASCADE) agent = models.ForeignKey(agents, on_delete=models.CASCADE) parent = models.ForeignKey("self", on_delete=models.CASCADE) forms.py class AgentSignUpForm(forms.ModelForm): class Meta: model = models.agents fields = ('name', 'address', 'phone', 'is_producer', 'serial', 'users', ) views.py @login_required def agent_register(request): if request.method == 'POST': form = forms.AgentSignUpForm(request.POST) if form.is_valid(): agent = form.save(commit=False) agent.save() form.save_m2m() return redirect('agent_list') else: form = forms.AgentSignUpForm() return render(request, 'agent/signup.html', {'form': form}) -
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?