Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write POST function for nested-serializers Django
I am unable to write a .create method for this nested serailizer. I want to create an appointment row for every new appointment and for appointment_detail table i want to create as many rows as many services are opted. my models.py class Service(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE,null=True, related_name='services') service_name = models.CharField(max_length=100) time = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=False) def __str__(self): return self.service_name + ' in ' + str(self.category) class Appointment_Status(models.Model): status = models.CharField(max_length=15) def __str__(self): return self.status class Appointment(models.Model): """This is the model where all the orders/Appointments will be saved""" user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE, null=True) branch = models.ForeignKey(Zorg_Branche, on_delete=models.CASCADE,null=True, related_name='branch') timestamp = models.DateTimeField(auto_now_add=True, blank=True) status = models.ForeignKey(Appointment_Status, on_delete=models.CASCADE, null=True) totaltime = models.PositiveIntegerField(default=0) total_price = models.DecimalField(decimal_places=2, max_digits=10, default=0) def __str__(self): return str(self.user) + ' -> ' + str(self.zorg) class AppointmentDetail(models.Model): appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE,null=True,related_name='appointment') related_name='category') service = models.ForeignKey(Service, on_delete=models.CASCADE,null=True, related_name='service') def __str__(self): return str(self.appointment) + ' ' + str(self.service) in serializers.py class UserAppointmentSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email_id', 'mobile_number', 'birthdate', 'photo_url', 'gender', ] class ZorgBranchAppointmentSerializer(serializers.ModelSerializer): class Meta: model = Zorg_Branche exclude = ['id', 'zorg'] class CategoryAppointmentSerializer(serializers.ModelSerializer): """ This serailizer is to serialize and deserailize category model """ class … -
How to Filer data between 2 Dates in Django?
I am trying to filter data between 2 dates in Django, I am using single input box for this and I am using jquery daterangepicker for this, Please check my coed and let me know where i am mistaking. here is my views.py file... def myview(request): if request.method == 'POST': startdate = request.POST.get('created_on') enddate = request.POST.get('created_on') if start != None or end != None: result = Model.objects.filter(created_on__range=[startdate,enddate]) else: print('Error') here is my forms ... <form method="POST"> {% csrf_token %} <div> <input type="text" name="created_on" value="" /> </div> <div class="col-sm-4"> <button>Submit</button> </div> </div> </form> I am getting errors to filter data, I think i am mistaking in query, Please let me know how i can Solve this issue. -
JWT token mismatch while OTP verification
I'm generating token while user verified OTP. but while i verify the token in header then I'm getting Invalid payload. if any help for why i'm getting this error then would be much appreciated. serializers.py : class OTPVerifyForResetPasswordAPIView(APIView): permission_classes = (AllowAny,) def post(self,request,*args,**kwargs): data = request.data user = request.user print(user) phone_number = request.data['phone_number'] country_code = request.data['country_code'] verification_code = request.data['verification_code'] if phone_number and country_code and verification_code: obj_qs = User.objects.filter(phone_number__iexact = phone_number,country_code__iexact = country_code) obj = '' if obj_qs.exists() and obj_qs.count() ==1: user_obj = obj_qs.first() #Development if verification_code == '1234': payload = jwt_payload_handler(user_obj) token = jwt_encode_handler(payload) token = 'JWT '+str(token) return Response({ 'success' : 'True', 'message' : 'Your mobile number verified successfully', 'data' : { 'phone_number' : user_obj.phone_number, 'country_code' : user_obj.country_code, 'token' : token, } },status=HTTP_200_OK) else: ##some logic.... else: ## some logic... -
How to authenticate session inside class based view django
I am new to Django I am trying to convert my function-based views to class-based views. Here I ran into a problem. I don't know wether the user is logged in or not. I can't call the user.is_authenticated inside my class-based view. My Code: class UserLoginView(FormView): template_name = 'login.html' form_class = UserLoginForm success_url = reverse_lazy('login') def form_valid(self, form): user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) if user is not None: login(request=self.request, user=user) print('Login Successfull') return HttpResponseRedirect(self.success_url) def form_invalid(self, form): print('Login Failed') return HttpResponseRedirect(self.success_url) How can I check wether the use is already logged in and send him directly to the home page. Thanks in advance. -
What is the best way to deploy Django web site ,I have already purchased a domain
I had a django website which was up and running but unfortunately it is down now. I'm moving on to re deploying it .Which is best approach to deploy it? There are few static pages and blog post function, and vacancy posting function. Both this blog post nd vacancy post done through the Django admin console(login in separately to Django admin with the super user created).I want all these to work as it is in the new environment. Please suggest best way to to do this? -
Django: Only getting first element of my list instead of the full list from a GET request
I'm having an issue getting a list of objects with a GET request on this endpoint: /api/stock/{bar_id}/ It should return a list of stock for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. When I make the GET request I only end up getting the first stock, but I should be getting the full list of stocks. I'm getting this: { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } Instead of this: { [ { "ref_id": { "ref": "first", "name": "first one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 }, { "ref_id": { "ref": "second", "name": "second one", "description": "description" }, "bar_id": 1, "stock": 10, "sold": 0 } ] } Here is my BarSerializer: from rest_framework import serializers from ..models.model_bar import Bar from .serializers_stock import * class BarIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Bars models from DB """ class Meta: model = Bar fields = [ 'id', 'name', 'stock' ] class BarDetailsSerializer(serializers.ModelSerializer): """ Serializer showing details of a Bar model from DB """ stock = StockDetailsSerializer(many=True) class Meta: … -
Error executing script because its MIME type
I have a DjangoRest/ Vue.js app that I want to deploy. My app is running fine if I run the two servers separately. So I did a npm run build and tried to run it locally as well. I did change my settings and index.html: index.html % extends "base.html" %} {% load static %} {% block style %} <link type="text/css" href="{% static 'bundle.css' %}"> {% endblock %} {% block content %} <div id="app"></div> {% endblock %} {% block js %} <script type="text/javascript" src="{% static 'bundle.js' %}"></script> {% endblock %} This is my vue.config.js: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "https://trustymonkey.herokuapp.com/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public("https://trustymonkey.herokuapp.com/") .host("https://trustymonkey.herokuapp.com/") .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, }}; This is the console: So my bundle.js is found. But I get a blank page and in the chrome dev tool console I get: -
how to display multiple forms on a page using formset
I'm making a form to add an organization record models.py: class Entity(BaseModel): title = models.CharField(_('Заголовок'), max_length=255, db_index=True) short_description = models.CharField(_('Короткое описание'), max_length=255, blank=True, null=True) body = models.TextField(verbose_name=_('Описание'), max_length=4096) ordering = models.IntegerField(_('Порядок'), default=0, db_index=True) test_field = models.TextField(verbose_name=_('Тестовое поле'), max_length=4096) test_field2 = models.CharField(max_length=255, blank=True,null=True, verbose_name=_('Тестовое поле 2')) class Meta: ordering = ('ordering',) verbose_name = _('Форма') verbose_name_plural = _('Формы') class Industry(BaseModel): name = models.CharField(_('Название'),max_length=255, blank=True, null=True) entity = models.ForeignKey( Entity, verbose_name=_('Организация'), related_name='industries', on_delete=models.CASCADE ) class Meta: ordering = ('ordering',) verbose_name = _('Отрасль') verbose_name_plural = _('Отрасли') def __str__(self): return self.name class BaseAddressClass(BaseModel): address = models.TextField(verbose_name=_('Адрес'), blank=True, null=True) oktmo = models.CharField(verbose_name=_('ОКТМО'),max_length=255, blank=True, null=True) postal_code = models.CharField(verbose_name=_('Почтовый индекс'), max_length=20, blank=True, null=True) entity = models.ForeignKey( Entity, verbose_name=_('Организация'), related_name='addresses', on_delete=models.CASCADE, blank=True, null=True ) class Meta: ordering = ('ordering',) class PhysicalAddress(BaseAddressClass): class Meta: verbose_name = _('Физический адрес') verbose_name_plural = _('Физические адреса') class LegalAddress(BaseAddressClass): class Meta: verbose_name = _('Юридический адрес') verbose_name_plural = _('Юридические адреса') i want the page to show the branches in a list and also have the ability to add addresses. for this in the EntityForm, i added the industry. The form with the address added inlineformset_factory.for rendering the formset i am using django-formset.js. forms.py: class EntityForm(forms.ModelForm): industry = forms.ModelChoiceField(queryset=models.Industry.objects.all()) class Meta: fields = '__all__' exclude = ('ordering', … -
How to set up Google Pay for my django online ecommerce website?
I have an online e-commerce website where the user can trade images with each other What I'm trying to achieve is: seller requests the buyer to give him money, the buyer clicks on the "accept payment" and then set up payment with his Google Pay account, finally the seller will get charged in his Google Pay account How can I do so? I'm using Django 3.1 -
Why django library xhtml2pdf returning an error?
I am using xhtml2pdf library in drf viewset to generate a pdf document from an html template that lists all records from a given model. Below is the action that I have defined inside my vieset @action(detail=False) def pdf(self, request, *args, **kwargs): import datetime filter = self.filter_queryset(Ledger.objects.values_list('name','groupid__name','panno', gstin')) pdf_obj = render_to_pdf('reports/report.html', {'data': filter}) if pdf_obj: response = HttpResponse(pdf_obj, content_type='application/pdf') filename = 'Ledgers-' + str(datetime.date.today()) + '.pdf' content = "inline; filename=%s" % (filename) download = request.GET.get("download") if download: content = "attachment; filename=%s" % (filename) response['Content-Disposition'] = content return response This results in ValueError exception with following message <PmlTable@0x7F7C4304B390 2 rows x 0 cols>... must have at least a row and column I am clueless what am I doing wrong here, Please advise. -
Automatic migration handling in django
I have been thinking about how to manage automatic migration like removing fields which are migrated from changing the branch like let say a field x was migration from dev branch and i have moved to master branch and there is no x field there i want to handle this automatically is there any scirpt/library for this or any idea, Thanks -
Handling Public and Internal version of Django Model
I am currently experiencing difficulties in processing community contributions to my publicly available Database. My Backend is designed using Django, and people are allowed to update some data via API calls. I have a lot of models, quite a few of which can be updated via API(DRF). Every registered user is allowed to post some updates, but these updates should not be publicly available immediately. After one of the moderators has reviewed and accepted these updates, they should be publicly available. The structure of each Database Table is designed with three states: "draft", "accepted" and "rejected". class SomeModel(models.Model): class Status(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted') REJECTED = 'rejected', _('Rejected') top_city = models.CharField(max_length=255) ... all other attributes goes here ... New data should replace the previously accepted data after review. Until this review has been completed (1, 2 or 3 days), the previously accepted data should remain public. Simply said, multiple versions of the model - one is public, the other is "internal" until accepted. Solution like Mixin Model or class decorator would be the best, so I don't need to repeat a lot of code in each Model. My current idea how to solve this does not … -
Filtering record from django model using a tuple
I have a django model such as this id task_id status content_type content_encoding result date_done meta task_args 1 "9bb8b186-da5d-43b2-8fca-1496474b1cc9" "SUCCESS" "application/json" "utf-8" """done""" "2020-09-23 14:15:03.064283+05:30" "{""children"": []}" "('test_user', 1, ['test'], 'id_001')" The task_args field in the model is a text field. How do I filter the model based on this data? Specifically I want the task_id where task_args is ('test_user', 1, ['test'], 'id_001') This is my code so far user = request.user.username num = 1 parsed_data = eval("['test']") id = "id_001" print(type(parsed_data)) args = f"{(user,num,parsed_data,id)}" print(args) task_id = list(TaskResult.objects.filter(task_args=args).values('task_id')) Right now this code outputs an empty list Not sure what I am doing wrong. Is this because I am passing the tuple as a string? I am passing this as a string because the task_args field is a text field. I also tried passing this as a tuple. Even that results in an empty list. -
How to call a request inside a class in view
I am new to Django. I need to set the foreign key as current signed in user for a post model but it says the NOT NULL constraint failed: posts_post.author_id django I dont know why. class UserRegistraionModel(models.Model): post = models.CharField(max_length=5000, blank=False, null=False) image = models.ImageField(upload_to='media', blank=False, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) I don't know what is the error how can I solve this. Thanks in advance. -
Meaning of these lines (python, django and channels)
I was messing aroung with django channels, and I was wondering how can I add a user to a chat, so I've come across this answer in stackoverflow: How to add members to same chat room in Django Channels 2.1.1 using multichat example But then I came across these lines and I realized that I don't understand them: '''if staff in users_and_rooms and len(users_and_rooms[staff]) in range(3):''' '''await channel_layer.send(users_and_channels[random_available_staff], content)''' '''users_and_channels[random_available_staff],''' I guess 'users_and_channels' is a dictionary with value pairs being the user and his/her channel. I got that. But what about the first line? 'len(users_and_channels[staff] in range(3)' Isn't 'range' for loops? What is it doing there? And 'len(users_and_channels[staff]', it is checking the length of what? The number of channels of a user? It's a little confusing to me. Hope someone can help me. Thank you very much. And excuse my English. -
How to send data via http request in django
I was trying to make a django webapp and I can send data through the http request. I want to send the id or number to be sent on the background not on the URL my main goal was to send the data like the user object in django, so we can access the data in the html like the user object {{user}} i tried to send with the request object but i didn't work -
How to login with register api if user already exits while social authentication: Django?
I'm creating custom user social authentication system. whenever user first time login then with social account then his/her social credential will be save in db. if second time will login with social account then it's automatic will login with his/her social_id that saved in db. but in my case, whenever user first time login with social account then his/her social credential saves in db. but in second time it's showing user already exits. Any help would be much appreciated. serializers.py : class CreateSocialUserSerializer(serializers.ModelSerializer): login_type = serializers.CharField(allow_blank=True) social_id = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) phone_number = serializers.CharField(allow_blank=True) country_code = serializers.CharField(allow_blank=True) token = serializers.CharField(read_only=True) first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) class Meta: model = User fields = ['login_type', 'social_id', 'email','phone_number', 'country_code','token','first_name','last_name', ] def validate(self,data): logger.debug(data) login_type = data['login_type'] social_id = data['social_id'] email = data['email'] phone_number= data['phone_number'] country_code = data['country_code'] #some validation logic here...... #Email Validation logic here ..... #Mobile Number Validation if phone_number.isdigit() == True: user_qs = User.objects.filter(phone_number__iexact = phone_number) if user_qs.exists(): raise APIException400({'success' : 'False','message' : 'User with this phone_number is already exists'}) else: if login_type in ['2','3','4','5','6']: if social_id: social_qs = User.objects.filter(social_id__iexact=social_id) if social_qs.exists(): raise APIException400({'success': 'False', 'message': 'User with this social_id is already exists. Please login.'}) return data return data … -
only '-' value appeared for all the data in my csv file
from django.contrib import admin from .models import NutritionModel from import_export.admin import ImportExportModelAdmin class NutritionModelAdmin(ImportExportModelAdmin, admin.ModelAdmin): list_display = ['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] search_fields=['sl_no', 'sub_domain', 'indicators', 'national_indicator_reference','sector', 'data_collab','variable_required','data_sources'] filter_horizontal=() list_filter=[] fieldsets=[] admin.site.register(NutritionModel,NutritionModelAdmin) from import_export import resources class NutritionModelResource(resources.ModelResource): class Meta: model = NutritionModel resource_class = NutritionModel #models.py from django.db import models class NutritionModel(models.Model): id=models.AutoField(primary_key=True) sl_no = models.CharField(null=True, blank=True,max_length=5, verbose_name="Sl no") sub_domain = models.CharField(null=True, blank=True,max_length=5,verbose_name="Sub-domain") indicators =models.CharField(null=True, blank=True,max_length=200,verbose_name="Indicators") national_indicator_reference =models.CharField(null=True, blank=True,max_length=10,verbose_name="National indicator reference") sector =models.CharField(null=True, blank=True,max_length=20,verbose_name="Sector") data_collab = models.CharField(null=True, blank=True,max_length=100,verbose_name="Ministry/ Agencies for data collaboration") variable_required =models.CharField(null=True, blank=True,max_length=200,verbose_name="Variable required") data_sources =models.CharField(null=True, blank=True,max_length=10,verbose_name="Data sources@") -
ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'
I am new to django framework. I tried to create a login authentication through twitter using tweepy. While saving the fetched data in my db, I am facing this issue for OAuth1Session. I have tweepy installed. I have also installed requests_oauthlib, but still doesn't able to resolve this error. from tweepy.auth import OAuthHandler #error called here (**ImportError: cannot import name 'OAuth1Session' from 'requests_oauthlib'** ) from .models import Tweet import credentials def user_tweets(): auth = OAuthHandler(credentials.CONSUMER_KEY, credentials.CONSUMER_SECRET) auth.set_access_token(credentials.ACCESS_TOKEN, credentials.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) user_tweets = api.user_timeline(count=50) return user_tweets -
How can I add an instruction after an object creation in Django CreateView?
On my generic class based CreateView, I would like to perform an instruction which creates new objects from another model related to the current created object. Example: Collection is a model which is related to 3 differents Element objects. When I create a MyCollection object, which is related to a Collection and a User, 3 MyElement object must be created too and related to the newly created MyCollection object. One for each Element related to Collection. # models.py from django.contrib.auth.models import User from django.db import models class Collection(models.Model): # attributes and methods... class Element(models.Model): collection = models.ForeignKey(Collection, # more arguments...) # more attributes and methods class MyCollection(models.Model): user = models.ForeignKey(User, # more arguments...) collection = = models.ForeignKey(Collection, # more arguments...) # more attributes and methods def get_absolute_url(self): reverse(# some url with the object pk) class MyElement(models.Model): element = models.ForeignKey(Element, # more arguments...) my_collection = models.ForeignKey(MyCollection, # more arguments...) # more attributes and methods I'm using the generic CreateView from Django and after a little bit of research, I saw that it was possible to perform additional actions in the CreateView by overriding the get_success_url() method. In my example, I did something similar: # views.py from django.views.generic import CreateView from .utils … -
Django Background Image Not Working How To Fix?
I am trying to make my background image for a website I am working on but when ever I try to make it, it appears white for that page image < as you can see the page just shows white I am not sure why it happens when ever I try to add a pg image My Home Page The background line of code is the first 2 line of code <head> <style type="text/css"> body { background-image: url("ok.png"); } .sidenav2 h1 { margin-top: 190px; margin-bottom: 100px; margin-right: 150px; margin-left: 350px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav3 h1 { margin-top: -125px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav4 h1 { margin-top: -128px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav5 h1 { margin-top: 328px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav6 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav7 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } </style> </head> < … -
Why I`m getting OSError: [Errno 7] Argument list too long: b'/usr/local/bin/git'?
I'm doing a programming course (CS50W) and it has a command to submit the project to github automatically. It's called submit50. When trying to push my code to github through this method, I do: submit50 --verbose web50/projects/2020/x/capstone And I'm getting the following error: OSError: [Errno 7] Argument list too long: b'/usr/local/bin/git' I have literally no idea what is happening here. If you could help me out I would be grateful. Full error with traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/bin/submit50", line 11, in <module> load_entry_point('submit50==3.0.2', 'console_scripts', 'submit50')() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/submit50/__main__.py", line 147, in main user_name, commit_hash, message = lib50.push("submit50", args.slug, CONFIG_LOADER, prompt=prompt) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 69, in push with authenticate(remote["org"], repo=repo) as user, prepare(tool, slug, user, included): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 326, in prepare _run(git(f"add -f {' '.join(shlex.quote(f) for f in included)}")) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 703, in _run with _spawn(command, quiet, timeout) as child: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__ return next(self.gen) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/lib50/_api.py", line 674, in _spawn child = pexpect.spawn( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 205, in __init__ self._spawn(command, args, preexec_fn, dimensions) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 303, in _spawn self.ptyproc = self._spawnpty(self.args, env=self.env, File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pexpect/pty_spawn.py", line 315, in _spawnpty return ptyprocess.PtyProcess.spawn(args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ptyprocess/ptyprocess.py", line … -
Does django testing have a breakDown() similar to setUp() that is ran after all tests complete?
I am running some tests in django but they depend on a response from an outside service. For instance, I might create a customer and wish to acknowledge it has been created in the outside service. Once I am done with testing I want to remove any test customers from the outside service. Ideally, there would be a method similar to setup() that runs after all tests have completed. Does anything like this exist? -
Django - Inserting initial value into ModelChoiceField
Let's go. So I have this site where users' first step is to register their company. The models.py of company is like this: class Company(models.Model): companyId = models.CharField(unique=True, max_length=20, primarykey=True) ...morefields... The forms.py is like this: class CompanyForm(forms.ModelForm): companyId = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Company ID'})) ...morefields... class Meta: model = Company fields = ('companyId', ...fields n fields...) And there's the views.py to register the company def registerCompany(request): context = {} company_form = CompanyForm(request.POST or None) if company_form.is_valid(): request.session['companyId'] = company_form.cleaned_data['companyId'] obj = company_form.save() obj.save() company_form = Company() return redirect("/accounts/register") context['company_form'] = company_form return render(request, 'register-company.html', context) In the views.py above, the companyId is being stored using sessions, it will be used later. After registering the company it's time to register the employee, which is presumed to be someone on the company's staff. The employee app is a custom user. This is how the employee models.py looks like: Class Employee(AbstractBaseUser, PermissionsMixin): ...fields n fields... company = models.ForeignKey(Company, default=None, blank=True, null=True, on_delete=models.CASCADE) ...custom user stuff... ps: Custom User is working fine, the problem doesn't seem to be related to this The Employee's forms.py: class RegistrationForm(UserCreationForm): company = forms.ModelChoiceField(initial='class', queryset=Company.objects.all()) class Meta: model = Employee fields=(fields n fields, "company") ps: these 'fields n fields' all have … -
The view profiles.views.ProfileDetailComment didn't return an HttpResponse object. It returned None instead
I am trying to process a form in generic detail view. I am using this django doc to make this view. In this view I am showing all the info and post by the profile model. and anyone visiting this profile can comment on the post of this profile Here is my view: from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.generic import DetailView, RedirectView, UpdateView, FormView from django.views.generic.detail import SingleObjectMixin from .models import Profile from posts.forms import PostModelForm, CommentModelForm from posts.models import Post from relationships.models import Relationship User = get_user_model() class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile slug_field = "slug" slug_url_kwarg = "slug" form_class = CommentModelForm queryset = Profile.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) sender_profile = get_object_or_404(Profile, id=self.request.user.id) receiver_profile = get_object_or_404(Profile, id=self.object.id) frnd_btn_state = Relationship.objects.relation_status( sender=sender_profile, receiver=receiver_profile, ) context['frnd_btn_state'] = frnd_btn_state context['frnd_req_rcvd'] = Relationship.objects.invitation_recieved( receiver = sender_profile ) context['form'] = CommentModelForm() return context class ProfilePostComment(SingleObjectMixin, FormView): template_name = 'profiles/profile_detail.html' form_class = CommentModelForm model = Profile def post(self, request, *args, **kwargs): comment_form = CommentModelForm() profile=Profile.objects.get(user=request.user) if 'submit_c_form' in request.POST: comment_form = CommentModelForm(request.POST or None) if …