Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python class instance only for current user in Django
I'm a novice with Django and I'm trying to figure out how to save a class instance for the current user, exactly what I'm trying to do is to log my user to Firebase, and then, retrieve data from the database on firebase and save that data on a local class which is only going to be available until the user logout, but all my attempts save those class instances make them global (so actually they are accesible for every user and will overwrite the previous one). My first attempt was on the views.py of my app, and looked like this: APPMANAGER = FirebaseManager() def homepage(request: HttpRequest) -> HttpResponse: APPManager.loadData(request.POST.get("data")) return HttpResponse("Done") But that APPMANAGER will be saved globally (and also will be erased if the server is rebooted). I was checking also Django sessions (https://docs.djangoproject.com/en/2.2/topics/http/sessions/), which seem like what I want to do, but it just take data that is serializeable, and I want to save a custom class instance, what is the best approach to do this? -
How to make .counts return 2 counts instead of 1
I have this line of code in my Django templates that returns counts of comments like 1, 2, 3... <li class="list-inline-item">comms: {{ article.comments.count }}</li> How do I make it return counts in twos for every comment? like 2, 4, 6... I can provide further details if need be. Thanks. -
Get URL with Current Language in Django
I have some unit-tests, which test for redirects from certain pages. In doing so, they use assertions similar to this one class SuccessfulSignUpTest(TestCase): def setUp(self): url = reverse('user_accounts:signup') data = { 'email': 'jon@doe.com', 'password1': 'abcdef1234', 'password2': 'abcdef1234', } self.response = self.client.post(url, data) # pages-root is the name of the URL pattern in DjangoCMS code self.home_url = reverse('pages-root') def test_redirection(self): ''' A valid form submission should redirect the user to the home page ''' self.assertRedirects(self.response, self.home_url) When I enabled internationalization, these tests began failing because self.home_url == /user/login/ instead of something like /en/user/login/. Is there a way to obtain a URL and have it contain the current language part or is the only way to tag the language to the URL manually via django.utils.translation.get_language()? -
Django Design question: How to break down the code properly
I would like to build an app which has some UI but a lot of backend activities. Basically, I would like to loop over list of files in a directory. for each such file, I would need to get a user feedback what is the type of the file, and then based on the file type, read all it's records and do some work on each. So the code will basically do: Loop over all the files in a directory: for each file --> Show the user the file name and then the user can select the right file type Loop over all records in this file Do Something My question is where should the loop over the files should be? In the view or in the html? If it is in the view, the HTML rendering to ask the user to select file type will be moving the control to the client (html) and then (after after user selection), It will return as a POST reply (outside the loop), right? So should the loop over the files be in the html itself? What should be the right breakup between the HTML and the View? -
how can I retrieve emai_id from django model without causing AttributeError: 'bool' object has no attribute 'emai_id'?
first at all. checks if an email in the database exists in my application, and then if it exists it will send an email to the owner account, and however when I am trying to update user_password_obj.token = None to make it invalid I am getting an error AttributeError: 'bool' object has no attribute 'email_id' my database table PasswordReset contains the following columns id,token,is_active,email_id models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(pre_save, sender='account.User') def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') class PasswordReset(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=100, null=True, blank=True,help_text="token reset") is_active = models.BooleanField(_('active'), default=True, help_text=_('token used or not')) helpers.py PasswordReset.objects.filter(email=user).delete() random_string = generate_random_string() created = PasswordReset.objects.create(email=user, token=random_string) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': random_string }) def generate_random_string(): return token_hex(16) views.py def password_process_reset(request, token): if request.method == 'POST': user_password_obj = verify_password_token(request.POST.get('token')) if user_password_obj: this_user = get_user_model().objects.get(id=user_password_obj.email_id) if not this_user: return False if request.POST.get('password') == request.POST.get('password_confirmation') and len(request.POST.get('password')) > 6: this_user.save() user_password_obj.token = None user_password_obj.save() else: pass if verify_password_token(token): token = token else: token = None return render(request, "account/reset-password.html", {'token': token}) -
html cannot display image in django
I have put my image file img.png and HTML file index.html in the same folder test I executed index.html in django, I wanted to display image from local I tried <img src='img.png'/> <img src='./img.png'/> <img src='..../test/img.png'/> <!-- absolute path --> the system all says cannot find the image file. -
How to solve this error while deploying in keroku?
would you be able to guide me here on what to do and also explaining why this happened? -
Getting null for my profile serializer data instead of actual data
I am using Django-rest-auth to authenticate my users, that works well. how my model is set up is that I have the custom user model for authentication and I also have a profile model that gets created with a signal whenever a user is created. I want that when the users are fetched in its URL, the profile for that user is also displayed, and I have passed through the serializer. THE PROBLEM: I am getting null instead of the actual data my models.py (I didnt include some models like the user managers, skill, e.t.c as i felt they werent relevant) class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() class Profile(models.Model): ''' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profiles') date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) profile_photo = models.CharField(blank=True, max_length=300, null=True) skills = models.ManyToManyField(Skill, related_name='skills') sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True) type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True) feet = models.PositiveIntegerField(blank=True, null=True) inches = models.PositiveIntegerField(blank=True, null=True) lives_in = models.CharField(max_length=50, blank=True, null=True) updated_on = models.DateTimeField(auto_now_add=True) the serializers.py code class ProfileSerializer(serializers.ModelSerializer): class … -
How to pass ID to items
I am having a problem with my code. When i add two item with same slug in my cart then i increase the quantity of the second item, it increases only the first item instead of the second item in cart. I think in my code the . first() is the problem. How do i add the ID of each items to my code. My code below. def update_cart(request, id): item = get_object_or_404(Item, id=id) if request.method == 'POST': qty = request.POST['quantity'] order_item_qs= OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if order_item_qs.exists(): item = order_item_qs.first() item.quantity = qty item.save() return redirect("shop:order-summary") -
Django Query (Postgresql) with Group, Max, Delete - need advise
I need to convert two sql order to django OEM: delete from rewards where rewards.award_id<5 AND rewards.player_id IN (select vl.player_id from vlifes vl right join (select player_id, MAX(date_last_sortie) AS maxdate from vlifes group by player_id) groupvl ON vl.player_id=groupvl.player_id AND vl.date_last_sortie = groupvl.maxdate WHERE (vl.dead=1 or vl.captured=1)) and update players set rating = 0 where players.id IN (select vl.player_id from vlifes vl right join (select player_id, MAX(date_last_sortie) AS maxdate from vlifes group by player_id) groupvl ON vl.player_id=groupvl.player_id AND vl.date_last_sortie = groupvl.maxdate WHERE (vl.dead=1 or vl.captured=1)) Django models: class VLife(models.Model): profile = models.ForeignKey(Profile, related_name='+', on_delete=models.CASCADE) player = models.ForeignKey(Player, related_name='+', on_delete=models.CASCADE) tour = models.ForeignKey(Tour, related_name='+', on_delete=models.CASCADE) date_first_sortie = models.DateTimeField(null=True) date_last_sortie = models.DateTimeField(null=True) date_last_combat = models.DateTimeField(null=True) bailout = models.IntegerField(default=0) wounded = models.IntegerField(default=0) dead = models.IntegerField(default=0) captured = models.IntegerField(default=0) relive = models.IntegerField(default=0, db_index=True) class Reward(models.Model): award = models.ForeignKey(Award, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'rewards' unique_together = (('award', 'player'),) verbose_name = _('reward') verbose_name_plural = _('rewards') def __str__(self): return '{player} - {award}'.format(player=self.player, award=self.award) For the first sql, I tried to break down the query from stats.models import VLife, Reward from django.db.models import Q from django.db.models import Max # select the latest flights for each pilot q0 = VLife.objects.values('player_id') \ .annotate(max_date=Max('date_last_sortie')) … -
Django loop through a form multiple choice field
I am very new to django and I'm making a project that tracks medications in our drug safe. Part of our daily activities is to check the amount of each drug in the safe and document each amount. In my model for the safe, I have a field "drug_name" that is a foreign key to a list of medications. I want to make a model form that auto populates each choice in the field and asks for the amount of the drug in the safe. Something like: Drug Name 1 Amount:_________ Drug Name 2 Amount:_________ and so on. Here is my model class Safe(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) date_created = models.DateTimeField(auto_now=True) drug_name = models.ForeignKey('components.Drug', related_name='drug_remove', on_delete=models.PROTECT, default=0, limit_choices_to={'is_active': True}) amount_removed = models.IntegerField(blank=True, null=True) amount_added = models.IntegerField(blank=True, null=True) amount_in_safe = models.IntegerField(blank=True, null=True) incident_number = models.CharField(max_length=20, default=0, blank=True) patient_name = models.CharField(max_length=20, default=0, blank=True) medic_unit = models.ForeignKey('components.MedicUnit', related_name='medic_unit', on_delete=models.PROTECT, blank=True, null=True) free_text = models.CharField(max_length=1000, default=0, blank =True) I'm not sure if I could submit all at once or if I would have to submit one drug at a time. Either way would work well as long as the user didn't have to manually select each medication. Thanks ahead of time for any help. -
PyMongo 3 and ServerSelectionTimeoutError while getting data from Mongodb
This seems like an old solved problem here and here and here but Still I am getting this error.I create my db on Docker.And It worked only one time.Before this, I re-created db, did "connect =false",added wait, downgraded pymongo, did previous solutions etc. I stuck. Python 3.8.0 Pymongo 3.9.0 from pymongo import MongoClient import pprint client = MongoClient('mongodb://192.168.1.100:27017/', username='admin', password='psw', authSource='myappdb', authMechanism='SCRAM-SHA-1', connect=False) db = client['myappdb'] serverStatusResult=db.command("serverStatus") pprint(serverStatusResult) and I am getting ServerSelectionTimeoutError Traceback (most recent call last): File "C:\Users\ME\eclipse2019-workspace\exdjango\exdjango__init__.py", line 12, in serverStatusResult=db.command("serverStatus") File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\database.py", line 610, in command with self.client._socket_for_reads( File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\contextlib.py", line 113, in __enter return next(self.gen) File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\mongo_client.py", line 1099, in _socket_for_reads server = topology.select_server(read_preference) File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\topology.py", line 222, in select_server return random.choice(self.select_servers(selector, File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\topology.py", line 182, in select_servers server_descriptions = self._select_servers_loop( File "C:\Users\ME\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\topology.py", line 198, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: 192.168.1.100:27017: timed out -
Cant login with the right credentials in django
I am building a registration and login system. User can register but when I try to login with the right credentials, I get error - "Please enter a correct username and password. Note that both fields may be case-sensitive.". I can only login super user(admin) in the login interface. views.py def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') fullname = form.cleaned_data.get('fullname') password = form.cleaned_data.get('password1') saved_user = form.save(commit=False) saved_user.set_password(password) saved_user.save() user = authenticate(request, username=username, password=password) messages.success(request, f'Welcome to blaza {fullname}') print(saved_user) if user is not None: login(request, user) return redirect(reverse('home')) else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) forms.py User = get_user_model() class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50) fullname = forms.CharField(max_length=200) email = forms.EmailField(max_length=200) password2 = None class Meta: model = User fields = ('username', 'fullname', 'email', 'password1') def clean_password1(self): password1 = self.cleaned_data.get('password1') try: password_validation.validate_password(password1, self.instance) except forms.ValidationError as error: self.add_error('password1', error) return password1 login.html <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="Submit">Login Now!</button> </form> urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='home.html'), name='home'), path('accounts/', include('users.urls')), path('accounts/', include('django.contrib.auth.urls')), ] I added this line of code to settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) -
Working with checkboxes and querying the database in Django
My goal is to create a page that lists all the courses available in the database and have the user select which courses they would like to be a tutor for. I have a CustomUser model, a courses model, and finally a TutorTeachesCourse model that takes user and courses as foreign keys. # model.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): is_tutee = models.BooleanField(default=False) is_tutor = models.BooleanField(default=False) class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) course_number = models.CharField(max_length=100, null = False) department = models.ForeignKey(Department, on_delete=models.CASCADE) course_description = models.CharField(max_length=1000, blank=True) objects = models.Manager() class TutorTeachesCourse(models.Model): tutor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, limit_choices_to=models.Q(is_status=True)) course = models.ForeignKey(Courses, on_delete=models.CASCADE) objects = models.Manager() class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) course_number = models.CharField(max_length=100, null = False) department = models.ForeignKey(Department, on_delete=models.CASCADE) course_description = models.CharField(max_length=1000, blank=True) objects = models.Manager() # forms.py class EditTutoredCourses(ModelForm): class Meta: model = TutorTeachesCourse fields = [] # not sure what to do here... # views.py def edit_tutored_courses(request): user = request.user if request.method == 'POST': #something about forms? form = EditTutoredCoursesForm(request.POST, instance=user) if form.is_valid(): user = form.save() messages.success(request, 'Success!') return redirect(reverse('view_profile')) else: form = EditTutoredCoursesForm(instance=user) course_list = Courses.objects.all() self_courses = TutorTeachesCourse.objects.filter(tutor=user) context = { 'form' : form, 'course_list': course_list, 'self_courses' : self_courses, } return … -
Get form field class in template
I want to check in my template if any of my form fields have certain values in their class. EG: *My form field: alcohol_percentage = DecimalField(max_digits=4, decimal_places=2, required=False, label='Alcohol', widget=(NumberInput(attrs={'class': 'form-control percentage'}))) *And then in my template: {% for field in form %} {{ field.label }} {{ field }} {% if 'percentage' in field.widget %} <!-- doing something --> {% endif %} {% endfor %} Any way to achieve this? -
Laravel route:list a like functionality in Python Django
am looking for Laravel route:list a like functionality in Python Django, i need to get a list of all urlsPatterns in my Django Project -
Can't import my compiled cython module in docker
I can successfully compile my cython module on windows (visual studio) and run python code that uses the cython module. I can successfully compile my cython module on linux (gcc/Docker container), but I get a ModuleNotFoundError when I run the same python code that works on windows. Here is my project structure on linux. When I compile it puts the .so file at /engine for some reason (doesn't do this on windows). So this is the structure after I move it to the proper spot in bbmajors_compute/compute_engine/engine: +-- bbmajors_compute | +-- compute_engine | | +-- engine | | | +-- __init__.py | | | +-- compute_cpp.pyx | | | +-- compute_cpp.pxd | | | +-- compute_cpp.cpp | | | +-- compute_cpp.cpython-37m-x86_64-linux-gnu.so | | +-- __init__.py | | +-- views.py +-- __init__.py +-- setup.py Here is my setup.py: from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize("bbmajors_compute/compute_engine/engine/compute_cpp.pyx")) Here is the build command: python ./setup.py build_ext --inplace Here is the code trying to import the cython module (last line is one that gives error): from django.shortcuts import render from django.shortcuts import redirect from django.http import HttpResponseRedirect from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .forms import TeamForm from .engine.player_costs_handler import create_costs_dict … -
Django how to make internationalization without url language prefix?
As topic says I would like to get rid of language prefixes in my urls, example: mypage.com/en - english version, mypage.com/de - german version, etc and store my website language info only in users sessions. Is there any way I can do that? -
Render django.forms.fields.ChoiceField object
In my Django Project I have the following Problem: I would like to have a dynamic Django form. In the first step the user is asked something by the first form. When I get the postmethod the variables should be used for genereating a new form my views.py def calc(request): if request.method =="POST": get_form = CalculationForm(request.POST) if get_form.is_valid(): op = get_form.cleaned_data['op'] ab = get_form.cleaned_data['ab'] alternative = AlternativForm(optype = op, wsgroup = ab) return render(request, 'calculated_lensar.html', {"alternativ" : alternativ}) else: form = CalculationForm() return render(request, 'calc.html', {'form': form}) The secondform (postmethod) looks like class AlternativForm(forms.Form): praep_button = ((3, 'hallo'), (4, 'tschüss')) def __init__(self, optype, wsgroup, *args, **kwargs): super(AlternativForm, self).__init__(*args, **kwargs) #dont know for what this is standing self.optype = optype self.wsgroup = wsgroup self.values = self.read_db() self.praep_button = self.buttons() self.felder = self.blub() self.neu2 = self.myfield_choices() def read_db(self): import sqlite3 .... return result #tuple with 15x5 elements def buttons(self): praep_button = [] for i in self.values: praep_button.append((i[4], i[1])) return praep_button #Just formating result from read_db in tuple(15x2) def blub(self): return forms.ChoiceField(widget=forms.RadioSelect, choices=self.praep_button) myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button) #print --><django.forms.fields.ChoiceField object at 0x751f9b90> def myfield_choices(self): field = self['myfield'] """i think here is the problem. Above 'myfield' is a django.forms.fields.ChoiceField object, but here it is … -
When i press on button from django form nothing happens
I am learning django forms and i am trying to create a form which will create a tag and here i got a problem i was trying figure out the problem of it, but i failed. When i press on button "Create Tag", nothing happends, also without method post in views.py it will not raise an error, just nothing. forms.py: from django import forms from blog.models import Tag, Post from django.core.exceptions import ValidationError class TagForm(forms.ModelForm): class Meta: model = Tag fields = ['title', 'slug'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'slug': forms.TextInput(attrs={'class': 'form-control'}), } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug must not be created') if Tag.objects.filter(slug__iexact=new_slug).count(): raise ValidationError('Slug must be unique. We have "{}" slug already'.format(new_slug)) return new_slug urls.py: from django.urls import path from .views import * # some-article urlpatterns = [ path('', posts_list, name='posts_list_url'), path('post/create/', PostCreate.as_view(), name='post_create_url'), path('post/<str:slug>/', PostDetail.as_view(), name='post_detail_url'), path('tags/', tag_list, name='tag_list_url'), path('tag/create', TagCreate.as_view(), name='tag_create_url'), path('tag/<str:slug>', TagDetail.as_view(), name='tag_detail_url'), ] my html pattern: {% extends 'blog/base_blog.html' %} {% block title %} Tag Create - {{ block.super }} {% endblock %} {% block content %} <form action="{% url 'tag_create_url' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {% if field.errors … -
Django Rest Framework objects referenced using multiple keyword objects
I have a model that has a unique constraint on two fields together: class Document(models.Model): filename = models.CharField(max_length=255) publication = models.CharField(max_length=8) class Meta: constraints = [ models.UniqueConstraint( fields=['filename', 'publication'], name='document_key') As per the docsting in the DRF GenericAPIView get_object method: """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ Referencing with multiple keyword arguments is exactly what I want to do. I've gotten started on overriding the get_object method class DocumentViewset(viewsets.ModelViewSet): serializer_class = serializers.ActSerializer lookup_fields = ('filename', 'publication') def get_object(self): """As per the example in the DRF docstring itself, objects are referenced using multiple keyword arguments in the URL conf. Therefore, we need to override. """ queryset = self.filter_queryset(self.get_queryset()) lookup_url_kwargs = self.lookup_fields print(lookup_url_kwargs) print(self.kwargs) Which gives me: ('filename', 'publication') {'pk': '17'} You can see the prolem is that my lookup_url_kwargs will not be in self.kwargs (which is validated on the next line). If 'lookup_url_kwarg' is set then self.kwargs will be that. But without it, self.kwargs defaults to 'pk'. How do I override this behaviour so that two fields are expected in the URL?? … -
Django filter within model field and return new model with filtered queryset
I have these two models: class Task(models.Model): pass class Result(models.Model) task = models.ForeignKey('tasks.Task', related_name='results') enabled = models.BooleanField('enabled', default=False) And I want to get task with filtered results for my temporary calculations: task = Task.objects.first() results = task.results.filter(enabled=True) task.results.set(results) This is the working code, but task results will be broken after the first usage. How to get the new task with filtered results without task.results destroying? -
Djnago Generic View Data validation
I have a model Item with a foreing key in Row model. models.py from django.db import models from django.urls import reverse from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=100, unique=True, validators=[validate_test]) number_of_questions = models.IntegerField(default=0) number_of_read_questions = models.IntegerField(default=0) def get_absolute_url(self): return reverse('uni_checker:main_editor') class Row(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) row_name = models.CharField(max_length=100, validators=[validate_test]) is_completed = models.BooleanField(default=False) deadline = models.DateField(default=timezone.now()) I'm looking for solution that will allow me to create something like that on one page: Item1_name: Row1_name; Row2_name; Row3_name; Item2_name: Row4_name; Row5_name; Row6_name; screenshot Problem For creating objects I use CreateView with form_class = Item, and context variable formset with Row forms. Problem is that I don't know how to validate data not only in form, but also in formset. If I input invalid data in row_name field, it just saves Item object, without saving Row object or showing errors. I know that something is wrong in view class or in form creation, but i couldn't find how to do it right way. Code views.py from django.views.generic import ListView from .models import Item from django.urls import reverse from .forms import ExampleFormSetHelper, CreateRowFormSet, ItemForm from crispy_forms.layout import Submit class ItemCreateView(CreateView): model = Item template_name = "uni_checker/item_create.html" form_class = ItemForm def get_context_data(self, **kwargs): … -
getting “no such table: accounts_user” after migrating and creating super user
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not … -
why am I not getting the tokens created when I tell django to do it?
I am trying to create a password reset in Django, but once the input finds the email in the database then send an email with their token similar to http://localhost:8000/account/account-recovery/process-reset/7d498a893edc45aa921a48f81f4826d3. it works amazingly until here, but after checking in Django shell the function that checks tokens. I have another problem it returns False that means no token was generated in the database. >>> verify_password_token('7d498a893edc45aa921a48f81f4826d3') False models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(pre_save, sender='account.User') def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') helper.py def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): return False if token is not None: return True else: return False my view only contains, if an email was found then send the email form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')):