Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sitemap Error: 'datetime.time' object has no attribute 'timetuple'
I am using django's built-in sitemap feature to dynamically create sitemap. But I am keep getting this error, and I don't know why? Please help me... Traceback: File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 16, in inner response = func(request, *args, **kwargs) File "/home/fancychamps/Django Projects/EduwizardTutorials/EWTEnv/lib/python3.5/site-packages/django/contrib/sitemaps/views.py", line 77, in sitemap else site_lastmod.timetuple() AttributeError: 'datetime.time' object has no attribute 'timetuple' My Code: class NoteClassSitemap(sitemaps.Sitemap): priority = 0.5 changefreq = 'monthly' def items(self): return Classes.objects.all().order_by('-date') def lastmod(self, obj): return obj.date -
Django - compare user objects by field
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
Unable to render the data from models to view in django framework
When i try to run a server,I am getting an error where it shows TypeError: 'Organization' object is not iterable. I am attaching the Model and views for the reference.Can you check and determine why i am getting the error. ''' Model.py from django.db import models # Create your models here. class Organization(models.Model): name = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Ticket_status(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): ticket_id = models.CharField(max_length=200, unique=True) orgname = models.ForeignKey(Organization, null=True, on_delete=models.SET_NULL) status = models.ForeignKey(Ticket_status, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.ticket_id ''' views.py ''' ----------- from django.shortcuts import render from django.http import HttpResponse from.models import * # Create your views here. def organization(request, orgname): organization_name=Organization.objects.get(id=orgname) organization_count=Organization.objects.get(id=orgname).ticket_set.all() return render(request,'ticket\organization1.html',{'organization_name':organization_name,' organization_count': organization_count}) ''' -
Django post save signal not updating the database
Im not getting why this signal is not working. This same code worked once but after that i deleted the objects from admin and ran it again and it stopped working. @receiver(post_save, sender=FinancePending) def calcualate_FinancePending(sender, instance, created, **kwargs): amount_paid = FinancePending.objects.values_list('amountPaid', flat=True) amount_paid = list(amount_paid) total_amount = FinancePending.objects.values_list('TotalAmount', flat=True) total_amount = list(total_amount) # total - paid TotalFee = [int(s.replace(',', '')) for s in total_amount] AmountPaid = [int(s.replace(',', '')) for s in amount_paid] finance_pending = FinancePending.objects.all() i = 1 while i <= len(TotalFee): amount_pending = TotalFee[i-1] - AmountPaid[i-1] amountpending = FinancePending.objects.filter(invoiceNumber=i) amountpending.AmountPending = amount_pending i = 1 + i -
one variable show other not, when pass post ajax in django
I don't Why I get this error, TypeError: 'method' object is not subscriptable same thing I used in another post request ajax I got all variable. but here I only get frm variable but not pk . HTML <form id="message-form" action="message/message_form/" user_id="{{u.id}}" method="POST"> {% csrf_token %} <div class="container"> <div class="row"> <div id="text" class="col-10"> {{ msgform.text }} </div> <div class="col-1"> <button id="submit" class="btn" type="submit"><img height="30px" src="/static/img/send-button.png" alt="send"></button> </div> </div> </div><br> </form> Script <script type="text/javascript"> var frm = $('#message-form'); var id; id = frm.attr("user_id"); frm.submit(function () { $.ajax({ type: frm.attr("method"), url: frm.attr("action"), dataType: 'json', data: { csrfmiddlewaretoken: "{{ csrf_token }}", pk:id, frm:frm}, error: function(data) { // $("#MESSAGE-DIV").html("Something went wrong!"); } }); return false; }); </script> views.py def post(self, request): new_msg = request.POST.get('text') print(new_msg) form = MessageForm() //I GET ERROR HERE MY PK VARIBLE NOT PRESENT IN REQUEST POST print('request.id is here',request.POST.get['pk']) u = get_object_or_404(User,pk=request.POST['pk']) msg = message.objects.filter(sender=request.user).filter(receiver=u).all() | message.objects.filter(sender=u).filter(receiver=request.user).all() if form.is_valid(): smg = form.save(commit=False) smg.sender = request.user smg.receiver = u smg.save() if request.user != u and User.objects.filter(receiver__receiver=u,receiver__read=False).exists: notify.send(request.user, recipient=u, verb="message you please read in message box",public=False) msg = message.objects.filter(sender=request.user).filter(receiver=u).all() | message.objects.filter(sender=u).filter(receiver=request.user).all() data = { "messages":msg} return HttpResponse(json.dumps(data), content_type='application/json') -
Django Wizard form with custom template
This is my wizard view: <div class="outer-panel"> <div class="outer-panel-inner"> <div class="process-title"> <h2 id="step-title-1" class="step-title is-active">Tell us more about you.</h2> <h2 id="step-title-4" class="step-title">Secure your account.</h2> </div> <form method="POST"> {% csrf_token %} {{ wizard.management_form }} {{ wizard.form.media }} <div id="signup-panel-1" class="process-panel-wrap is-narrow is-active"> <div class="form-panel"> <div class="field"> <label>First Name</label> <div class="control"> {{ form.f_name}} </div> </div> <div class="field"> <label>Last Name</label> <div class="control"> {{ form.l_name}} </div> </div> <div class="field"> <label>Email</label> <div class="control"> {{ form.email}} </div> </div> </div> <div class="buttons"> {% comment %} <a class="button is-rounded process-button" name="wizard_goto_step" data-step="step-dot-1">Back</a> {% endcomment %} <a class="button is-rounded process-button is-next" name="wizard_goto_step" data-step="step-dot-4">Next</a> </div> </div> <div id="signup-panel-4" class="process-panel-wrap is-narrow"> <div class="form-panel"> <div class="field"> <label>Password</label> <div class="control"> {{ form.password}} </div> </div> {% comment %} <div class="field"> <label>Repeat Password</label> <div class="control"> <input type="password" class="input" placeholder="Repeat your password"> </div> </div> {% endcomment %} <div class="field"> <label>Phone Number</label> <div class="control"> {{ form.phone}} </div> </div> </div> <div class="buttons"> <a class="button is-rounded process-button" data-step="step-dot-1">Back</a> {% comment %} <a class="button is-rounded process-button is-next" data-step="step-dot-5">Next</a> {% endcomment %} </div> </div> {% comment %} {% else %} {{ wizard.from }} {% endcomment %} </form> </div> </div> Form View: from django import forms class ContactForm1(forms.Form): f_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs= { 'class': 'input', 'placeholder':'Enter First Name' })) l_name = forms.CharField(max_length=100,widget=forms.TextInput(attrs= { … -
How do I unit-test my Google Social Log-in View?
I have been wondering how I can test my custom Google social login view for my django project. Below is my views.py import json import ast import httplib2 import google.oauth2.credentials import jwt import requests from google.oauth2 import id_token from django.shortcuts import render from django.views import View from django.http import JsonResponse from apiclient import discovery from oauth2client import client from pinterrorist.settings import SECRET_KEY from .models import User, Social, Follow class GoogleLoginView(View): def post(self, request): token = request.headers["Authorization"] url = 'https://oauth2.googleapis.com/tokeninfo?id_token=' response = requests.get(url+token) user = response.json() if User.objects.filter(social_id = user['sub']).exists(): user_info = User.objects.get(social_id=user['sub']) encoded_jwt = jwt.encode({'id': user["sub"]}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : user['name'], 'user_pk' : user_info.id }, status = 200) else: new_user_info = User( social_id = user['sub'], username = user['name'], social_service = SocialPlatform.objects.get(name = "google"), email = user.get('email', None) ) new_user_info.save() encoded_jwt = jwt.encode({'id': new_user_info.id}, SECRET_KEY, algorithm='HS256') return JsonResponse({ 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : new_user_info.username, 'user_pk' : new_user_info.id }, status = 200) and below is my test.py code so far... from django.test import TestCase, client from .models import User class GoogleLoginTest(TestCase): def setUp(self): client = Client() User.objects.create(username='john', social_service_id=1) def tearDown(self): User.objects.last().delete() def test_get_user_view(self): response = self.client.get('account/google') self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), { 'access_token' : encoded_jwt.decode('UTF-8'), 'username' : new_user_info.username, 'user_pk' … -
Django rest framework, create Foreign key object
I have the following models in my API: class Message(models.Model): sender = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) sent_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='sent_to') sent_at = models.DateTimeField(default=timezone.now) subject = models.CharField(max_length=120, help_text='Message subject is limited to 120 characters') content = models.TextField(validators=[validate_message_content], help_text="Message Body") def __str__(self): return f"{self.subject} : \n {self.content} " class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=120) email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] messages = models.ForeignKey(related_name='messages', on_delete=models.CASCADE, to=Message, null=True ) def __str__(self): return f"{self.username}" def read(self): self.last_read_date = timezone.now() self.save() And the serializers: class MessageSerializer(ModelSerializer): class Meta: model = Message fields = ('subject', 'sent_to', 'content') class UserSerializer(HyperlinkedModelSerializer): messages = MessageSerializer(many=True) url = HyperlinkedRelatedField(view_name='UserViewSet', read_only=True) class Meta: model = User fields = ( FieldsConsts.URL, FieldsConsts.EMAIL, FieldsConsts.FIRST_NAME, FieldsConsts.LAST_NAME, FieldsConsts.PASSWORD, FieldsConsts.MESSAGES ) extra_kwargs = {FieldsConsts.PASSWORD: {SerializerFields.WRITE_ONLY: True}, FieldsConsts.SENDER: {SerializerFields.READ_ONLY}, FieldsConsts.SUBJECT: {SerializerFields.ALLOW_NULL: False, SerializerFields.REQUIRED: True}, FieldsConsts.CONTENT: {SerializerFields.ALLOW_NULL: False, SerializerFields.REQUIRED: True}, FieldsConsts.SENT_TO:{} } def create(self, validated_data): password = validated_data.pop(FieldsConsts.PASSWORD) user = User(**validated_data) # Hash passwords user.set_password(password) msg_data = validated_data.pop(FieldsConsts.MESSAGES) User.objects.create(**validated_data) for msg_data in msg_data: Message.objects.create(user=user, **msg_data) user.save() return user def update(self, instance, validated_data): instance.FieldsConsts.EMAIL = validated_data.get(FieldsConsts.EMAIL, instance.FieldsConsts.EMAIL) instance.save() return instance And the view: class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): permission_classes = [] if self.action == 'create': permission_classes = [AllowAny] elif self.action … -
What is the best practices or pattern for creating sync (real time and offline) using Django?
I guess it's better to use WebSockets (channels). But the question is how can I guarantee that every device will have the latest set of data. For example when one device goes offline, then back online is Django channels gonna send messages again to him? Any suggestions for articles or examples? Thanks in advance. -
Fees payment and registration system
I have a dissertation project in python "Fees payment and student registration system" can anybody help with python code or already made project? -
Selecting multiple options in a form and storing all of the choosen values inside a model using django
I am facing problem in Selecting multiple options in a form and storing all of the chosen values inside a model using Django python. I have created a form inenter code here forms.py file : class CustomerSignup(forms.Form): name = forms.CharField(label="Customer Name",widget=forms.TextInput(),required=True) phone = forms.CharField(widget=forms.NumberInput) address = forms.CharField(widget=forms.TextInput()) time =forms.DateTimeField(label="Time of Arrival",initial=datetime.datetime.today) guests = forms.CharField(label="Number of Guests",widget=forms.NumberInput) orderList=[ ('organic tomato salad','organic tomato salad'), ('Baked broccoli','Baked broccoli'), ('Spicy meatballs','Spicy meatballs'), ('Eggplant parmigiana','Eggplant parmigiana'), ('Grilled Caesar salad, shaved reggiano','Grilled Caesar salad, shaved reggiano'), ('Spicy Calamari and beans','Spicy Calamari and beans'), ('>Bacon wrapped wild gulf prawns','>Bacon wrapped wild gulf prawns'), ('Seared ahi tuna fillet*, honey-ginger sauce','Seared ahi tuna fillet*, honey-ginger sauce'), ('Grilled Caesar salad, shaved reggiano','Grilled Caesar salad, shaved reggiano'), ('Spicy Calamari and beans','Spicy Calamari and beans'), ('chettinad chicken','chettinad chicken'), ('italian salad','italian salad'), ('combo of slad with tuna','combo of slad with tuna'), ('fried chicken65','fried chicken65'), ('hakka noodels','hakka noodels'), ('fruit twist','fruit twist'), ('garlic chilly chicken','garlic chilly chicken'), ('cabbage salad','cabbage salad'), ('grlic bread with white soup','grlic bread with white soup'), ('lentils and chicken salad','lentils and chicken salad'), ('french toast','french toast'), ] order=forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(choices=orderList)) password = forms.CharField(widget=forms.PasswordInput()) confirm=forms.BooleanField() I have a model corresponding to this form as: models.py class Registration(models.Model): name = models.CharField(max_length=30) address = models.TextField() phone = … -
How to store multiple drop-down list selections in variables and use them to fetch data from Google Spreadsheet in Django?
I am creating a website that asks the user to select a subject, level, and medium and returns resources (stored in a Google Spreadsheet) based on the user's selections. When the user opens the website, they are welcomed with a HomePage and a link to get started. After clicking the link, they are brought to the SubjectPage, which prompts the user to choose a subject from the drop-down menu. After submitting their subject selection, they are taken to the LevelPage, which asks the user to select a level of expertise. After submitting their Level selection, they are taken to the last question, which asks the user to choose what medium they prefer for their resource. Finally, the user is taken to the Results Page where they are given a list of resources. So far, I have set up my pages and connected my project to the Google Spreadsheet I am using. However, I am having trouble figuring out how to carry the user's selections between pages and use the user's three selections to display information on the ResultsPage. Below, I have included screenshots and code that may be helpful. Please feel free to ask me for further clarification or more … -
Iterate over int in HTML?
Sorry if this is a silly question but I want to iterate over an integer attribute of an object and I'm just wondering if that's possible in HTML. So something sort of like: {% for review in reviews %} {% for r in review.rating %} <p>*</p> {% endfor %} {% endfor %} The review.rating attribute is an integer between 1 and 5. When I try something like i have above I get "'int' object is not iterable". Is there something like a foreach loop in strictly HTML or will I have to learn a bit of Javascript or something to do this? -
Can I use a function in a Django class-based view to determine template_name?
I'm trying to convert my function-based view into a class-based view to clean some things up in a Django 3 app. I've had no problem using get_context_data to work, but I can't figure out how to determine my template_name since it's normally determined from variables: from the function based view: def tour_page(request, page_safe_name, tour_id): site_name = request.META['HTTP_HOST'] s = Site.objects.get(domain=site_name) t = Tour.objects.get(pk=tour_id) page_location = 'tours/' + t.tour_safe_name + '/' + page_safe_name + '.html' ... return render(request, page_location, context) So.... I can do this with a function based view pretty easily. I'm a little confused on where in a class-based view I could (or even should?) do this. I've read some things about dispatch and potentially overriding get... but I'm not 100% sure where I should be doing this especially since I do some of this processing in the context: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) site_tour_data, s, t = self.get_site_tour_data() context.update( { 'site_safe_name': s.site_safe_name, 'site_name': s.site_name, 'site_tour_data': site_tour_data, 'tour_name': t.tour_safe_name, 'tour_id': t.id, 'domain': s.domain, } ) return context Is there either a way to grab it from the context or process these things out somewhere else in the loading of that particular page? Every other view works great since … -
Django shows "preview" of files like word document and powerpoint?
The websiote I'm developign allows user to upload files like word document, excel, powerpoint etc. Other users will be able to download these but I want to give them an option to open and view it on the site instead of forcing them to download..What is the best solution for this? Do i convert to pdf and embed it in the site? -
Django - Cannot resolve keyword 'slug' into field
When i click on my product this error appears. I already migrate the shop models and admin, and on the /admin i rename the products, slugs and descriptions. The error that i get when i try to go to the product page is this: Cannot resolve keyword 'slug' into field. Choices are: available, category, category_id, created, id, image, order_items, price, translations, updated I dont know what to do my migrations worked fine, and the server is running okay, until i click a product. shop/models.py : from django.db import models from django.urls import reverse from parler.models import TranslatableModel, TranslatedFields class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True, unique=True) ) class Meta: # ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True), description = models.TextField(blank=True) ) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # class Meta: # ordering = ('name',) # index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) admin.py: from django.contrib import admin … -
How to add auto-escaped characters in Django template?
In my project I'm using a combination of Django template and Vue.js. I'm using Vue.js, so if a user registers a string that contains Mustache syntax, rendering it in a template can cause XSS. So, I'd like to use Django's AutoEscape feature to escape strings in Mustache syntax. If possible, I want to apply the filter to the whole project. Is there a way to add an auto escape character in Django? Or is there no choice but to apply a custom filter to each item? -
SQL Query to Django Query
I'm trying to figure out how can I convert below SQL query into Django query select main_project.name, (main_contacts.first_name) as Name, group_concat(main_property.property_id) as Properties, sum(main_property.super_area), sum(main_property.covered_area), (main_contacts.first_name||main_project.name) as CONPROP from main_project INNER join main_property on main_property.project_id = main_project.id INNER join main_property_owner ON main_property_owner.property_id = main_property.id INNER JOIN main_contacts ON main_contacts.id = main_property_owner.contacts_id group by CONPROP I've learned that it will be done using 'annotate' but somehow I'm unable to do it. -
Updating cart quantity not working properly due to Form in Template
I have been fighting to fix this bug for a long time, I have an item with variations s,m and l, when I try to add or remove in the order summary page it is only updated to the item.slug not the item variations. Adding the same item with different variations is working fine except that in the template order summary.html there is a tag with href to add to cart and remove a single item from cart which I think is the reason for the issue of not updating the quantity to the variant but updating to the item.slug, the addition to the cart is not reading variations. I have drawn arrows in the views and template where I think the reason for the error. I have also tried to add a post method in the order.summary.html template but it didn't work. (the reason I did this is that I have added the item variations from the product detail template through a post method, I have tried to do the same and it is illustrated below) To better clarify here is the models.py class Item(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=100) slug = models.SlugField(unique=True) … -
Keep getting: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I'm working on a password reset feature for my django application. I'm following along using this tutorial: https://www.youtube.com/watch?v=-tyBEsHSv7w&t=924s Everything works great but I get this error when I give the email and press enter on password-reset/: NoReverseMatch at /password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I've done everything in the tutorial yet I still get this error. Thanks -
Only Admin can login but not the user i created in Users admin
Views.py def login_page(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) if 'next' in request.POST: return redirect(request.POST.get('next')) else: return redirect('/orderlist') else: form = AuthenticationForm() return render(request, "login.html",{'form':form}) urls.py app_name = 'accounts' urlpatterns = [ path('', login_page, name='login-page'), ] I have created a function for users to log in to my website. However, it only works if I login with the superuser admin account, otherwise it cannot login with the user that i created in Users admin. When I try to login with User i created in admin Users it says "Please enter a correct username and password. Note that both fields may be case-sensitive. ". -
How can I get current logged in user in django?
When I return request.user from login function, it returns currently logged in user. But, after logged_in when I redirect to other function(getuser) and return request.user from there, it retuns AnonymousUser. This works. It returns logged in user. class Login(APIView): def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponse(request.user) else: return Response(status=401) But, this won't. It returns AnonymousUser class Login(APIView): def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('getuser') else: return Response(status=401) class getuser(APIView): def get(self, request): return HttpResponse(request.user) -
Django import export update field before export signal
I want to update my field before exporting the csv. I just found out about https://django-import-export.readthedocs.io/en/latest/getting_started.html#signals. Say i have a field named totalstudents that stores the total number of students in an empty coloumn before export, how will i do it? I get really confused everytime I have to use signals, so any help would be appreciated -
Why won't this Django TestCase test pass?
I am trying to write tests for an API. I'm having trouble with a couple of User model methods. The methods all work in development and production environments, but the test does not. Here is the test: def test_delete_user(self): USER_DELETED = 1 self.u = self.setup() result = User.delete_user(self.u, self.u.pk) # response self.assertEqual(result, USER_DELETED) # functionality self.assertIsNone(self.u) print(self.u) When I run this test, the return value USER_DELETED is correct, but the user object is not actually deleted. self.setup() returns a single created user. I can post this if it is needed, but the setup and teardown both work with various other tests in the UserTest class. Here is the model method being tested: @staticmethod def delete_user(requesting_user, user_id): # static variables USER_DELETED = 1 NOT_AUTHORIZED = 0 NO_USER = -1 user_to_be_deleted = User.get_user_from_user_id(user_id) if user_to_be_deleted == NO_USER: return NO_USER # check for authorization to delete if requesting_user != user_to_be_deleted: return NOT_AUTHORIZED user_to_be_deleted.delete() return USER_DELETED I also tried creating the user with the setup and then calling self.u.delete() instead of the custom method I have. This gives the same result: AssertionError: <User: test_user> is not None Can someone explain what I am doing wrong here? Thanks. -
User deletion in Django
I created a custom Account table in Django. I even created an email-based activation to activate an account. It is working fine. The problem arises when, while new registration, the user enters an email ID which does not belong to him, or when he enters an invalid email id, or when he doesn't receive any verification mail and is trying to register again. While doing so, Error pops up showing that the email already exists. So what I want is like if the account hasn't been activated, the account details must be removed completely from the table rather than just making is_active=False. Is there any method to do this?