Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom validation AFTER to_internal_value
I am doing a business logic heavy project and uncertainty of data passed to validate function adds unnecessary extra work. For example I am not sure about date formats and ids/objects in PrimaryKeyRelatedFields Is there any way to run validations after converting fields to internal values? -
Django - Populating Edit/Update Form With an Object's Preexisting Data
I have an edit/update values form in Django, in which you need to choose the object you want to change its details from a drop down menu and then enter the new information you wanted to edit/update. When you choose an object from the dropdown menu the form looks like this: I am trying to populate the edit form with the pre existing fields of the object that I chose from the dropdown menu to make it easier to make changes. it should look like this screenshot: Any ideas how I can achieve that? Views.py Code: def tasks(request): if request.user.is_superuser: context = { 'tasks':Task.objects.all(), 'title': 'Tasks', 'addForm':AddNewTask(prefix = 'add'), 'editForm':EditTask(prefix = 'edit'), } else: context = { 'tasks':Task.objects.filter(created_by=request.user), 'title': 'Tasks', 'addForm':AddNewTask(prefix = 'add'), 'editForm':EditTask(prefix = 'edit'), } if request.method =='POST': if 'addNew'in request.POST: addForm = AddNewTask(request.POST,prefix = 'add') if addForm.is_valid(): task = addForm.save(commit=False) task.created_by = request.user task.save() messages.success(request, f' Task Created Successfully ') else: messages.warning(request, 'Something Went Wrong !') elif 'editExisting' in request.POST: editForm = EditTask(request.POST,prefix = 'edit') if editForm.is_valid(): taskID = editForm.cleaned_data['existing_task'].id new_title = editForm.cleaned_data['title'] new_desc = editForm.cleaned_data['description'] new_status = editForm.cleaned_data['status'] object = Task.objects.get(id=taskID) object.title = new_title object.description = new_desc object.status = new_status object.save() messages.success(request, f'Task #{taskID} Has Been … -
ImportError: cannot import name 'gTTS' from 'gtts'
I want to use the gtts library over my django project so i also installed django-gtts. The command "from gtts import gTTS" runs fine when I run it in a virtual environment in an empty folder, but the moment i install Django or django-gtts it starts giving me the error ImportError: cannot import name 'gTTS' from 'gtts' (/Users/amay/Desktop/untitled folder 2/tts/lib/python3.10/site-packages/gtts/__init__.py) asgiref==3.4.1 certifi==2021.10.8 charset-normalizer==2.0.10 click==8.0.3 Django==4.0.1 Django-Gtts==0.4 gTTS==2.2.3 idna==3.3 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 urllib3==1.26.8 These are all the Dependencies in my Project and i am Running it on my Mac OS System. What can be the possible error? Is the gTTS module conflicting with some other dependency? -
GeoDjango Admin displaying openlayers map instead of open street map in Admin
i am have enabled everything needed to work with spatial data at the database and django setting level, my profile model has a default_location field that is a PointField. as shown below. from django.contrib.gis import models class Profile(models.Model): ... default_location = models.PointField() i registered the profile model as an inline to be viewed and edited from within a User model (one-to-one relationship between user and profile).code shown below class ProfileInline(StackedInline): model = models.Profile class NewUserAdmin(admin.GISModelAdmin): gis_widget = OSMWidget inlines = [ProfileInline] admin.site.unregister(models.User) admin.site.register(models.User, NewUserAdmin) however i keep getting a openlayer map in my django admin page please can anyone suggest a fix to this. i need open street map because of it detailed street feature. -
Django submitting two forms cannot assign instance error
I have the following models/forms/view in which I have managed to submit to two different models as follows: Models class Account(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) actflag = models.CharField(max_length=1, blank=True) acttime = models.DateTimeField(blank=True, null=True) comments = models.TextField(_('comments'), max_length=500, blank=True) def __str__(self): return self.name class ISIN(models.Model): code = models.CharField(max_length=12) account_name = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) actflag = models.CharField(max_length=1, blank=True) acttime = models.DateTimeField(blank=True, null=True) def __str__(self): return self.code Forms from apps.portfolio.models import Account, ISIN class PortfolioForm(forms.ModelForm): class Meta: model = Account fields = ['name', 'comments'] class IdentifierForm(forms.ModelForm): class Meta: model = ISIN fields = ['code'] View def portfolios(request): if request.user.is_authenticated: if request.POST: fm = PortfolioForm(request.POST) fm2 = IdentifierForm(request.POST) if fm.is_valid(): messages.success(request, 'Portfolio has been created.') account = fm.save(commit=False) account.username = request.user account.acttime = timezone.now() account.actflag = 'I' account.save() isin = fm2.save(commit=False) #isin.account_name = account.name isin.acttime = timezone.now() isin.actflag = 'I' isin.save() return redirect('portfolios') else: fm = PortfolioForm() fm2 = IdentifierForm() context = {"name": request.user, "form": fm, "form2": fm2} return render(request, 'portfolios.html', context) else: return redirect('login') However, you will notice the commented line in my view: isin.account_name = account.name, when I uncomment this line and try to submit the forms again I get the following error: Cannot assign "'test'": "ISIN.account_name" must … -
Django not logging all errors on production
My Django app is locally properly logging and emailing errors. However, on production, I'm only getting 'Invalid HTTP_HOST header' errors in both the log file and my inbox. Every other error is not logged in the django log nor is it emailed to me. I'm not sure what could cause this or how to continue investigating the issue. I've tried some things with this test request: def test(request): logging.debug('debug test message') // Appears in log file from django.core.mail import mail_admins mail_admins('test error', 'test error via call to mail_admins()') // Arrives in my inbox raise Appointment.DoesNotExist // On production, Does not appear in log file or in inbox. Behaves as expected locally. Could it possibly be something to do with directory and file permissions? I would expect logging not to work at all in that case. My logging settings for both local and production: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, 'csv_formatter': { 'format': '%(levelname)s;%(asctime)s;%(message)s' } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 1024 … -
Django testing of views.py and model.py
I am new to django testing am doing the testing for my views.py file which cintain alot oif classes Here we are take one of the class among the others the views.py file looks like class AssignSubFarmer(viewsets.ViewSet): permission_classes = [permissions.AllowAny] http_method_names = ['patch', 'post'] serializer_class = BatchSerializer queryset = Farm.objects.all() def create(self, request, *args, **kwargs): header = {'Content-Type': 'application/json', 'Authorization': request.headers['Authorization']} farm_id = request.data.get('farm_id', None) batch_id = request.data.get('batch_id', None) subfarmer_id = request.data.get('user_id', None) mobile = request.data.get('mobile', None) name = request.data.get('name', None) document_photo = request.data.get('document_photo', None) user_type = request.data.get('user_type', None) aadhar_number = request.data.get('aadhar_number', None) pancard = request.data.get('pancard', None) voter_id = request.data.get('voter_id', None) gst_no = request.data.get('gst_no', None) primary_user_id = request.data.get('primary_user_id', None) if not subfarmer_id: payload = { "name": name, "mobile": mobile, "document_photo": document_photo, "user_type": user_type, "aadhar_number": aadhar_number, "pancard": pancard, "voter_id": voter_id, "gst_no": gst_no } response = requests.post(url=settings.CREATE_SUB_FARMER.format(primary_user_id), data=json.dumps(payload), headers=header) data = json.loads(response.content) secondary_user_id = None if not data['error'] and data['data']: secondary_user_id = data['data'].get('secondary_user_tbl_id', None) else: return Response({"message": data['message'], "error": data['error']}, status=status.HTTP_200_OK) subfarmer_id = 0 if secondary_user_id: subfarmer_id = secondary_user_id if farm_id and subfarmer_id: Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id) elif batch_id and subfarmer_id: Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id) elif farm_id: Batch.objects.filter(farm_id=farm_id).update(sub_farmer_id=subfarmer_id) elif batch_id: Batch.objects.filter(id=batch_id).update(sub_farmer_id=subfarmer_id) return Response({"message": "Successfully updated", "error": "False"}, status=status.HTTP_200_OK) and when I am doin the testing for this class … -
How to render Django template after ajax call
Iam Building a application that renders a group of cards based on options clicked by user, iam using ajax on option click so that cards appear without page reload,but the problem is i cannot render the cards into my page,iam passing calculated values to frontend as django context using return render(request,'base.html',{'context':context}) Ajax: <script > function sendData(date){ $.ajax({ type : "POST", url: "", data: { date : date, csrfmiddlewaretoken:'{{ csrf_token }}', click:'click' }, }); return false; } view.py: def datepicker(request): if 'click' in request.POST: return render(request,'datepicker.html',{'dates':availabe_dates,'time':time}) return render(request,'datepicker.html',{'dates':availabe_dates,'time':['choose a date']}) I have tried giving: <div class="card-body"> {% for t in time %} <p>{{t}}</p> {% endfor %} </div> Only choose a date is shown instead of cards.I am sure that if 'click' in request.POST: is runned as i have tried giving some print statements Please Help as iam new to Ajax and Django -
I get 400 bad request when refreshing django-simple-jwt token
I am getting 400 bad request when I request a new token. It throws an error saying that refresh field is required. my code: export const refreshToken = (token) => { let object = { refresh: token, }; return (dispatch) => { api .post(TOKEN_REFRESH_ENDPOINT, object) .then((response) => { dispatch(refreshSuccess(response.data)); }) .catch((error) => { dispatch(refreshFail(error.message)); }); }; }; React.useEffect(() => { let refreshToken = Cookies.get(TOKEN_REFRESH_NAME); let timer = setTimeout( () => dispatch(action.account.refreshToken(refreshToken)), 2 * 1000 ); return () => { clearTimeout(timer); }; }, [dispatch]); What am I doing wrong? -
Django form with formset between three models
I have three models: Experiment, Label and LabelMappings while LabelMappings is connecting Devices with Labels. I want to create ExperimentForm but don't know how to add Label field to it using inline formset. I am using ClassBasedViews but couldn't figure out how to save Labels and build this relationship in backend class Experiment(models.Model): name = models.CharField(max_length=255) comment = models.TextField(blank=True, null=True) class Label(models.Model): name = models.CharField(max_length=255) comment = models.CharField(max_length=255, blank=True, null=True) class LabelMappings(models.Model): experiment = models.OneToOneField(Device, models.DO_NOTHING) label = models.ForeignKey(Location, models.DO_NOTHING) I thought about somethinglike LabelMappingFormSet = inlineformset_factory(Experiment, LabelMapping, form=LabelMappingForm, extra=1 ) LabelFormSet = inlineformset_factory(LabelMappingForm, Label, form=LabelForm, extra=1 ) but i didn't work out. -
How to capture "close browser windows" and then update a DataBase item with Django?
first of all happy new year! I am starting to learn Django, sorry if the question is too obvious. Context: I have a web aplication in Django, this aplication is a dashboard where the users can verify and validate the recognition made by an AI of each part of an invoice (prices, taxes...). The user can manually review this recognition and consequently validate if everything is correct. Situation: Now when a user to do click on the verify button redirect to another view. This new view is a Django template with a iframe. This Django view executes a function which update the status of the item to '31.Verificando usuario' in the DB. urls.py: path('verification/<int:id>/', views.VerificationPage, name="fci-verification" ) views.py: def VerificationPage (request, id): invoice= Invoice.objects.get(id=id) url= invoice.verification_url invoice_id = invoice.id status = '31.Verificando usuario' message = _('Invoice in web verification') try: change_invoice_status(invoice_id, status, message) except Exception as e: capture_exception(e) return render(request, "fci_verification.html", {'verification_url': url,'invoice_id': id}) When this user click on "verified" into iframe, I catch this event with window.addEventListener("message", receiveMessage, false); and update to new status. Problem: If the user close tab or browser, item status stays as "31.Verificando usuario" and another user cannot review this invoice. **How can I capture … -
How to get maximum value of each day in month using django queryset
Let's assume I have Model, Products and I have 100k records. Now I want to pass month 2022-01-01 and get maximum price of each day of the passed month. Product Model id price date 1. 33.33 2022-01-01 2. 93.33 2022-01-01 3. 64.33 2022-01-02 4. 34.33 2022-01-02 . . . 101. 43.33 2022-01-29 102. 74.33 2022-01-30 103. 36.33 2022-01-30 Expecting Result 93.33 64.33 . . . 43.33 74.33 I just want queryset. Kindly try avoid loop. -
G Suite - django social auth redirecting to accounts/login
I have configured social-auth-django for my project. And in G suite, I have done all the setup for third party SAML authentication (SSO). The problem is after completing the Google authentication it is redirecting to accounts/login/ instead of the configured redirect URL. # Social Auth settings AUTHENTICATION_BACKENDS = [ 'social_core.backends.saml.SAMLAuth', 'django.contrib.auth.backends.ModelBackend', 'users.auth.backend.CaseInsensitiveModelBackend', ] SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'https://example.com/home' # Overriding pipeline to skip user auto registration # since we have automatic user provisioning enabled SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Package verions: social-auth-app-django==5.0.0 social-auth-core==4.1.0 python3-saml==1.12.0 Django==3.0.5 Anyone have any idea on this? Thank you -
Update a field but do not replace the old one in django rest framework
I have a barcode field in a model. While updating i do not want to replace with old one instead i want to add the new one and keep the old one also and while getting the data latest one will be visible. For example barcode contains B001 in that model and i updated with B002. So it will not replace B001. It will keep both B001 and B002. I am really curious how to achieve this. Any help would be really appreciated. -
I can't login with facebook after in django
After i hosted my app in heroku when i click on login with facebook it throws me an error saying: ProgrammingError at /oauth/complete/facebook/ relation "social_auth_usersocialauth" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "social_au... Request Method: GET Request URL: https://zu4.herokuapp.com/oauth/complete/facebook/? granted_scopes=public_profile&denied_scopes&code=AQBjAKGr1DmC3xKRUcPBZw8t_aS77an_AmwYItJ- qCQyhEjxnxTmnwLNNLISHIGhOlV9LMCRX72- YjBt7Oiaa3zRO56QTqpQZVHL_3OwF6xQMbDOsc0_S8XvogqboLykuQ7O2P7_jtlnV1g4wqZ0Ktlg7feUsQMeWzNwILpHfcdVx9ZAVkB-qamP42ae0iN3mKePBdoIIaD_4ES_0aEhlS47VDXKHRFTmBnyWNpr1J6oWtVby184FTXvY3X7nxzIvhDVFrueCdAoJ8MhxU- nFiPdzfHMwBcyoaNq67a564MdadIMledAFbDdvq0vfG6xuA15X5HVGq9nIyocGBjmtRZBeQc25nNCmXLhDOFq9a- bJBzGQIsFSvahjHQxV2lnNFY&state=oqiCjnfkDTr208JjRHj2mBUdpgVMsPnZ Django Version: 4.0 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #Scial liogin Module 'social_django', #My App Module 'itouch', #Bootstrap Module 'bootstrap5', #cloudinary Module 'cloudinary', ] Any help please ? -
javascript afterprint event works once
I need to carry out my own procedure after calling up the print function of the browser. The only problem is that it only runs it once. I'm using JQuery and Sweetalert2. Below is the source code: window.onafterprint = function () { location.href = '{% url 'logout_' %}'; } Swal.fire({ title: 'Example', showDenyButton: true, showCancelButton: true, confirmButtonText: 'Yes', confirmButtonColor: 'green', denyButtonText: 'No', cancelButtonText: 'Cancel' }).then((result) => { if (result.isConfirmed) { flPrint = true; } else if (result.isDenied) { flPrint = false; } if ((result.isConfirmed) || (result.isDenied)) { $.ajax({ url: '{% url 'ajax-view' %}', dataType: 'json', contentType: "application/json", type: 'GET', success: function (r) { if (r.result) { if (flPrint) { window.print(); } else { location.href = '{% url 'logout_' %}'; } } }, error: function (err) { console.log(err); } }); } }) What can I do to make the afterprint() event always run? Thanks. -
convert oracel query into django
Query: select t1.a, t2.b, t3.c, t2.f from t1 t2 t3 where t1.b=t2.c and t1.c=t3.a and t2.b=t3.c t1, t2, t3, t4 represent tables a,b,c are values -
Running heroku local results in SyntaxError: invalid syntax
When I run heroku local in terminal it throws this error: 22:01:24 web.1 | File "manage.py", line 17 22:01:24 web.1 | ) from exc 22:01:24 web.1 | ^ 22:01:24 web.1 | SyntaxError: invalid syntax [DONE] Killing all processes with signal SIGINT 22:01:24 web.1 Exited with exit code null I am following this tutorial. Not sure if it helps but here is my Procfile contents: web: python manage.py runserver 0.0.0.0:$PORT My Python version is 3.9.9 -
How do i fix Exception Type:OperationalError Exception Value:no such table: home_user
from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils.html import escape, mark_safe from embed_video.fields import EmbedVideoField class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_teacher', True) other_fields.setdefault('is_learner', True) other_fields.setdefault('is_admin', True) if other_fields.get('is_teacher') is not True: raise ValueError( 'admin must be assigned to is_teacher=True.') if other_fields.get('is_learner') is not True: raise ValueError( 'admin must be assigned to is_learner=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True,default="") first_name = models.CharField(max_length=150, blank=True) about = models.TextField(( 'about'), max_length=500, blank=True) is_learner = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def str(self): return self.user_name Admin from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.forms import TextInput, Textarea from .models import User,Profile,Announcement,Course,Tutorial,Notes,Quiz,Answer,Learner,Instructor,TakenQuiz,LearnerAnswer class UserAdminConfig(UserAdmin): model = User search_fields = ('email', 'user_name', 'first_name',) list_filter = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') ordering = ('-start_date',) list_display = ('email', 'user_name', 'first_name', 'is_teacher', 'is_learner') fieldsets = ( (None, {'fields': ('email', 'user_name', 'first_name',)}), … -
How can I do JavaScript ajax call on page onload and retrieve data from views in Django
I wish to pass localStorage data to Django views and display the return record on page template on page load. I think it can be done with Ajax, but I have no Idea how I can pass specific localStorage variable to Django views on specific pageload and display the record on template as regular templating(not ajax html return) For example: If I load abcd.com/test URL, I want to pass an array of ids or something of a Variable, and return views on template according to passed values. Is there any better way of achieving this ? I have tried this way but no luck: Javascript: <script> window.onload = function(){ var compare = localStorage.getItem("comparisionProducts"); var action_url =$this().window.location.href if (compare.value !== ''){ $.ajax({ url: action_url, type: "POST", data: {'compare_id': compare }, headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function (result) { console.log("Success") }, error: function () { alert("Please login"); } }); } }; <script> and My Views: def compare(request): if request.is_ajax() and request.POST and 'compare_id' in request.POST: data = Products.objects.filter(product_id = int(request.POST['compare_id'])) context={ 'product':product, } return render (request, './ecommerce/compare.html', context) -
Temporary model instances referenced as foreign keys
Is there a way to keep a Django model instance, which is referenced by foreign keys, in memory without storing it to the database? The code is part of an _add_ overload, but the way it is implemented now is very ugly as it is hard to keep track of the new instances, and it also produces a lot of unnecessary DB accesses. Ideally I want to keep the new instances temporary as long as the user does not call the save() method on the returned instance. When I uncomment the save() calls like below, the annotation instances are not referenced in the returned Sequence instance. class Sequence(models.Model): ... def __add__(self, other:'Sequence'): """ This enables you to use the + operator when dealing with Sequence objects :param other: :return: """ # concatenate the actual sequences sum_seq.sequence = self.sequence + other.sequence #sum_seq.save() len_self_seq = len(self.sequence) # annotations annot: SequenceAnnotation # copy the own anntotations for annot in self.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None # this is crucial to actually create a new instance new_annot.ref_sequence = sum_seq #new_annot.save() if other_is_bioseq: # copy the other annotations, adjust the start and end positions for annot in other.annotations.all(): new_annot = deepcopy(annot) new_annot.id = None … -
How can I get a object for a specific user?
I'm trying to display all the Books issued by a user. In my views im trying to get the IssueBook model's objects (only with the current user), The Book is just working fine, having trouble with IssueBook model- views.py def booksIssued(request): issued = IssueBook.objects.filter(user=request.user) books = Book.objects.filter(issued=True, user=request.user) print(issued, books) context = { "books" : books, "issued" : issued } return render(request, 'books_issued.html', context) models.py class IssueBook(models.Model): name = models.CharField(max_length=400) classSection = models.CharField(max_length=10) rollno = models.PositiveIntegerField() issued_date = models.DateTimeField(auto_now_add=True) date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return f"{self.book} issued by {self.name}" forms.py class issueBook(ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('usr') super(ModelForm, self).__init__(*args, **kwargs) self.fields['book'] = forms.ModelChoiceField(queryset=Book.objects.filter(user = user)) date = forms.DateTimeField(widget=forms.DateInput(attrs={'type':'date'})) class Meta: model = IssueBook fields = ['name', 'classSection', 'book', 'rollno', 'date'] -
Django odd behaviour
Whenever I start a project in Django, independently of the name of the app or project, and irrespective of any urls or settings configuration, upon running python manage.py runserver and navigating to 127.0.0.1 I get the following error: Not Found: /ball/ [10/Jan/2022 11:32:32] "GET /ball/ HTTP/1.1" 404 2337 and this displays in th browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ball/ Using the URLconf defined in ornaments.urls, Django tried these URL patterns, in this order: admin/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, ball/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Why is Django looking for a route called ball? Thanks. -
Mock async_task of Django-q
I'm using django-q and I'm currently working on adding tests using mock for my existing tasks. I could easily create tests for each task without depending on django-q but one of my task is calling another async_task. Here's an example: import requests from django_q.tasks import async_task task_a(): response = requests.get(url) # process response here if condition: async_task('task_b') task_b(): response = requests.get(another_url) And here's how I test them: import requests from .tasks import task_a from .mock_responses import task_a_response @mock.patch.object(requests, "get") @mock.patch("django_q.tasks.async_task") def test_async_task(self, mock_async_task, mock_task_a): mock_task_a.return_value.status_code = 200 mock_task_a.return_value.json.return_value = task_a_response mock_async_task.return_value = "12345" # execute the task task_a() self.assertTrue(mock_task_a.called) self.assertTrue(mock_async_task.called) I know for a fact that async_task returns the task ID, hence the line, mock_async_task.return_value = "12345". However, after running the test, mock_async_task returns False and the task is being added into the queue (I could see a bunch of 01:42:59 [Q] INFO Enqueued 1 from the server) which is what I'm trying to avoid. Is there any way to accomplish this? -
I am trying to register a staff in my database throuout the form But I get error
I have two models staff and UserAddress and I'm trying to add the staff through models. But I get this error: AttributeError at /accounts/signup/staff/ 'NoneType' object has no attribute 'add' What should I do now, Could some one help me? I wanted to register a staff but this thing happened. models.py: class UserAddress(models.Model): city = models.CharField(max_length=100) address = models.CharField(max_length=200) zip_code = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.id) class CustomUser(AbstractUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) user_address = models.ForeignKey(UserAddress, on_delete=models.CASCADE, null=True) class Staff(CustomUser): def save(self, *args, **kwargs): if not self.id: self.is_staff = True self.is_superuser = False return super(Staff, self).save(*args, **kwargs) class Meta: proxy = True forms.py: class StaffCreationForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) email = forms.EmailField(required=True) city = forms.CharField(max_length=100) address = forms.CharField(max_length=100) zip_code = forms.CharField(max_length=15, required=True) class Meta(UserCreationForm.Meta): model = CustomUser @transaction.atomic def save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get("first_name") user.last_name = self.cleaned_data.get("last_name") user.email = self.cleaned_data.get("email") user.is_staff = True user.save() address = UserAddress.objects.create(city=self.cleaned_data.get("city"), address=self.cleaned_data.get("address"), zip_code=self.cleaned_data.get("zip_code")) user.user_address.add(address) return user views.py: class StaffSignUpView(CreateView): model = CustomUser form_class = StaffCreationForm template_name = "accounts/signup_user.html" def get_context_data(self, **kwargs): kwargs["user_type"] = "staff" return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect("home")