Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unresponsive after changing deployment environment to apache/mod_wsgi
I am moving a Django app from IIS (via FastCGI) to Apache on the same system (Windows Server 2016). The site runs fine on IIS and the development server, but when I spin it up in Apache, it is unresponsive (Waiting on 127.0.0.1…). No error messages (despite debug logging in Django and httpd), no useful logs, just unresponsiveness. I added some debug statements throughout the code and it looks like settings.py loads successfully, but wsgi doesn’t return the application. If I comment out all of the apps from settings.py and urls.py, I am greeted with the default login page, so I don’t think that it is a mod_wsgi configuration issue. I am using the latest 64-bit Apache from Apache Lounge (built with VC16), mod_wsgi built from source using pip and VC16, Django 3.0 and Python3.7 (64-bit). My relevant lines from httpd –M, httpd –V, python –V, etc. below. Full output, vhost config and settings.py are on pastebin. $httpd.exe -V Server version: Apache/2.4.41 (Win64) Apache Lounge VS16 Server built: Aug 9 2019 16:46:32 Server's Module Magic Number: 20120211:88 Server loaded: APR 1.7.0, APR-UTIL 1.6.1 Compiled using: APR 1.7.0, APR-UTIL 1.6.1 Architecture: 64-bit Server MPM: WinNT threaded: yes (fixed thread count) forked: … -
Django .objects,get for merged querysets from different models
I have an abstract base model ('Base') from which two models inherit: 'Movie' and 'Cartoon'. I display a list of both movies and cartoons to the user (with the help of itertools.chain). Then I want to give the user the opportunity to delete any of these items, without knowing in advance whether it is a movie or a cartoon. I am trying to do it like this: ... movies = Movie.objects.filter(user_created=userlist).order_by('title') cartoons = Cartoon.objects.filter(user_created=userlist).order_by('title') all_items = list(chain(movies, cartoons)) item = all_items.get(id=item_id) item.delete() But then PyCharm states, Unresolved attribute reference 'get' for class 'list' I understand why this happens but I don't know how to avoid it. Is there any way to merge two querysets from different models and apply get or filter without removing the abstract base model and creating a physical parent model? -
How to add taxonomy models like Drupal in Wagtail?
How to add taxonomy models like Drupal in Wagtail? Like this: - Sports --- Baseball --- Basketball --- Footbal - Technology --- Computers --- Videogames --- Software ----- Development ----- Apps ..... And create url pattern based in taxonomy terms with a serial number at the end Like this: www.myweb.com/technology/software/development/post-title-slug-54321 -
Right serializer relations between two models
I'm trying to create two interlinked instances of models in the database and I get an error. TypeError: Got a TypeError when calling Vendors.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Vendors.objects.create(). You may need to make the field read-only, or override the VendorsSerializer.create() method to handle this correctly. models.py class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) ... class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.ForeignKey('Vendors', models.DO_NOTHING) contact_name = models.CharField(max_length=45, blank=True, null=True) email = models.CharField(max_length=80, blank=True, null=True) phone = models.CharField(max_length=45, blank=True) serializer.py class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorsSerializer(serializers.ModelSerializer): vendor_contact = VendorContactSerializer() class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda', 'vendor_contact',) views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" serializer_class = (VendorsSerializer) def post(self, request, *args, **kwargs): vendor_serializer = VendorsSerializer(data=request.data) vendor_contact_serializer = VendorContactSerializer(data=request.data) try: vendor_serializer.is_valid(raise_exception=True) \ and vendor_contact_serializer.is_valid(raise_exception=True) # vendor = vendor_serializer.save(user_id=CustomUser.objects.get(id=2)) print(vendor_serializer.validated_data) vendor = vendor_serializer.save() vendor_contact_serializer.save(vendor=vendor) except ValidationError: return Response({"errors": (vendor_serializer.errors, vendor_contact_serializer.errors, )}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) I also tried to do in VendorsSerializer vendorcontact = VendorContactSerializer(source='vendor.vendorcontacts', many=True) but got the … -
How to implement paginations in function base views in django
i know how to implement pagination in class base views using ListView class ProductListView(ListView): model = product template_name = 'products/product_list.html' context_object_name = 'products' ordering = ['-pub_date'] paginate_by = 5 but i don't know how to implement paginations in function base views. i read that we have to import Paginator for django.core.paginator and use it in functions base view like this paginator = Paginator(qs, 5) but it's not working. def Productlistview(request): qs = product.objects.all() location_search = request.GET.get('location') print(location_search) categories = request.GET.get('categories') price = request.GET.get('price') ordering = ['-pub_date'] paginator = Paginator(qs, 5) if location_search != "" and location_search is not None: qs = qs.filter(location__contains=location_search) context = { 'posts': qs } return render(request, "products/product_list.html", context) -
How to access authenticated user in graphene-django resolve method?
I have added this to my Query class and it's returning null in response. me = graphene.Field(UserType) def resolve_user(root, info): logger.info("***** Inside resolve ****") return info.context.user and my UserType is defined like this. class UserType(DjangoObjectType): fields = ["id", "name", "email", "username"] class Meta: model = User I'm on Django==3.0 if it helps I'm authenticated and the cookies are present. It's not even printing the log which is confusing me. -
Django: search form does not work due to page not found error
I am new to Django. I am trying to implement a search function on a blog but it does not appear to work. I do not understand why. Could someone tell me what goes wrong. My code snippet in the HTML looks like this: <form action="{% url 'search' %}"> <div class="form-group"> <input type="search" name="q" id="search" placeholder="Enter search query"> <button type="submit" class="submit"><i class="icon-search-1"></i></button> </div> </form> My urls.py is setup like this: urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name= 'post-list'), path('search/', search, name='search'), path('post/<id>/', post, name= 'post-detail'), path(r'tinymce/', include('tinymce.urls')) ] And the Error looks like this: Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='post-list'] search/ [name='search'] post/<id>/ [name='post-detail'] tinymce/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, action=/search, didn't match any of these. As you can see: search is in the urls.py: does it have anything to do with the fact that somehow Django automatically puts a leading '/' in front of 'search'? As indicated: I am relatively new to Django so I hope this is enough information to be able to answer my question. If not, please indicate so. -
Django: separate sessions for admin and user
I have two React frontends (admin.example.com and www.example.com). My Django backend is located on backend.example.com. Right now I have one LoginView for both use cases (admin and end-user). I am using SessionMiddleware. What I want to achieve are two different sessions - so I can login as an admin and have access to admin.example.com and separately be logged in into www.example.com as a user. If I set SESSION_COOKIE_DOMAIN = '.example.com' I have just a single session for everything. Can anyone point me in the right direction on how could I achieve this? Any best practices? Any help is very much appreciated. -
Is it possible to define a field that auto-increments within the value of a foreign key?
Is it possible to define a field that auto-increments within the value of a foreign key? E.g. if we define Company and Department models in Django: class Company(models.Model): name = models.CharField(max_length=25) class Department(models.Model): company = models.ForeignKey(Company) department_number = ...? # should start from 1 for each company in a pure SQL implementation the pair (company_id, department_number) would be a composite primary key. I'm looking for solutions in Django or SQL that are safe (in terms of multiple processes creating departments simultaneously) and efficient. I'm using MySQL, but comparisons with other databases are also welcome. -
Django add specific attribute for form select options
I have a two models : class Font(models.Model): name = models.CharField(max_length=64) css_value = models.CharField(max_length=128) def __str__(self): return self.name class DesignOverride(models.Model): x_font = models.ForeignKey(Font, null=True, blank=True, on_delete=models.SET_NULL) In my ModelForm for 'DesignOverride' I am calling 'x_font' using the widget select : class DesignOverrideForm(forms.ModelForm): class Meta: model = DesignOverride fields = ['x_font'] widgets = { 'x_font': forms.Select(attrs={ 'class': 'form-control'}) } I wanted to know if there was a way from Django to customize my options by giving them the style 'font-family: X' where X is the css_value of the options Font. I tried to loop in the 'x_font' select field in the template but seems it's only having the options as string (and therefore lost the information about 'css_value'). -
Where did the error in the Django model come from?
I'm trying to add additional fields for the User model. The migrate and makemigrations commands worked. When I try to create createsuperuser, this error occurs . Postgresql Is Enabled . I tried to change upload_to, add "blank = True", "default" to the model parameters, but nothing changed. Trace: return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: ОШИБКА: отношение "blog_customuser" не существует LINE 1: ..._customuser"."age", "blog_customuser"."city" FROM "blog_cust... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 95, in handle error_msg = self._validate_username(username, verbose_field_name, database) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 201, in _validate_username self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 44, in get_by_natural_key return self.get(**{self.model.USERNAME_FIELD: username}) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 402, in get num = len(clone) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 256, in __len__ self._fetch_all() File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Роман\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line … -
Unbound Local Error while searching in Django
I'm trying to search advertisements by their locations. But For the following codes, I'm receiving: 'UnboundLocalError: local variable 'advertisements' referenced before assignment' I'm new to Django so any help would be appreciated. views.py: def Search(request): query = request.GET['query'] advertisements = advertisements.objects.filter(place__icontains=query) params = {'advertisements':advertisements} return render(request, 'search.html', params) html: <form method="get" action="/search" class="form-inline"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="query" id="query"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit"><i class="fas fa search"></i><a>Search</a></button> </form> <h2>Search Results:</h2> {% for advertisement in advertisements %} <div class="col-sm"> <div class="card" style="width: 16rem;"> <div class="card-body"> <h5 class="card-title">{{advertisement.place}}</h5> <p>House/Apartment Size: {{advertisement.size}} squarefeet</p> <p>Time Posted: {{advertisement.date_posted}}</p> <p>Rent per month: {{advertisement.rent}} taka</p> <a href='{% url 'advertisement_details' advertisement.id %}' class="card-link">Full Details</a> </div> </div> </div> {% endfor %} models.py: class advertisements(models.Model): place=models.CharField(max_length=30) address=models.CharField(max_length=50) bedroom=models.PositiveSmallIntegerField() bathroom=models.PositiveSmallIntegerField() rent=models.PositiveIntegerField() size=models.PositiveIntegerField() date_posted=models.DateTimeField(default=timezone.now) owner= models.ForeignKey(User,on_delete=models.CASCADE) -
Enable/Disable an HTML Element With Dynamically Generated Names/Tags
I have a table in HTML where the ID is dynamically generated from a row counter: $(table).find('tbody').append("<tr>name=\"tableRow\"</tr>" + "<td>" + "<select id=\"shapeSelect_" + rowCount + "></td>" + "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>" + "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>" + "</select>" + "</td>" + "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>" + "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>" + "</tr>" I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input. Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding: $(#maxAltitude).prop("disabled", true); How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed. I've tried jQuery and javascript but can't seem to find a good way to do this: <option onclick="shapeSelect()" value="sphere">Sphere</option> <option onclick="shapeSelect()" value="cylinder">Cylinder</option> function shapeSelect() { var shapeSelects = document.getElementsByName("shapeSelect"); var maxAlts = document.getElementsByName("maxAlt"); for(var i = 0; i < shapeSelects.length; i++) { switch(shapeSelects[i].value) { case "sphere": maxAlts[I].disabled = True; … -
1048, "Column 'user_id' cannot be null"
models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=30,blank=False,null=False) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10,blank=True) def __str__(self): return self.fullname forms.py class UserForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter Username'})) password= forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Enter Password'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2 = None class Meta: model=User fields=['username','password','email'] class ProfileForm(forms.ModelForm): fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) class Meta: model=Profile fields=['fullname'] views.py def register(request): if request.method =='POST': form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): variable=form.save(commit=False) variable.password = pbkdf2_sha256.encrypt(request.POST['password'],rounds=12000,salt_size=32) variable.save() profile=profile_form.save(commit=False) profile.username=variable.username profile.save() username = form.cleaned_data.get('username') messages.success(request,f'account created for { username }') return redirect('login') else: form = UserForm() profile_form = ProfileForm() context={'form':form , 'profile_form':profile_form} return render(request, 'users/register.html',context) I have created two table auth_user (default) and users_profile.When i register the User default data goes into auth table but fullname is not inserted into user_profile. -
Django application structure,
I'm trying to deploy my Django project to Google AppEngine, however I can't figure out how to properly set up application entrypoint. This is my whole project structure: service-master: app.yaml main.py service: manage.py service-project: wsgi.py settings.py ... service-app-1: ... service-app-2: ... How can I make it work? I tried to move main.py to service and use entrypoint: gunicorn --chdir /service main:application in app.yaml but it results in Error: can't chdir to '/service', I guess AppEngine doesn't allow to change directory. -
Displaying title in the django administration instead of object
I have got a main table called Item and table Bike that is connected to Item with OneToOneField. When I add a new Bike using django administration page, it shows as Bike object (1). Is there a way to show the title of that Bike, that is stored in the Item table instead of that "Bike object (1)"? my models.py: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') -
Windows IOError: [Errno 13] Permission denied:
I'm setting up tinymce with Django for the first time and we want to enable image upload. I configured the image upload URL, even managed to pass the CSRF token, otherwise Django wouldn't accept the POST request. Here's the view tinymce is interacting with: @login_required @require_http_methods(['GET', 'POST']) def upload_image(request): if request.method == 'GET': return JsonResponse({'location': settings.IMAGES_DIR}) if request.method == 'POST': with open(settings.IMAGES_DIR, 'wb+') as destination: for chunk in request.FILES['image'].chunks(): destination.write(chunk) I set up settings.IMAGES_DIR as in the local project directory just to test it out. However when the function gets to the part where it starts writing the file I'm getting the following error: IOError: [Errno 13] Permission denied: 'C:\\Users\\xxxxxx\\PycharmProjects\\xxxxx\\media' I am not too familiar with Windows permissions but I checked the folder properties and every user group seems to have write permissions. Now, I'm not sure "who" is the user doing the actual writing, it must be the user running the PyCharm server locally, right? Well, that's just my regular Windows user which is an admin and all, and in any case has write permissions in that folder as I mentioned. What's going on here? PS: yes, I am on Windows and I am using Django 1.8. Please don't … -
What can I do to make 'id' = id in this class-based view in Django?
views.py from django.shortcuts import render from django.views.generic import DetailView from .models import Producto def general_view(request): context = { 'articulos': Producto.objects.all(), } return render(request, 'shop/general_view.html', context) class DetailedView(DetailView): model = Producto template_name = 'shop/specific_view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['determinado'] = Producto.objects.get(pk=*¿?*) return context urls.py from django.urls import path from . import views from .views import DetailedView urlpatterns = [ path('', views.general_view, name='general-view'), path('<int:pk>/', DetailedView.as_view(), name='specific-article'), ] As you see, the problem occurs because I don't know how to call the id or pk in the detailed_view in views.py, I'm guessing you maybe have to do a dictionary but I don't know where to do it nor how. It works if I set the id to 1, but obviously what this does is that is shows in every url with a different id the same article. -
Deploy django app as static pages on common static web-hosting provider? [closed]
I've worked a few times on django but I'm not an expert and I don't know all the low level functionalities of the framework. With that in mind, I was wondering if there's is a way to deploy a django app as a static website or if there's something out there that generates html pages out of a django project (connecting routes to files, fixing links, etc.) and then store those generated files on static web-hosting provider (i.e. github-pages) I've looked around but I couldn't find anything worth trying out. What do you guys suggest? -
how manage connections of mysql for concurrent request passes from celery
We are using 'django-db-connection-pool' package to manage connection pooling. We are trying to execute two tasks concurrently using celery with two different queues of rabbitmq(rabbitmq is celery broker), one task execute successfully but second task is not succeeded , this will drop mysql connections. if we try both functions without queuing, it will work properly. That means, if concurrent request is passed to mysql that loss mysql connections. for sequential execution it will works properly. Please provide solution to overcome this issue. Thanks in advance. -
Object not being saved to database Django
I have a webapp with a friends feature, which is all working except for the bit of saving the current user into the requested user's ManyToManyField. Here is my model friends = models.ManyToManyField(User,blank=True,related_name='user_connections') And my view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): username = self.kwargs.get("username") obj = get_object_or_404(UserProfileInfo,slug=username) # print(f'OBJECT: {other}') # print(f'Current user: {self.request.user}') # user_profile = User.objects.get(username=username) url_ = obj.get_absolute_url() user = self.request.user user_ = self.request.user.username # user__ = print(f"HEY YOU! YE! \n{username}\n{obj}\n{url_}\n{user}") if user.is_authenticated: print("User is authenticated") if user in obj.friends.all(): obj.friends.remove(user) user.user_connections.remove(obj) user.save() else: obj.friends.add(user) user.user_connections.add(obj) user.save() return url_ And finally my urls path('profile/<str:username>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), Everything is working except for saving for the user.user_connections.add(obj). On obj.friends.add(user), it adds the current user to their Manytomanyfield, but it's just not working on the user.user_connections.add(obj) one. I have tried heaps of things, including user.friends.add(obj) user.userprofileinfo.friends.add(obj) user.userprofileinfo.user_connections.add(obj) UserProfileInfo is my custom UserProfile model I am just confused as to why this isn't working, and it's weirder because no errors are being thrown either. Thanks for any help -
Working with Django Foreign Keys, Linking to HTML page
I made a Django app for an online school, so I added a foreign key to link the databases Classes and Subjects, I just created A subject in the admin page, linked it into the wanted class, when trying to access it in HTML page I am just having the same subject on all classes, So i thing I used the foreign key the wrong way! how to do it? please help. MODELS.py: class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title class Material(models.Model): name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) classes= models.ForeignKey(Class, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.name HTML page: <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> <button class="bt1"><a href="#">سجل دخول</a></button> </ul> </nav> <div class="div1"> <img src="static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">الصفوف</h1> </div> <div class="cardrow"> {% for class in class.all %} <div class="cardcolumn"> <a href="{{% url 'material' class.id %}}"> <div class="card"> <img class="imgcls" src="{{ class.image.url }}"> <h1>{{ class.title }}</h1> </div> </a> </div> {% endfor %} </div> </div> </body> </html> … -
How can i delete a database row from a Django view? [duplicate]
I created a form where an user can delete some preferences from the Database. Here is my view: if 'button2' in request.POST: instance = Keys.objects.get(id=request.POST['id']) form2 = DeleteKey(request.POST, instance=instance) if form2.is_valid(): profile = form.save(commit=False) profile.key = '' profile.save() messages.success(request, f"Success") return HttpResponseRedirect(request.path_info) And the form: class DeleteKey(forms.ModelForm): class Meta: model = Keys fields = () def save(self, commit=True): send = super(DeleteKey, self).save(commit=False) if commit: send.save() return send This code works, the problem is that i'm not really deleting the row from my own database, i'm just setting that field to an empty string. Is there any way to completely delete the row, instead? Thanks in advance! -
How to properly write a custom user model and manager in Django v3?
I have a user model like below class User(AbstractBaseUser, PermissionsMixin): class Type: FP = 'fp' BRANCH = 'branch' CHOICES = ( (FP, '채용공고 보기'), (BRANCH, '채용공고 내기'), ) class Sex: MALE = 'male' FEMALE = 'female' CHOICES = ( (MALE, '남성'), (FEMALE, '여성') ) type = models.CharField( max_length=10, verbose_name='계정 종류', choices=Type.CHOICES, ) email = models.EmailField( verbose_name='이메일', unique=True, ) name = models.CharField( max_length=10, verbose_name='이름' ) nickname = models.CharField( max_length=10, verbose_name='닉네임', unique=True, ) phone = models.CharField( max_length=20, verbose_name='전화번호', ) sex = models.CharField( max_length=10, verbose_name='성별', choices=Sex.CHOICES, ) company_name = models.CharField( verbose_name='회사이름', max_length=256, ) dob = models.DateTimeField( verbose_name='생년월일' ) profile_img = models.ImageField( verbose_name='프로필 이미지', upload_to=user_profile_img_file_path, ) sns_id = models.TextField( verbose_name='SNS ID' ) sns_type = models.CharField( verbose_name='SNS 종류', max_length=20, ) objects = UserManager() USERNAME_FIELD = 'email' and custom manager like below class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): sys.stderr.write(repr(extra_fields)) if not email: raise ValueError('이메일은 필수사항입니다') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_superuser = True user.save(using=self._db) return user and test looking like below def test_create_valid_user_success(self): """ Test that creating user with valid payload is successful """ profile_img = self.generate_photo_file() payload = { 'email': 'test@gmail.com', 'password': '1234567', 'type': 'fp', 'name': 'testname', 'nickname': 'testnickname', 'phone': '01012341234', 'sex': 'male', … -
Error after deploying a Django app on Heroku
I am deploying a Django app on heroku , which is successfully deploying, but I am getting the following error when I want to view the app on the provided http link. i am deploying on linux mint mint 19.3.Keep in mind gunicorn is in requirements.txt file. Blockquote 2020-02-21T16:22:09.021935+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-21T16:22:18.635625+00:00 heroku[web.1]: Starting process with command `gunicorn brendan_project.wsgi -- log file-` 2020-02-21T16:22:20.734759+00:00 heroku[web.1]: Process exited with status 127 2020-02-21T16:22:20.679520+00:00 app[web.1]: bash: gunicorn: command not found Blockquote Hear is my requirements.txt file Blockquote asgiref==3.2.3 astroid==2.3.3 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.2 django-crispy-forms==1.8.1 django-fontawesome==1.0 django-heroku==0.3.1 django-mailjet==0.3.1 django-sendgrid==1.0.1 django-smtp-ssl==1.0 gunicorn==20.0.4 idna==2.8 isort==4.3.21 lazy-object-proxy==1.4.3 mailjet-rest==1.3.3 mccabe==0.6.1 psycopg2==2.8.4 pylint==2.4.4 pytz==2019.3 PyYAML==5.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 typed-ast==1.4.1 urllib3==1.25.7 whitenoise==5.0.1 Blockquote