Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with linking ID of a task in DJANGO
I am working on to do app, and I cannot solve this problem. The problem is linking the tasks with ID or PK... i am getting this error: NoReverseMatch at / Reverse for 'update_task' with arguments '(1,)' not found. 1 pattern(s) tried: ['update_task/ and it is pointing that error is here (in template): <a href="{% url 'update_task' task.id %}">Update</a> views.py def updateTask(request, pk): task = Task.objects.get(id=pk) form =TaskForm(instance=task) context = {'form': form} return render(request, 'tasks/update_task.html',context) template <h3>To Do</h3> <form action='/' method="POST"> {% csrf_token %} {{form.title}} <input type="submit" name="Create Task"> </form> {% for task in tasks %} <div class=""> <a href="{% url 'update_task' task.id %}">Update</a> <p>{{task}}</p> </div> {% endfor %} URLS.PY from django.urls import path from tasks import views urlpatterns = [ path('', views.index, name='list'), path('update_task/<str:pk/', views.updateTask, name='update_task'), ] -
How to set Environment Varibales EC2 Ubuntu for Django App
I am EC2 to host a django app and now want the Database settings not to hard coded in the settings file rather set them as environment variables. I changed the /etc/environment and added the variables as .... DB_HOST="HOST VALUE" DB_NAME="DB NAME" .... The app is not reading them and rather acts like the variables are not present.I thought it was only problem with host and its user name and password so i put them directly in settings and left the name of db in the environment variables only. But It wasn't reading the environment variables at all and error came up: No Database Selected I want to set the database variables in such a way that i can use them in settings .... 'HOST':os.environ.get('DB_HOST'), .... and i get the value mentioned in the environments for DB_HOST. -
How to change header/page title of User change page in Django admin
I'm working on Django.And I wanted to change the header in the User change page in the Django admin as marked with red color in the pic : And my admin.py file is this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So what should be done to change this?? Thanks in advance!! -
How to solve IntegrityError (FOREIGN KEY constraint failed) in django?
I have this model system. The project contains entries. But when I try to delete Project I am getting this error. I am getting IntegrityError (FOREIGN KEY constraint failed) on deleting a project. How can I solve this error? Here are my foreign key relations from models.py class Project(models.Model): project_author = models.ForeignKey(User, on_delete=models.CASCADE) project_entry = models.ForeignKey(Project, on_delete=models.CASCADE) class Entry(models.Model): entry_author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Project, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) reply = models.ForeignKey('Comment', null=True, blank=True,related_name="replies", on_delete=models.CASCADE) class EntryComment(models.Model): post = models.ForeignKey(Entry, blank=True, null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) entryreply = models.ForeignKey('EntryComment', null=True, blank=True,related_name="entryreplies", on_delete=models.CASCADE) Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/lift/delete/ Traceback (most recent call last): File "D:\Projects\django_project\django_venv\lib\site-packages\django\db\backends\base\base.py", line 243, in _commit return self.connection.commit() The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projects\django_project\django_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\contrib\auth\mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "D:\Projects\django_project\django_venv\lib\site-packages\django\views\generic\base.py", line 97, in … -
variable DJANGO_CONFIGURATION is undefined - Django + virtual env + apache
I try to deploy my Django App in my apache server. Despite all the tutorials and threads (including stackoverflow) I read, I'm still not able to find the solution. Just for the context, I made a Django App locally using virtual env and Django 3+. My next step is to put it in the Apache server. So after pulling from my github account, I have set up a virtual environment on the server using virtualenv env Then I run the following command line to install the requirements pip install -r requirements.txt So far so good. Basically, after configurating the virtual host, I have the following error : **django.core.exceptions.ImproperlyConfigured: Configuration cannot be imported, environment variable DJANGO_CONFIGURATION is undefined.** I precise (it will be included below) that everything is installed correctly and the environment variable has been set. Here my logs project_error.log : [Fri Apr 24 17:54:52.416771 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] mod_wsgi (pid=30069): Target WSGI script '/var/www/admin-dashboard/project/wsgi.py' cannot be loaded as Python module. [Fri Apr 24 17:54:52.416903 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] mod_wsgi (pid=30069): Exception occurred processing WSGI script '/var/www/admin-dashboard/project/wsgi.py'. [Fri Apr 24 17:54:52.417460 2020] [wsgi:error] [pid 30069] [remote 193.248.218.163:55647] Traceback (most recent call last): [Fri Apr 24 17:54:52.417527 … -
How to make the django redirects a user to the page I need?
How to make the django redirects a user to the page I need? I have a web app. For example a user is on a page with an address local:8000/detail-order/18. This page is detail info of the order 18. On this page is link to edit this order. When a user clicks this link a order editing form shows up. When a user writes in this form and click the submit button, he has an error. I whould like that a user goes back to local:8000/detail-order/18. NoReverseMatch at /update-orders/18 Reverse for 'detail_order' with no arguments not found. 1 pattern(s) tried: ['detail\-order/(?P[0-9]+)$'] Request Method: POST Request URL: http://192.168.0.249:8000/update-orders/18 Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail_order' with no arguments not found. 1 pattern(s) tried: ['detail\-order/(?P[0-9]+)$'] Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 urls.py from django.contrib import admin from django.urls import path, include from .views import * from print import views urlpatterns = [ path('', views.home_page, name='index'), path('orders', views.OrderCreateView.as_view(), name='orders'), path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'), path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'), ] views.py class UpdateOrderView(CustomSuccessMessageMixin, UpdateView): model = Order template_name = 'orders.html' form_class = OrderForm success_url = reverse_lazy('detail_order')# HERE success_msg = 'Изменения сохранены' def get_context_data(self, **kwargs): kwargs['update'] = True return super().get_context_data(**kwargs) -
Error: The SECRET_KEY setting must not be empty - Django webdev
I developed a simpel web application in django and everything is working perfectly. I did push the code already to Heroku and no errors appeared. Now i'm trying to set my secret key and other vital settings to environment variables. I'm on a Windows and set everything correctly in the control panel. when i test the secret key with: SECRET_KEY = os.environ.get('SECRET_KEY_THIJS') print(SECRET_KEY) It prints out the secret key correctly. When i try to push the code to Heroku via Git is says: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Please help me out! *Note: excuse me for me English and i am a hobby programmer and did not have any education related to it (learned everything via Google and Youtube) :) Sincerely, Rick -
Unresolved import in my django project : VSCode
I have a Django project called ubm-app with two apps, main and ubm-app. I've created a couple of classes, URLAdder and URLModifier in the views.py file in the main app. Im trying to import these views into my urls.py file by using the line from . import views but VS Code shows me the error unresolved import 'c:\Users\Hari\Desktop\django\UBM-App\main.'. This is my urls.py file. from django.urls import path, include from . import views urlpatterns = [ path('',views.home,name='home'), path('api/add/', views.URLAdder.as_view()), path('api/modify/',views.URLModifier.as_view()), ] This is the settings.json file found when I use the Configure Language Specific Settings... option. { "C_Cpp.updateChannel": "Insiders", "[python]": { } } This is the settings.json file in the .vscode folder in my Django project. { "python.pythonPath": "env\\Scripts\\python.exe" } Can anyone please suggest a fix to this with an explanation? I seem to be having these unresolved import errors time and again. Forgive me if the error is a basic one. -
Can I match the height of a formset input with a button?
I'm currently making a todo list using Django model formsets. I came across a problem when trying to list each form in the formset with a delete button next to it. Here's a picture of what it looks like now: When looked at closely, the spacing and height for each form are slightly different than the spacing and height for each delete button. Here's my views.py: def dashboard(request): user = request.user todo_list = Todo.objects.filter(user=user).all() UpdateFormSet = modelformset_factory(Todo, fields=('item',)) if request.method == 'POST': formset = UpdateFormSet(request.POST, queryset=todo_list) if 'delete' in request.POST: items_to_delete = request.POST.getlist('delete') deleted_items = Todo.objects.filter(pk__in=items_to_delete).delete() if 'update' in request.POST: if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.user = user instance.save() return redirect('dashboard') formset = UpdateFormSet(queryset=todo_list) if not formset: formset = UpdateFormSet() # Figure out a way to put add button next to first form context = { 'current_user': request.user, 'formset':formset, 'items':todo_list, } return render(request, 'users/dashboard.html', context) Template: <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 pt-3">ToDo Items</legend> {{ formset.management_form }} <div class="row"> <div class="col-6"> {% for form in formset reversed %} {{ form.id }} <div class="py-3"> {{ form.item }} </div> {% endfor %} </div> <div class="col-6"> <div class="input-group"> <div class="input-group-append"> <button type="submit" class="btn btn-sm btn-success … -
Django Missapplying Migrations
I am not sure whether I am doing something wrong or it is a problem with one of the pieces I am using for the project. Basically, I added a field to a model and am trying to make a migration. Here is the model. The field is the poster one. class Video(models.Model): title=models.CharField(max_length=500) description=models.TextField(default="") creation_date=models.DateTimeField(default=timezone.now) videofile=models.FileField(upload_to='videos/', null=True, verbose_name="") poster=models.ImageField(upload_to='video/thumbnails', null=True, verbose_name="") tags = TaggableManager() actions = ['delete'] def __str__(self): return self.title + ": " + str(self.videofile) ... That is the only thing that changed in the model. Let's make the migrations. (app-web) selfishman@user-desktop:~/sites/app-web/app$ python manage.py makemigrations Migrations for 'video_uploader': video_uploader/migrations/0007_video_poster.py - Add field poster to video So far, so good. Let's try to apply the migration. (app-web) user@user-desktop:~/sites/app-web/app$ python manage.py migrate video_uploader Operations to perform: Apply all migrations: video_uploader Running migrations: Applying video_uploader.0002_video_creation_date...Traceback (most recent call last): File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/db/backends/ut ils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "creation_date" of relation "video_uploader_video" already exists There rest of the backtrace: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/miniconda3/envs/app-web/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
django user creation using UserCreationForm issue
As per youtube tutorial the user is created with exactly same method but mine doesn't work. Why? views.py from django.shortcuts import render,redirect from .forms import CreateUserForm def registerView(request): form=CreateUserForm() if request.method=="POST": form=CreateUserForm(request.POST) if form.is_valid(): form.save() user=form.cleaned_data.get('username') messages.success(request,'Account was successfully created for '+ user) return redirect('login') context={'form':form} return render(request,"accounts/register.html", context) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] Why is a user not created? -
image will not display Django3 serving Angular8
similar to this SO Question but that solution would not work for me. I cannot get my image to render with the Angular frontend. In the browser {{recipe.photo}} displays http://127.0.0.1:8000/media/images/photo1_mMxzxU0.png. From the other SO question I thought since this was an absolute url pointing to the image it would work.. html <div *ngIf= "recipes"> <ul *ngFor ="let recipe of recipes"> {{recipe.name}} {{recipe.photo}} <img src={{recipe.photo}} height="150" > </div> models.py class Recipe(models.Model): name = models.CharField(max_length=30) photo = models.ImageField(upload_to='images/', null=False, blank=False) views.py class RestaurantRecipes(generics.ListAPIView): serializer_class = RecipeSerializerShort serializers.py class RecipeSerializerShort(serializers.ModelSerializer): class Meta: model = Recipe fields = ['name','photo'] settings.py MEDIA_ROOT = '/Users//Documents///backend/images/' MEDIA_URL = '/media/' -
How to edit user data in django
I have used bs4 modal in profile.py and and Profile model which has bio,fullname,gender and other related info. I am unable to edit user information.When i click on save changes on modal button,nothing happens. this is forms.py:- class UserUpdateForm(forms.ModelForm): class Meta: model=User fields=['username','email'] widgets={ 'username':forms.TextInput(attrs={'placeholder':'Enter Name'}), 'email':forms.TextInput(attrs={'placeholder':'Enter Email'}) } class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=['image','fullname','bio','location','birth_date','gender'] widgets={ 'image':forms.FileInput(attrs={'placeholder':'Upload Image'}), 'fullname':forms.TextInput(attrs={'placeholder':'Enter Fullname'}), 'bio':forms.Textarea(attrs={'placeholder':'Enter bio'}), 'location':forms.TextInput(attrs={'placeholder':'Enter location'}), 'birth_date':forms.TextInput(attrs={'placeholder':'Enter birth_date'}), 'gender':forms.TextInput(attrs={'placeholder':'Enter gender'}), } this is profile.py:- <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered model-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">EDIT INFORMATION</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body "> <form method="POST" class="form-group" enctype="multipart/form-data" > {% csrf_token %} <div class="form-group textinput"> {% for fields in u_form %} {{fields}} <br> {% endfor %} {% for fields in p_form %} {{fields}} <br> {% endfor %} </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> this is views.py:- @login_required def profile(request): if request.method =='POST': u_form = UserUpdateForm(request.POST,instance=request.user) #request.POST=>to post the data , instace=request.user=> p_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile)#request.FILES is for image upload if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context={ 'u_form':u_form,'p_form':p_form} return render(request, 'users/profile.html',context) … -
Django: How to get a JSON object from models with ONLY fields and not pk and model key?
2 days with the same problem... overall, Django is very simple but for json, I do not understand... I want to pass data from my database to be used in JS code in order to construct dynamically a table first I tried to pass my data as a context trought a "data-" attribute in one of my html element but the problem is that my data are in a string format instead of JSON and I am unable to parse when I use django serializer to get an Json object, I have pk and model key that make it difficult to manipulate... is there a easiest way to have a simple Json object from my model? or, how is the good pratice to get data from server/database to be available in JS? [ { "pk": "4b678b301dfd8a4e0dad910de3ae245b", "model": "sessions.session", "fields": { "expire_date": "2013-01-16T08:16:59.844Z", ... } } ] expected : [ { "expire_date": "2013-01-16T08:16:59.844Z", ... } ] -
Creating django widget 3.x
I have been trying to create a form widget in Django 3.x and not many of 2.x blogs seem to work. The following doesnt work widgets.py from django import forms from django.template import loader from django.utils.safestring import mark_safe class AutocompleteInputWidget(forms.Widget): template_name = 'widgets/autocomplete.html' def get_context(self, name, value, attrs=None): return {'widget': { 'name': name, 'value': value, }} def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name) return mark_safe(template) apps.py from django.apps import AppConfig class WidgetsConfig(AppConfig): name = 'widgets' forms.py from django import forms from .models import Country, CountryList from .widgets import AutocompleteInputWidget class CountryForm(forms.ModelForm): name = forms.CharField(max_length=20, widget=AutocompleteInputWidget()) class Meta: model = Country fields = ['name'] # widgets={'last_name':AutocompleteInputWidget()} lookups.py from ajax_select import register, LookupChannel from .models import Country from django.db.models import Lookup # @register('country') class CountryLookup(Lookup): model = Country def get_query(self, q, request): return self.model.objects.filter(country__icontains=q).order_by('country')[:50] def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.country models.py from django.db.models.fields import Field Field.register_lookup(CountryLookup) from django.db import models from .widgets import AutocompleteInputWidget class CountryList(models.Model): name = models.CharField("name", max_length=20, blank=False, null=False) class Country(models.Model): # country = models.CharField(verbose_name="Country", max_length=20, blank=False, null=False) country = models.ForeignKey(CountryList, on_delete=models.PROTECT, verbose_name="Country") -
WSGI Server logging stdout info logs as error
Initially in our django project we log everything to file(info | error). But recently we want to move away from file logging to console logging. Everything seems to be working fine except, the info log is being logged as [wsgi.error] []1 I tried every possible thing that I could, but still couldn't figure out a way to log it as wsgi.info. Dev Environment : Django app running as docker docker container Just a beginner to django, so please do help me out. -
Django- make form fields read only
I have a Django web app with a form that initiates with initial data. Users are able to update the information in the form and submit changes. I want to disable form input on weekends, making the fields read only. Is there a way to toggle all the fields in the form to read only, possibly from django admin? -
save cropped image of cropper.js to database using django
I was using django to build a webpage and used cropper.js to crop a image, but i am not able to save the cropped image. The original image uploaded is getting saved to the DB not the cropped image. Code: Your browser does not support canvas. <script> window.onload = function () { var c = document.getElementById("testCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("img"); ctx.drawImage(img, 20, 20); } // initialize cropper by providing it with a target canvas and a XY ratio (height = width * ratio) cropper.start(document.getElementById("testCanvas"), 1); function handleFileSelect() { // "{{ image.data_image.url }}" // this function will be called when the file input below is changed var file = document.getElementById("fileInput").files[0]; // get a reference to the selected file var reader = new FileReader(); // create a file reader // set an onload function to show the image in cropper once it has been loaded reader.onload = function (event) { var data = event.target.result; // the "data url" of the image cropper.showImage(data); // hand this to cropper, it will be displayed }; // this loads the file as a data url calling the function above once done reader.readAsDataURL(file); } </script> </div> -
Django: Access user object in models.py using sessions
I'm trying to access user object in models.py I have two apps (users & employees) under my Django project, I just want to know which user added employee in the employees model at the time of displaying the employees details -
Django REST Framework: POST Request: How to save data only if the data doesn't exist
I'm new in Django and I'm stuck on the following problem: I have the following code: models.py: class Vote(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='votes', null=True) views.py: class VoteViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = VoteSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) serializer.py: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = ('id', 'answer', 'user') def create(self, validated_data): answer = validated_data.get("answer", None) poll = answer.poll return Vote.objects.create(answer=answer, poll=poll, user=user) Each time I do a POST Vote request a new Vote is created. But I would like to check if the user has already voted for the poll. I have this code but I don't know where to put it: if not poll in [vote.poll for vote in user.votes.all()]: # Create Vote How to correctly check if the user has already voted in the poll and if not, create a vote? -
How do I get my serializer to return data from a dependent field in my model?
I'm using Django 2 and Python 3.7. I have these models set up. One (Coop) is dependent on the other (CoopType) using Many-To-Many ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False, unique=True) objects = CoopTypeManager() class CoopManager(models.Manager): # Look up by coop type def get_by_type(self, type): qset = Coop.objects.filter(type__name=type, enabled=True) return qset # Look up coops by a partial name (case insensitive) def find_by_name(self, partial_name): queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True) print(queryset.query) return queryset # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): filter = Q( *[('type__name__icontains', type) for type in types_arr], _connector=Q.OR ) queryset = Coop.objects.filter(filter, enabled=True) return queryset class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have the following serializers set up, designed to return the data in JSON form ... class CoopTypeField(serializers.PrimaryKeyRelatedField): queryset = CoopType.objects def to_internal_value(self, data): if type(data) == dict: cooptype, created = CoopType.objects.get_or_create(**data) # Replace the dict with the ID of the newly obtained object data = cooptype.pk return super().to_internal_value(data) ... class CoopTypeSerializer(serializers.ModelSerializer): class Meta: model = CoopType fields = ['id', 'name'] def … -
Is there a more efficient substitute to my code?
please help give me a more efficient substitute to my code -
'Cannot query Conversationt, Use a query set for Profile'
I'm trying to query my Conversation objects, and get a convo object that may be already created or may not be already created between the two users. Then, I want to get_or_create one passing in the two users. Now, I'm getting a 'cannot query conversation object. Use profile' ... not sure why this is. I should be returning a list that I can pluck in or if it can't get it, it should create it. Conversation object has a ManyToMany field called Members. Profile is my user model that I created. **error ** ValueError at /message/2/ Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile". Request Method: GET Request URL: http://localhost:8000/message/2/ Django Version: 2.2.3 Exception Type: ValueError Exception Value: Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile". Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py in check_related_objects, line 1081 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingAppCustom', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] views.py/Message def message (request, profile_id): other_user = get_object_or_404(Profile,id=profile_id) members_query = Conversation.objects.filter(members= request.user).filter(members= other_user) conversation, created = Conversation.objects.get_or_create( members = members_query) if request.method == 'POST': form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date) if form.is_valid(): form.save() return redirect ('dating_app:messages.html') else: conversation, created = Conversation.objects.get_or_create( members= [request.user, other_user]) … -
Update instances of ModelFormset
In my django app two models are connecetd by manytomany relation and I am using modelformset_fatory to create a form like this Views.py def post(request): tform = TeamForm() pform = modelformset_factory(Player, form=PlayerForm, extra = 1) pform = pform(request.POST or None, queryset = Player.objects.filter(id__isnull = True)) if request.method == 'POST': t = Team() tform = TeamForm(request.POST, instance=t) if tform.is_valid() and pform.is_valid(): tform.save() instances = pform.save(commit=False) for i in instances: player = Player() player.pname = i.pname player.hscore = i.age player.age = i.hscore player.save() t.player.add(player) t.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) This is working perfectly fine but the problem occurs when I try to update the form, I am able to initialize the form with the data but when I create a new player instance in form it does not get saved. Update function: def update(request, pk = None): team = Team.objects.get(id = pk) tform = TeamForm(instance = team) pform = modelformset_factory(Player, form=PlayerForm, extra=0) print("players", Player.objects.filter(team=team)) pform = pform(request.POST or None, queryset=Player.objects.filter(team=team)) if request.method == 'POST': tform = TeamForm(request.POST, instance=team) print("tform ", tform) print("pform ", pform) if tform.is_valid() and pform.is_valid(): tform.save() pform.save() return redirect('/exams/dashboard/') else: print('invalid data') return render(request, 'team/team_create.html', {'exform': tform, 'exformset': pform}) Do I … -
Django Deploy to heroku: Application Error
I deployed my Django project to heroku. It deployed successfully but the page shown Application error. In logs on heroku error be like this. 2020-04-24T05:34:09.500250+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [4] [INFO] Using worker: sync 2020-04-24T05:34:09.506988+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [10] [INFO] Booting worker with pid: 10 2020-04-24T05:34:09.532649+00:00 app[web.1]: [2020-04-24 05:34:09 +0000] [11] [INFO] Booting worker with pid: 11 2020-04-24T05:34:10.051702+00:00 heroku[web.1]: State changed from starting to up 2020-04-24T05:34:20.000000+00:00 app[api]: Build succeeded 2020-04-24T05:34:26.126726+00:00 app[web.1]: [2020-04-24 05:34:26 +0000] [4] [INFO] Shutting down: Master 2020-04-24T05:34:41.808971+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/favicon.ico" host=dashboard-retail.herokuapp.com request_id=f5feaeba-075f-4dc7-a637-fe6b271f0d67 fwd="125.24.11.115" dyno=web.1 connect=1ms service=30003ms status=503 bytes=0 protocol=https 2020-04-24T05:34:42.096139+00:00 app[web.1]: [2020-04-24 05:34:42 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:10) In Procfile,I set like this web: gunicorn myWeb.wsgi --log-file - Help me please. Thank.