Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When to set related objects with clear=True in Django?
The other day I came across the following snippet in the code base I'm working with: instance.teachers.clear() instance.teachers.add(*teachers) I was wondering how it was different from simply calling instance.teachers.set(teachers). I looked .set() up in the documentation which says: This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once. Honestly it's still not clear to me what the difference effectively is. I also checked the implementation of .set() and co and what I found that calling clear(), for instance, will dispatch certain signals. Unless I need this, is there any other point in using it? -
Very large python function definition in exec() call crashes Django but does not crash directly executed Python code
I have a very large (~400k lines) Python function that I am attempting to define through an exec() call. If I run the following Python script: exec("""def blah() # 400k lines of IF/THEN/ELSE """, globals()) blah() By calling Python from the command line, it works fine. However, if I do the same within a Django instance, it crashes the server without any error message or stack trace, which I can only assume is due to a segmentation fault. Both Django runserver and the above script are run from the same Conda enviroment, and both have unlimited stack available (confirmed by printing out resource.getrlimit in Django). Here's my full ulimit -a output: core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 515017 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) unlimited cpu time (seconds, -t) unlimited max user processes (-u) 4096 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited -
Webpack build all django applications
I'm using Django as a backend an all apps are located in apps folder . βββ apps β βββ account β βββ api β βββ listing β βββ login β βββ __pycache__ β βββ static β βββ user βββ dwapper β βββ asgi.py β βββ __init__.py β βββ middleware.py β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ VK_settings.py β βββ wsgi.py Every app has static folder w the files accont βββ static β βββ account β βββ css β βββ js I"m already building base static with this config const MiniCss = require('mini-css-extract-plugin'); let path = require('path'); module.exports = { mode: 'development', entry: './static_src/base/js/base.js', output: { filename: 'base.js', path: path.resolve(__dirname, "../../static/base/js") }, module: { rules: [ { test: /\.scss$/, use: [ MiniCss.loader, 'css-loader', 'sass-loader' ] }, { test: /.(gif|svg|woff|woff2|ttf|eot)$/, use: "url-loader?limit=100000" }, { test: /.(png|ico|jpg|jpeg)$/, use: "file-loader" } ] }, plugins: [ new MiniCss({ filename: '../css/base.css', }) ] } {project}/static_src static_src βββ base βββ base.config.js βββ img β βββ dwapper-logo150.png β βββ dwapper-logo278.png β βββ dwapper-logo32.png β βββ dwapper-logo.png β βββ favicon.ico βββ js β βββ base.js βββ sass βββ additional.scss βββ base.scss Everything i want to do is build all other static js and scss files β¦ -
Database Structure for Preference selection
I have two models, user and course who should be matched. To provide a basis for this matching, both models can rank the other one. I'm trying to figure out a database structure to efficiently store the preferences. The problem is, that the number of ranks is unknown (depending of number of users/courses). I'm using Django with Postgres, if this helps. I tried storing the preferences as a field with a pickled dictionary, but this causes problems if a model stored in the dict is updated and takes a long time to load. I'm thankful for any tips or suggestions for improvement. -
How to upload multiple images in db in django
I tried to store images in filestorage api. But what i am concerned is, that how will i query those images from a file. So is there any way to store image in database. -
Django ORM (Redundant Data in 'Through'-Table)
UPDATE: After writing this down I realized that I could drop the "Listing"-Field in the "Bid"-Table, and therefor won't have any redundant data anymore. Thought I post the question anyways, cause I wonder if this is the best approach (and if this is maybe interesting for some one else) Hello! I am new to Django and ORM in general, and I spent a lot of time to make this work. And it does! But looking at my tables I wonder if there's a better way, or if this is just how the Django ORM works under the hood. Here are the two Models that are important for this: class Listing(models.Model): title = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=512) imgurl = models.CharField(max_length=128) start_price = models.DecimalField(max_digits=12, decimal_places=2) closed = models.BooleanField(default=False, editable=False) bids = models.ManyToManyField('Bid', blank=True, related_name='listing_bids') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f"{self.title}" class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bid_price = models.DecimalField(max_digits=12, decimal_places=2) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) def __str__(self): return f"{self.user} ({self.bid_price}) @ {self.listing}" And here, for the sake of better visualization, are the two resulting tables (with some data): As I see it, this is all the information that is necessary. The bid table tracks the β¦ -
django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
Getting the above mentioned error while running a django web app which requires creating a database in sql server. My base.py file: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST':'localhost,1433', ## to be used in Linux OS 'NAME':'dbname', 'USER':'sa', 'PASSWORD':'#######', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'host_is_server': True, }, } } quoted = urllib.parse.quote_plus('driver={ODBC Driver 17 for SQL Server};server=localhost,1433;database=dbname;UID=sa;PWD=#######;Encrypt=yes;TrustServerCertificate=yes;Connection Timeout=30;') My SQL Server consists of the following: 1. An initial login by the name of 'sa' 2. A DB by the name of 'dbname' My Django version: 3.0.6 My Python version: 3.6.9 Please ley me know if more info is required. Very naive to coding! -
Django REST Framework: error [ "Incorrect type. Expected pk value, received str." ]
I'm getting the following error when trying to post multipart/form-data with both a FileField and ManyToManyRelationship: [ "Incorrect type. Expected pk value, received str." ] My serializer is as follows: class DatasetStorePointerCreateSerializer(serializers.ModelSerializer): domains = serializers.PrimaryKeyRelatedField(many=True, queryset=Domain.objects.all()) class Meta: model = DatasetStorePointer fields = [ 'name', 'description', 'supplementary_information', 'type', 'file_entity', 'domains', 'citations', 'owner' ] So my serializer is expecting an Array of IDs such as [1,2] but in the request.data the Array of domains is going up as 'domains': ['1,2'] ...but it should be 'domains': [1,2] N.B. The payload object being sent up is new FormData(), where I am taking a Javascript object as parsing it to FormData as follows: getFormData(object) { const formData = new FormData(); Object.keys(object).forEach(key => formData.append(this.camelToUnderscore(key), object[key])); return formData; }, Does anyone know the fix for this? -
NoReverseMatch at is not a registered namespace
I see there are a lot of examples of this error, but I cannot figure out why my code is not working. I am using Django 3.0.3 and I get an error that says NoReverseMatch at /browse/ 'browse' is not a registered namespace in my browse app. It looks to me like I have everything i need, do I need to add a reference to browse somewhere else? views.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register', views.register, name='register'), ] urls.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "browse/index.html") def register(request): return render(request, "browse/register.html") layout.html: <a class="dropdown-item" href="{% url 'browse:register' %}">Register</a> project-wide urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('browse/', include('browse.urls')), ] -
Djoser Permission Classes Issue
So Im trying make an app with djoser as my third party package. I have made a bunch of @api_views along with it and i wanted to apply some permissions as well. I have already done IsAuthenticated but am unable to update custom permission for djoser : 'user': ['djoser.permissions.CurrentUserOrAdminOrReadOnly'] I have used PERMISSION instead of DEFAULT_PERMISSION_CLASSES in djoser list. I would like to be able to get a token and only able to change that users data and not someone elses but till now it hasnt worked. i can update or post any type of data of different user with a valid token . Can someone help me out here? Thanks in Advance -
How to annotate an existing queryset
I want to update a queryset with an annotation in class based view. Why does this work: def get_queryset(self): qs = self.model._default_manager.all().annotate(admin_roles_count=Count('administrators')) return qs But this does not?: def get_queryset(self): qs = super().get_queryset() qs.annotate(admin_roles_count=Count('administrators')) return qs print(qs[0].admin_roles_count) throws: AttributeError: 'MyModel' object has no attribute 'admin_roles_count' -
I can't login with email in django
I tried to login with email but I can't! I saw this kind of question was asked before but I don't know what I did wrong here! It works fine with registration. In the login logic I wrote if user is not None then call the login method from django.contrib.auth else display a warning message and when I clicked login it displayed a warning message. Noted that I wanted to use custom form fields with html and css. here is my backends.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.db.models import Q class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email = username) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return None forms.py from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import get_user_model from django import forms class RegisterForm(UserCreationForm): class Meta: model = get_user_model() fields = [ 'username', 'email', 'password1', 'password2' ] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'Username', 'type': 'text', 'name': 'username-register', 'class': 'form-control mt-4 mb-3 ml-3', }) self.fields['email'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'Email Address', 'type': 'email', 'name': 'email-register', 'class': 'form-control mb-3 ml-3', }) self.fields['password1'].widget.attrs.update({ 'id': 'register-form', 'placeholder': 'New Password', 'type': 'password', 'name': 'password1-register', 'class': β¦ -
Session not working in django using django rest api with react js in frontend
I am not able to auto login using session in django. Every time i am logging in django is creating a new sessions row in the database. These two are my view functions.. user_login(for login) and is_login(for checking if user is already loggeg in or not) def user_login(request): if request.method == "POST": recieved_data = JSONParser().parse(request) username = recieved_data['username'] password = recieved_data['password'] data = {} user = User.objects.get(username = username) if user is not None: if check_password(password, user.password): login(request, user) request.session['username'] = username data['response'] = 'login successfull' data['username'] = username token = Token.objects.get(user = user).key data['token'] = token return JsonResponse(data, status = 201) else: data['response'] = 'invalid password' return JsonResponse(data, status = 400) else: data['response'] = 'invalid username' return JsonResponse(data, status = 400) def is_login(request): if request.method == "POST": key = 'username' data = {} if key in request.session: data['username'] = "username" data['response'] = 'logged in' return HttpResponse(data, status = 201) else: data['response'] = 'not logged in' return HttpResponse(data, status = 400) -
I have two models in django named user and customer (the customer has a foreign key as user).I want to make a customer whenever someone registers
this is my models.py class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) mobile = models.CharField(max_length=12) first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile','first_name','last_name'] class Customer(models.Model): user=models.OneToOneField(MyUser,null=True,blank=True,on_delete=models.CASCADE) name=models.CharField(max_length=100,null=True) email=models.CharField(max_length=100) mobile=models.CharField(max_length=12) def __str__(self): return self.name class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False,null=True,blank=False) transaction_id=models.CharField(max_length=100,null=True) and this is my views.py def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] mobile=request.POST['mobile'] password=request.POST['password'] cpassword=request.POST['cpassword'] if password==cpassword: if User.objects.filter(email=email).exists(): messages.info(request,'Email already in use') return redirect('signup') elif User.objects.filter(mobile=mobile).exists(): messages.info(request,'Mobile Number already in use') return redirect('signup') else: user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,password=password,mobile=mobile) customer=Customer(user=user.email,mobile=mobile,name=first_name) customer.save(); user.save(); return redirect('/login/') else: messages.info(request,'Passwords not matching') return redirect('signup') else: return render(request,'signup.html') I am working on a basic e-commerce website and to access the shopping cart the user must be registered. The other model i am using is Order and which has a foreign key as customer.So basically to access the cart one has to be the customer. The signup page that i have registers the users but also at the same time I want to make him/her a customer as well but i am not able to do it. I tried using this customer=Customer(user=user.email,mobile=mobile,name=first_name) customer.save(); but i am getting error. Please suggest some way so that whenever someone registers β¦ -
How to make a file uploader (.jpg, .mp3, .pdf etc) from local directory for a user in django
Need an idea about how we can get that file from the user that he has selected from the local directory and send it to database. -
Django-parler 'PostTranslation' object has no attribute 'publish'
I use django-parler to translate model fields. My model has some DateTime fields, which I do not need to be translated. When I try to add an instance from the admin page, I get the following error: 'PostTranslation' object has no attribute 'publish', and I cannot seem to understand what causes it. The error occurs whether I try to add a new instance, or edit an existing one. models.py: class PublishedManager(TranslatableModel): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class DefaultManager(TranslatableModel): def get_queryset(self): return super(PublishedManager, self).get_queryset() class Post(TranslatableModel): objects = DefaultManager() # The default manager adapted for translations. published = PublishedManager() # Our custom manager. STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) translations = TranslatedFields( title=models.CharField(max_length=250), slug=models.SlugField(max_length=250, unique_for_date='publish'), body=models.TextField() ) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blogapp:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) admin.py: @admin.register(Post) class PostAdmin(TranslatableAdmin): list_display = ('title', 'slug', 'publish', 'status') list_filter = ('status', 'created', 'publish') search_fields = ('title', 'body') date_hierarchy = 'publish' ordering = ('status', 'publish') formfield_overrides = { TextField: {'widget': TinyMCE()}, } def get_prepopulated_fields(self, request, obj=None): return {'slug': ('title',)} -
Save dictionary values into django model like DRF
I have dictionary values then i want dictionary values into django database model. traditionally we use like Dic = {'id':1,'name':'shiva'} Data=Model(id=dic['id'], name=dic['name']) data.save() So here i want save dictionary values similar DRF Serializer concept not like above ModelSerializer(dic) ModelSerializer.save() How i can implement ,to prevent assigning field values while saving data -
Implement Azure AD Authentication in DRF backend
I'm creating an Angular app with a Django Rest Framework backend. I have followed this tutorial for implementing Azure Active Directory in the Angular app. That part works but I dont' know how to implement the Azure AD in the backend. Form the tutorial it looks like I have the set the token in de header and the backend checks with the AD of the token correct is. How do I do that in DRF? Thanks in advance! -
in django can we pass arguments in redirect/HttpResponseRedirect to another view
i am trying to pass arguments like form, orm queries used in 1 view function to another without changing the url reference in url.py with redirect or httpRedirect. request.session is also not working as orm queries or form details needs to serialized or pickled before attempting to pass to another function.sorry if i sound silly as i am just learning django below is my code. views.py ..................................... def home(request, **kwargs): y = blog.objects.all() print("******************") try: if request.user is not None: x = Profile.objects.get(user__id=request.user.id) form = blog_form(request.POST, request.FILES or None) if request.method == "POST": form = blog_form(request.POST, request.FILES or None) if form.is_valid(): title = form.cleaned_data.get("title") content = form.cleaned_data.get("content") types = form.cleaned_data.get("types") x1 = form.save(commit=False) x1.created_date = datetime.datetime.now() x1.created_by = request.user x1.save() return redirect("home") else: form = blog_form() return render(request, 'home.html', {'form1': form, 'y': y, 'x': x }) except: print("anonymous user") return render(request, 'home.html', {'y': y}) return render(request, 'home.html',{'form2': kwargs.get('form2'), 'p9': kwargs.get("p1")}) @login_required(redirect_field_name='my_redirect_field') def user_comments(request, id, *args, **kwargs): x1 = blog.objects.get(id=id) n1 = comments.objects.filter(commented_blog__id=id) print(x1) form2 = comment_form(request.POST, request.FILES or None) print(form2.is_valid()) print(form2.errors) if request.method == "POST": form2 = comment_form(request.POST) print(form2) if form2.is_valid(): print("--valid-----") comment_text = form2.cleaned_data.get("comment_text") x2 = form2.save(commit=False) x2.commented_user = request.user x2.commented_blog = x1 x2.save() kwargs = {'form2': form2, 'usercomment': β¦ -
Celery alternative for Windows
One of our solutions uses Django on top of services created using Python libraries. In order to concurrently process multiple queued service tasks the only production ready option seems to be with Celery [producer, consumer] and RabbitMQ[broker]. However Celery has stopped support for Windows OS sometime ago. We are able to deploy to linux OS, but would like to allow for Windows deployment as well since all our other libraries work well on both. Any suggestions for an alternative to Celery? NOTE: We've already tried Django's native queuing engine and not satisfied with the concurrency behavior. We've also tried the how-to-run-celery-on-windows, but not satisfied with the robustness of the solution for Prod. -
convert json from one form to another in python
I have got a response after altering a list. My response looks something like this : { "response": [ { "timestamp": "21:15-21:30", "logs": [ { "exception": "IllegalAgrumentsException", "count": 1 } ] }, { "timestamp": "21:15-21:30", "logs": [ { "exception": "NullPointerException", "count": 2 } ] },.. I want the result to be something like this:- "response": [ { "timestamp": "21:15-21:30", "logs": [ { "exception": "IllegalAgrumentsException", "count": 1 }, { "exception": "NullPointerException", "count": 2 } ] } How can I merge logs together like above in python? -
Get post id in a Class based view
Trying to get post id in Detailview in views.py .I am trying to add like button on blog Detail page. I think I need to add id in kwargs in get_absolute_url function but that didn't work or I didn't add that correctly.so, please help me. #views.py class PostDetail(DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, *args, **kwargs): context = super(PostDetail, self).get_context_data(*args, **kwargs) post = get_object_or_404(Post, id=self.kwargs['id']) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context["post"] = post context["is_liked"] = is_liked return context model.py class Post(models.Model): cover = models.URLField(blank=True) tag = models.CharField(max_length=100, unique=True, default=0) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(accountUser, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() likes = models.ManyToManyField(accountUser, related_name='likes', blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse("post_detail", kwargs={"slug": str(self.slug)}) Error in terminal #error post = get_object_or_404(Post, id=self.kwargs['id']) KeyError: 'id' -
Django - search a text field for a word or phrase contained in another model
What would be the best method for setting up a keyword finder as below? class scene(models.Model): fk_type = models.ForeignKey(scene_types, on_delete=models.CASCADE) text = models.CharField(max_length=250, default='') order = models.PositiveSmallIntegerField() def __str__(self): return self.text class Meta: ordering = ('order', ) class AI_keywords(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) keyword = models.CharField(max_length=250) response = models.ForeignKey(AI_responses, default='1', on_delete=models.CASCADE) def __str__(self): return self.keyword class Meta: ordering = ('keyword', ) views class v_scene(LoginRequiredMixin, ListView): model = scene template_name = 'storiesapp/scene.html' context_object_name = 'scene' The idea is when a keyword in the AI_keywords model is detected in the scene.text field, it displays the AI_keywords.response field -
Django Select and Display Model Inlines Dynamically with multiple select drop down box
Here is what my admin page looks like: Here is a link of the admin page: https://i.stack.imgur.com/Ghq5f.png As I add more models, I will have more foreign keys related to Selector and each instance of the selector model doesnβt need all the inlines. I would like to be able to select and choose which inlines to display for simplicity of the admin page. Does anyone have any suggestions on how I can simplify my page and have a dropdown multiple select box for dynamically displaying the inlines? Here is my models.py file: from django.db import models class Selector(models.Model): lst = [ ("Model1", "Model1"), ("Model2", "Model2"), ("Model3", "Model3"), ("Model4", "Model4"), ] choice = models.CharField("Choices", choices=lst, max_length=40) class Model1(models.Model): select = models.ForeignKey(Selector, on_delete=models.CASCADE) param1 = models.IntegerField("Input 1") param2 = models.IntegerField("Input 2") param3 = models.IntegerField("Input 3") class Model2(models.Model): select = models.ForeignKey(Selector, on_delete=models.CASCADE) param1 = models.IntegerField("Input 1") param2 = models.IntegerField("Input 2") param3 = models.IntegerField("Input 3") class Model3(models.Model): select = models.ForeignKey(Selector, on_delete=models.CASCADE) param1 = models.IntegerField("Input 1") param2 = models.IntegerField("Input 2") param3 = models.IntegerField("Input 3") class Model4(models.Model): select = models.ForeignKey(Selector, on_delete=models.CASCADE) param1 = models.IntegerField("Input 1") param2 = models.IntegerField("Input 2") param3 = models.IntegerField("Input 3") Here is my admin.py file: from django.contrib import admin from .models import Model1, β¦ -
How can I list all the users who liked a post in django rest framework?
I am new to django rest framework and I am trying to list all the users who have liked particular posts, but here I am getting only a empty dictionary. I may have my views or serializers wrong, can anyone check the code out and suggest the changes I should make? class LikeListApiView(APIView): serializer_class = PostLikeListSerializer permission_classes = (IsAuthenticated,) def get(self, *args, **kwargs): try: post = get_object_or_404(Post, slug=self.kwargs['slug']) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) likes_list = post.likes.all() serializer = PostLikeListSerializer(likes_list) return Response(serializer.data, status=status.HTTP_200_OK) class UserSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['username',] class PostLikeListSerializer(serializers.ModelSerializer): likes = UserSerializer(many=True, read_only=True) #likes is in Post model with foreign key to user Model class Meta: model = Post fields = ['likes',] Please let me know if further details are needed. Thanks