Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django view without response?
I want to make a Django view that handles GET-request to save some data to database (I know there is POST-request, but I want to use GET exactly). But I don't need any response - I don't need reloading the page - it will handled by fetch api in javascript. But if if return no response - the error occurs... Pls advise. -
How to apply changes to ontology saved on SQLite Database?
Everytime I create a new instance on my ontology, something goes wrong If I try to read from the same database again. ps - these are all part of different views on Django This is how I am adding instances to my ontology: # OWLREADY2 try: myworld = World(filename='backup.db', exclusive=False) kiposcrum = myworld.get_ontology(os.path.dirname(__file__) + '/kipo.owl').load() except: print("Error opening ontology") # Sync #-------------------------------------------------------------------------- sync_reasoner() seed = str(time.time()) id_unico = faz_id(seed) try: with kiposcrum: # here I am creating my instance, these are all strings I got from the user kiposcrum[input_classe](input_nome + id_unico) if input_observacao != "": kiposcrum[input_nome + id_unico].Observacao.append(input_observacao) sync_reasoner() status = "OK!" myworld.close() myworld.save() except: print("Mistakes were made!") status = "Error!" input_nome = "Mistakes were made!" input_classe = "Mistakes were made!" finally: print(input_nome + " " + id_unico) print(input_classe) print(status) This is how I am reading stuff from It: # OWLREADY2 try: myworld = World(filename='backup.db', exclusive=False) kiposcrum = myworld.get_ontology(os.path.dirname(__file__) + '/kipo_fialho.owl').load() except: print("Error") sync_reasoner() try: with kiposcrum: num_inst = 0 # gets a list of properties given an instance informed by the user propriedades = kiposcrum[instancia].get_properties() num_prop = len(propriedades) myworld.close() I am 100% able to read from my ontology, but If I try to create an instance and then try … -
KeyError 'first_name'
I am having an KeyError when I clicked to the ADD USER button in the Django Adminastration. I abstracted user and created a new form with abstracted model. Code works when I delete def__init__ in class CustomUserCreationForm but then styling is dissapearing. I added the necessary pictures and codes. Thank you for your help. <body> <div class="container"> <div class="login--wrapper"> <form method="POST" class="form"> {% csrf_token %} <div class="center"> <h1>Kullanıcı Ekle</h1> {% csrf_token %} {% for field in form %} <div class="mb-3"> <label for="exampleInputPassword1" class="from-label">{{field.label}}</label> {{field}} </div> {% endfor %} <button type="submit" class="btn btn-primary">Ekle</button> </div> </div> </div> </div> <body> from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm ,UserChangeForm from django import forms from users.models import DataEbotUser class CustomUserCreationForm(UserCreationForm): class Meta: model = DataEbotUser fields = ['username','first_name','last_name','email','phone','password1','password2'] def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter username...'}) self.fields['first_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter First Name...'}) self.fields['last_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Last Name ...'}) self.fields['email'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Email...'}) self.fields['phone'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Phone...'}) self.fields['password1'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter password...'}) self.fields['password2'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Confirm password...'}) enter image description here enter image description here enter image description here -
Copying data from a model field to another field without losing data
i wanna copy a data and add it to another field without lose or corrupt data. after that delete old field and continue with new field. Im using postgresql and when i try this connection with fields to copy data i get e.300 and e.307 error as i see on internet this problem cause by wrong foreign key usage and caused by same problem. POST MODEL class Post(models.Model): user = models.ForeignKey('user.CustomUser', verbose_name='Author', on_delete=models.CASCADE, related_name='posts') title = models.CharField(max_length=120) content = models.TextField() image = models.ImageField(null=True, blank=True, upload_to="media/images") publishing_date = models.DateTimeField(verbose_name='Publishing Date', auto_now_add=True) COMMENT MODEL class Comment(models.Model): post = models.ForeignKey('post.Post', related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Name') # user = models.ForeignKey('self.user', related_name='comment', on_delete=models.CASCADE) content = models.TextField(verbose_name='Comment') created_date = models.DateTimeField(auto_now_add=True) I'm currently trying to copy name field to user field and getting e.307 and e.300 post.Comment.user: (fields.E300) Field defines a relation with model 'self.user', which is either not installed, or is abstract. post.Comment.user: (fields.E307) The field post.Comment.user was declared with a lazy reference to 'self.user', but app 'self' isn't installed. Thanks for anyone who try to help. -
Django flash database object
I want to make an app where someone can search for something. When he searches he will get all of the things in the database that start with anything he wrote. Here is the backend code: def home(request): if request.method == 'POST': name = request.POST['name'] search = Team.objects.filter(name__startswith=name).all() if not search: messages.info(request, 'There wasnt') else: #looping all the items that search has for i in search: #flash the object messages.info(request,i) return render(request,'home.html') And the HTML code: {%if messages%} {%for msg in messages%} <div class='searching'> #showing the name and the title of the object <p style='color:white;margin-left:25px;'>{{msg.name}} {{msg.title}}</p> </div> {%endfor%} {%endif%} But when I run it I don't get anything. Also I don't use extra_tags because I want the name and the title appear in the same div. What should I do? Thanks. -
django next variable in url not working correctly
I'm working on a project and there is an odd problem where when the user is logged out and reloads a pre-loaded page, it goes to login page but the next url variable is incorrect. for example if the correct next varibale is like below: http://example.com/login/?next=/exmple/ but the url i'm getting is like this: http://example.com/login/?next=http%3A//host/example/ I should say that 'host' is one of my ALLOWED_HOSTS in settings.py It's very weird because I don't have this problem on debug mode, but only on the actual project that has been launched and is being used by the customer. -
Lightbox gallery navigation images: How to center selected active image
Hello I am using Lightbox gallery on my Django app. When user clicks one of the images, gallery will appear with main selected image, next and prev functional icons and all images on the navigation part. I am trying to center active selected image by floating to the left side of the screen. Image: Code: JS <script type="text/javascript"> function openModal() { document.getElementById("myModal").style.display = "block"; } function closeModal() { document.getElementById("myModal").style.display = "none"; } var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("demo"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; } </script> {% endblock %} HTML <div id="myModal" class="modal"> <div class="close-modal-container"> <a href="#" class="btn d-flex align-items-center text-light" onclick="closeModal()" aria-label="{% trans "Close" %}"> <span class="close-icon">{% icon 'CLOSE' 20 version='v2' %}</span> <span class="gr-link2 ml-2">{% trans "Close" %}</span> </a> </div> <div class="body-container"> {% for file in files %} {% if … -
How to create a searchable table from a dict data?
I want to create a search bar for my Django project and user can be able to search reporting_group I'm trying to use django-filters for that. But I'm returning a dict and I cannot use it with django-filters. Is there a way to make a search bar for a dict table? class ProcessTypeGroups(ReportsMixin, ListView): '''Process per Type by Groups''' model = User active_tab = 'reports_group' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) fieldname = 'case_type_value' date_1 = self.request.GET.get('date1') date_2 = self.request.GET.get('date2') cases = Case.objects.filter(date_created__range=[date_1, date_2]).values(fieldname).order_by( fieldname).annotate(the_count=Count(fieldname)) process_types = ProcessType.objects.all() report_group = {} for i in cases: for j in process_types: if str(j) in i["case_type_value"]: report_group[str(j.reporting_group)] = i["the_count"] context['report_group'] = report_group context['date_1'] = date_1 context['date_2'] = date_2 return context The output of the report_group is: {'test': 27, 'Undefined': 44} And my table template: <table class="table table-striped table-condensed"> <thead> <tr> <th>Group</th> <th>Number of Cases</th> </tr> </thead> <tbody> {% for index,key in report_group.items %} <tr> <td> <a href="{% url 'process_groups' date_1 date_2 index %}" style="color: black"> {{ index }} </a> </td> <td>{{ key }}</td> </tr> {% endfor %} </tbody> </table> -
Django ORM: Why is exclude() so slow and how to optimize it?
I have the following 3 queries in my CBV: filtered_content = Article.objects.filter_articles(search_term) filtered_articles = filtered_content.exclude(source__website=TWITTER) filtered_tweets = filtered_content.filter(source__website=TWITTER) Short explanation: I'm querying my database (PostgreSQL) for all article titles that contain the search term. After that, I separate the results into one variable that contains all articles originating from Twitter and the other variable contains all articles originating from all other websites. I have two questions about optimizing these queries. Question 1: Looking at the average time it takes to run these queries, it doesn't make sense to me (filtered_content = less than 0.001 seconds, filtered_articles = 0.2 seconds and filtered_tweets = 0.04 seconds). What is the reason for the exclude() statement (filtered_articles) being so slow? I also tried doing the query in another way, but this was even slower: filtered_content = Article.objects.filter_articles(search_term) filtered_tweets = filtered_content.filter(source__website=TWITTER) filtered_content.exclude(article_id__in=[tweet.article_id for tweet in filtered_tweets]) Question 2: Is there a more elegant way to solve this problem / is there a way to do it in less than 3 separate queries? More specifically, using the Django ORM, is there a way to do a query where all excluded() objects are stored in one variable while all non-excluded objects are stored in another? -
RSA key format is not supported for python that saved in djagno
When users signup to my application, i add new private key and public to every user profile. import Crypto from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Cipher import PKCS1_OAEP from Crypto import Random recipient = get_object_or_404(User, email=request.POST.get('email')) random = Random.new().read private_key = RSA.generate(1024, random) public_key = private_key.publickey() recipient.private_key = private_key.exportKey('PEM') recipient.public_key = public_key.exportKey('PEM') recipient.save() and then I retrieve the public key to encrypt a message for the user from a background process like this. user = User.objects.get(id=xyz) pvt_key = RSA.importKey(user.private_key) and it fires me these error: ValueErro RSA key format is not supported in database, the public key was saved like this way: b'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDxcmh0/JQ+2WrpP/1PuSotY7+B\nghEzIjVrqN+rLwSrgzowKIU8Ch3sUMynE2XNgpN6jMiv/Jjb0odptuWwSoZg/NYR\necIr0eLuYIN1R3zic7OwCy86DcML/bNAer89NEk5XHmC5goRZJFn8B+nPyeaQ4Uw\n7JXqmMcCCYflpr9X/QIDAQAB\n-----END PUBLIC KEY-----' Can anyone tell me what's wrong there? how can I solve this problem? -
How to refresh single div includes server logic (Django)?
I have a <div> dynamically rendered with own logic by Django on server side. I use js with fetch() method to make a get request - which updates a database (likes on posts). Then I just wish to refresh <div> that displays the like using server Django logic so that the like displayed properly. I want the logic proceeds on server side - so I need only to refresh part of code (<div>) from the page (Django template). Is it possible? -
CITextField in admin is displayed as text area, not as one line
I'm using python 3.9 with django 4.1 I'm just starting to play with it, I want to use CITextField from Postgresql so i imported it from django.contrib.postgres.fields, it works fine but that admin displays it as TextArea, which means it's not a one-liner input text, it's a all box of text to enter even if i configured a max length of 100 characters. how can I correct that? as an example to show the problem I created a Country model with name_en which is a CharField and name_fr and name_he which are CITextField, all of them are set to max length of 100 characters: class Country(models.Model): class Meta: verbose_name_plural = "Countries" name_en = models.CharField(unique=True, verbose_name="English Country Name", max_length=100) name_fr = CITextField(unique=True, verbose_name="French Country Name", max_length=100) name_he = CITextField(unique=True, verbose_name="Hebrew Country Name", max_length=100) when i browse it on the admin page this is the result: what can I do to resolve it ? thanks -
SSL Cert Verification Error hostname 'x.x.x' doesn't match either of '*exmple.com',
I'm working with many APIs, I send 200,000 requests per day and sometimes I get this error and don't know why: HTTPSConnectionPool(host='x.x.x', port=443): Max retries exceeded with url: /api/x/x/x/x (Caused by SSLError(SSLCertVerificationError("hostname 'api.exmple.com' doesn't match either of '.azureedge.net', '.media.microsoftstream.com', '.origin.mediaservices.windows.net', '.streaming.mediaservices.windows.net'"))) When I was searching for the cause of this problem, I found many responses like you should change Verify =False and like you should add (ssl.match_hostname = lambda cert, hostname: True) But I am really not satisfied with this response because most of the requests are working fine. if 'Content-Type' in header and header['Content-Type'] == 'application/json': if username and password: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,auth=(username, password),verify=True) else: response = requests.request(http_method, url, json=data, headers=header, timeout=timeout,verify=True) Please help me and thanks -
Annotate queryset with filtered related querysets which should be annotated as well
class A(models.Model): name = models.CharField() class B(models.Model): name = models.CharField() class C(models.Model): name = models.CharField() class D(models.Model): a = models.ForeignKey(A, related_name='set_of_a') b = models.ForeignKey(B, related_name='set_of_d') set_of_c = models.ManyToManyField(C, related_name='set_of_d') I want to get a queryset that should replace the following function (may be pseudocode in some places): def get_queryset(name, list_of_d): result = list(A.objects.filter(name__icontains=name)) for a in result: a.map_b_to_list_of_d = {} # annotation for b in B.objects.filter(set_of_d__set_of_c__intersects_with=set_of_c): a.map_b_to_list_of_d.setdefault(c, []) += list(b.set_of_d.filter(a__name__icontains=name, set_of_c__intersects_with=set_of_c)) return result -
Understanding how the data handling works in production
I do not really understand how the database works when using in production. My stack: Django Heroku AWS S3 PostgresSQL on Heroku Users can generate some images on my app. The images are saved to AWS S3, and in some feature I want to retrieve the last generated image. This below is my model where the images are saved in. models.py: class imgUploadModel(models.Model): auto_increment_id = models.AutoField(primary_key=True, default=True) image = models.ImageField(null=True, blank=True, upload_to="images/") And here the view where the images is taken again and handled in some features. view.py: imgname = imgUploadModel.objects.all().last().image As you can see I use .last() to get to the latest images which was generated. Now to my questions: In production, could it be that one user sees another users images? Or how does the Dynos (from heroku) separate the sessions? Since the AWS S3 bucket is just a memory storage without dividing it by users, I assume that one user can see other users images. Especially then, when user A creates an Img, and user B clicks on 'latest image'. If it is so, how can I create Dynos or Buckets or anything else to prevent this behaviour. I just do not really understand it from a … -
How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed?
How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed? error code is django.db.utils.IntegrityError: UNIQUE constraint failed: Movies_comment.user_id, Movies_comment.tv_or_movie_id. This error occurs Comment(comment=form.cleaned_data["comment"],user=request.user,stars=form.cleaned_data["stars"],tv_or_movie=tv_or_movie_object).save() views.py def view_tv_and_movie_detail(request, type_movie_or_tv, id): tv_or_movie_object, _ = TVAndMovie.objects.get_or_create(tmdb_id=id, judge_tv_or_movie=type_movie_or_tv) detail_tv_or_movie = TvAndMovieDetailhelp(request, tv_or_movie_object, 3) mycomment_obj = detail_tv_or_movie.get_user_post_comment_for_tv_or_movie() if request.method == "POST": if request.POST.get("action") == "delete": mycomment_obj.delete() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) else: form = CommentCreateForm(request.POST, instance=mycomment_obj) if form.is_valid() and request.POST.get("action") == "update": form.save() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) elif form.is_valid() and request.POST.get("action") == "create": Comment( comment=form.cleaned_data["comment"], user=request.user, stars=form.cleaned_data["stars"], tv_or_movie=tv_or_movie_object, ).save() return redirect("view_tv_and_movie_detail", type=type_movie_or_tv, id=id) else: form = CommentCreateForm(instance=mycomment_obj) data = detail_tv_or_movie.get_object_tv_or_movie_data() recommendations = detail_tv_or_movie.get_recommendations_tmdb_data() pages = detail_tv_or_movie.get_page_comment() average = tv_or_movie_object.average_stars() context = { "data": data, "recommendations": recommendations, "type": "movie", "mycomment": mycomment_obj, "average": average, "form": form, "pages": pages } return render(request, "Movie/movie_detail.html", context) models.py class TVAndMovie(models.Model): tmdb_id = models.CharField( validators=[alphanumeric], max_length=9999 ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_judge_tv_or_movie(self) -> str: return self.judge_tv_or_movie def get_comments(self) -> object: return Comment.objects.prefetch_related("tv_or_movie").filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = … -
add if does not already exist
Hello every one I'm trying to write a View Set API, that let you add course obj to your favorite list,but before adding check it if user added course already don't let user add again and if user didn't add so let user add it to the list, but I don't have any idea how can I do it with View set my view class AddtoMyCoursesView(viewsets.ModelViewSet): serializer_class = MyCoursesListSerializer def get_queryset(self, *args, **kwargs): pk = self.request.POST.get('pk') course = get_object_or_404(Courses, id=pk) print(course) course_list, _ = MyCoursesList.objects.filter(courses=course).exist() print(course_list) course_list.courses.add(course_list) My model is class MyCoursesList(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True) courses = models.ForeignKey(Courses, on_delete=models.CASCADE, blank=True,related_name='my_courses') added_date = models.DateTimeField(auto_now_add=True) teacher = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING, default=1) So what should I do to my code?? -
how to get image url attribute in django
i have a problem with getting image url in django template. In views file i am getting "product__stock_keeping_unit__image" which is related products' image as below. data = models.Product.objects.filter(category__slug=slug, product__is_default=True).values("id", "name", "product__sku", "slug", "category__name", "product__store_price", "product__sub_product__units", "product__stock_keeping_unit__image") in template file i am trying to display image {% for item in data %} <div class="col-lg-3 mb-4 text-center"> <div class="product-entry border"> <a href="#" class="prod-img"> <img src="{{ item.product__stock_keeping_unit__image.url }}"> </a> <div class="desc"> <h2><a href="{% url 'product_detail' item.slug item.product__sku %}">{{ item.name }}</a></h2> <span class="price">${{ item.product__store_price }}</span> </div> </div> </div> {% endfor %} Everything works fine except img field. In the page source i am getting empty string. But when i write <img src="{{ item.product__stock_keeping_unit__image }}"> i am getting image path in page source images/men-shoes.jpg but not add MEDIA_URL /media/images/men-shoes.jpg into path. Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' How can i solve this problem. Thank in advance! -
Model.save() got an unexpected keyword argument 'commit' django error
im trying implement the register form and i geting this erorr: Model.save() got an unexpected keyword argument 'commit' And I wrote the save method, but I still get an error forms.py class RegisterForm(forms.ModelForm): class Meta: model = CustomUser fields = ['email', 'password', 'password2'] def save(self, commit=True, *args, **kwargs): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.password = self.cleaned_data['password'] if commit: user.save() return user views.py class UserRegisterView(View): User = get_user_model() form_class = forms.RegisterForm template_name = 'account/register.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated == True: return redirect('home:home') return super().dispatch(request, *args, **kwargs) def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user_email = form.cleaned_data.get('email') user_password = form.cleaned_data.get('password') new_user = CustomUser(email=user_email) new_user.set_password(user_password) new_user.is_active = False new_user.save(commit=False) activateemail(request, new_user, user_email) return redirect('account:user_login') return render(request, self.template_name, {'form': form}) -
Django custom template tag that does not require a quoted string (like `load`)
The django template tag {% load mylib1 mylib2 %} does not require mylib2 and mylib1 to be quoted as a string. How does one create a template tag like this? All the examples in the documentation one has to quote argument strings. I tried to find the code for the load tag in django/template/loader_tags.py and django/template/templatetags, and grepped for @register.tag("load") but could not find it. -
i'am creating a django e-com project , i want to filter product by a price range with html range tag. I tried a lot
This is the html code .i need view functions for price filter <div class=""> <h5>Filter</h5> <input class="progress-bar bg-danger" type="range" name="range" id="" min ="5" , max = ""> </div> -
trigger a celery job via django singnals
I would like to use Django signals to trigger a celery task like so: def delete_content(sender, instance, **kwargs): task_id = uuid() task = delete_libera_contents.apply_async(kwargs={"instance": instance}, task_id=task_id) task.wait(timeout=300, interval=2) But I'm always running into kombu.exceptions.EncodeError: Object of type MusicTracks is not JSON serializable Now I'm not sure how to tread MusicTracks instance as it's a model class instance. How can I properly pass such instances to my task? At my tasks.py I have the following: @app.task(name="Delete Libera Contents", queue='high_priority_tasks') def delete_libera_contents(instance, **kwargs): libera_backend = instance.file.libera_backend ... -
How to call a view from within itself in a Django REST API?
I have this function in my Django REST API that handles the insertion of products. Sometimes a product will be a variational product (when product.type = 3), in which case I get all the permutations of these variations and want to insert a new product corresponding to each permutation into the database. @api_view(['POST']) def upsertProduct(request): productData = request.data['product'] variations = productData.pop('variations', []) variationTypes = productData.pop('variationTypes', []) product, created = Product.objects.update_or_create(pk=productData['id'], defaults=productData) if (productData['type'].id == 3): variations_by_type = [] for variationType in variationTypes: variations_by_type.append([variation for variation in variations if variation['variationType'] == variationType['id']]) combinations = list(itertools.product(*variations_by_type)) for combination in combinations: productData['name'] = product.name + ' (' + ' | '.join(' : '.join(i['name'] for i in item) for item in combination) + ')' productData['type'] = {'id': 5} productData['parent'] = product.id #Recursive call should go here #upsertProduct(request={'data': {'product': productData}}) My first attempt was to simply call the function as I did in the commented line. Django returned the following AssertionError: The request argument must be an instance of django.http.HttpRequest, not builtins.dict. I then attempted making use of this HttpRequest object from Django, but can not figure out how to use it properly for this use case. I've also tried the standard request library in … -
working on a django usermanager and am trying to set it up to where the user can be created using username or password is my code sufficient
from django.db import models from django.db.models import Q from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) # Create your models here. I need to know if I am headed in the right direction towards building a proper custom user manager.... class ProfileUserManager(BaseUserManager):`enter code here` def create_user(self, email, username, password=None): if not (Q(username)|Q(email)): raise ValueError('User must create account using username or email') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): user = self.create_user( email, username, password=password, ) user.is_admin= True user.save(using=self._db) return user Blockquote > I need any direction on if I am approaching building the custom user manager to include both the username or email when creating a user manager..... -
check if model was recently updated fails trying to use timedelta
I have the following model that saves a datetime on save: class StockInfo(models.Model): ticker = models.CharField(max_length=100) current_price = models.FloatField() name = models.CharField(max_length=255) summary = models.TextField() sector = models.CharField(max_length=100) dividends = models.ArrayField(model_container=Dividend) last_updated_time = models.DateTimeField(null=True) objects = models.DjongoManager() # https://stackoverflow.com/questions/9953427/django-custom-save-model def save(self, *args, **kwargs): self.last_updated_time = datetime.datetime.now().astimezone() super(StockInfo, self).save(*args, **kwargs) In the view I try using a timedelta to determine if the model had been updated within the last minute: the_timedelta = stock.last_updated_time.replace(tzinfo=None) - now print(the_timedelta) if the_timedelta > datetime.timedelta(minutes=1): print("stock was updated within the last minute") else: print("stock hasn't been updated recently") I was expecting it to determine these rapid updates were within a minute: found the stock the last updated time for stock good before save: 08/15/2022 07:51:09 -1 day, 23:59:31.335919 stock hasn't been updated recently the last updated time for stock good after save: 08/15/2022 07:51:38 reversing the comparison to if the_timedelta < datetime.timedelta(minutes=1): causes the opposite error: the last updated time for stock stag before save: 08/15/2022 07:51:37 -1 day, 23:50:47.073490 stock was updated within the last minute the last updated time for stock stag after save: 08/15/2022 08:00:50 I would like to be able to determine if the stock object was saved in the last 60 …