Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, django. AbstractUser Class. How to fix the problem with not updated field in Model?
Greetings to all and thanks for you time. Decided to create a CustomUser Model in my app based on app needs. Key notes: register by mobile phone with API verification. no password is needed (Token for mobile devices instead). all other fields are autofilled (username, country, birth_date, etc.) later on the user has opportunity to change the registration data. Everything works well. But I've found out that I can't change the username, using admin panel. It's not being updated when I try. Any suggestion how to fix this? And also I would be grateful for answering the second priority question: In models.py in class Users I overwrite the save() method. In this save method I first add a new User, get it's Id and then update the fields 'username' and 'email' joining 'id' at the end. From my point of view the way I do it is awkward. Any suggestions? models.py: from django.conf import settings from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token import phonenumbers class UsersManager(BaseUserManager): def create_user(self, mobile, password=None): """ Creates and saves a User with the given username … -
How I can give a view to my models.py in django?
My models.py File from django.db import models class Post(models.Model): name=models.CharField(max_length=200) content=models.CharField(max_length=200) pub_time=models.DateTimeField( auto_now=True) Can You tell me how I can put this in my views.py and HTML file? -
how can i filter items in some dictionaries?
My view: new = Product.objects.all().order_by('-time_add')[:10] discount = Product.objects.all().order_by('-discount')[:10] papular = Product.objects.annotate(num_likes=Count('liked')).order_by('-num_likes')[:10] free_shipping = Product.objects.filter(free_shipping=True).order_by('-time_add')[:10] items = {'new':new, 'discount':discount, 'papular':papular, 'free_shipping':free_shipping} return render(request, 'index.html', {'items':items}) I want to filter and show products in the above categories. But each Item may be in multiple categories. What should I do to mark products and avoid duplicate items when showing all of them in the template? Should I change my queries in views.py or change template tags? I test queries. they retrieve correct data. The output should be something like this: new: a, b, c, d, e discount: b, d, f, i papular: a, c, g free_shipping: d, f, h and all items without duplicates: all: a, b, c, d, e, f, g, h, i I have not any problem in HTML, CSS or js. The problem is just to mark products that are in two categories with python/tags in view/template. It's my template: <div class="featured__controls"> <ul> <li class="active" data-filter="*">All</li> <li data-filter=".popular">Popular</li> <li data-filter=".new">New</li> <li data-filter=".discount">Discount</li> <li data-filter=".free_shipping">Free Shipping</li> </ul> </div> . . . <div class="row featured__filter"> {% for key, value in items.items %} <div class="all {{key}}"> {% for i in vlaue %} <div class="featured__item"> <div class="featured__item__text"> <h6><a href="#">{{i.name}}</a></h6> <h5>{{i.price}}</h5> </div> </div> {% endfor … -
How to Logout "without" Django authentication? [closed]
I have created a project to login on template without Django authentication. But not getting idea to get logout view on template. Since user.is_authenticated is for Django authentication but what command to use in other case. And then logout without Django authentication. Can someone please guide. I am using mysql Thanks. -
"exclude()" breaks the query in django
The query below returns the most liked entry of a title in my blog and it works fine: best_one_core=Like.objects.annotate(cnt=Count('entry')).filter(entry__title=id).order_by('-cnt').first() As I didn't want to modify it I am using default django user model's last_name field to keep track of blocked users. So if a user is blocked the last_name is blocked. What I want to do is to exclude blocked users from the results obtained by the query above. My solution is adding .exclude(user__last_name="blocked") to the query: best_one_core=Like.objects.annotate(cnt=Count('entry')).filter(entry__title=id).exclude(user__last_name="blocked").order_by('-cnt').first() This solution works for couple of other queries in the project apart from this one. I tried every possible placement so that's the problem for sure. I can share the models too if needed. -
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '/bootstrap4/popper.js'' from 'styles/bootstrap4/popper.js''
I have created the static directory from which I am loading the template. {% load static %} I am getting this error as django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '/bootstrap4/popper.js'' from 'styles/bootstrap4/popper.js'' Hare's how I am loading bootstarp. <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script> <script src="{% static styles/bootstrap4/popper.js' %}"></script> <script src="{% static styles/bootstrap4/bootstrap.min.js' %}"></script> can someone help me with this ? -
REST API, Authorization data itself is not coming in
It is the same thread as this question. The problem is that the output values on the local and EB instances are different. users/views.py class UsersViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def get_permissions(self): if self.action == "list": permission_classes = [IsAdminUser] elif self.action == "create" or self.action == "retrieve": permission_classes = [AllowAny] elif self.action == "destroy": permission_classes = [IsAdminOrSelf] else: permission_classes = [IsSelf] return [permission() for permission in permission_classes] users/permissions.py class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): print("=" * 50) print(dir(request)) print(request.authenticators) print(request.auth) print(request.data) print(request.user) print("=" * 50) return bool(request.user and request.user.is_admin) The main code is as above, and the result of sending GET user list request to the server is as follows. EB [Wed Jul 01 21:58:26.498909 2020] [:error] [pid 8264] ======================================== ========== [Wed Jul 01 21:58:26.499000 2020] [:error] [pid 8264] ['DATA', 'FILES', 'POST', 'QUERY_PARAMS', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_auth', '_authenticate', '_authenticator', '_content_type', '_data', '_default_negotiator', '_files', '_full_data', '_load_data_and_files', '_load_stream', '_not_authenticated', '_parse', '_request', '_stream', '_supports_form_parsing', '_user', 'accepted_media_type', 'accepted_renderer', 'auth', 'authenticators', 'content_type', 'data', 'force_plaintext_errors', 'negotiator', 'parser_context', 'parsers', 'query_params', 'stream', 'successful_authenticator', 'user', … -
Django context_processor no module named
I want to use a context_processors for my base.html template. You can see my project structure in the following picture: Project structure from difoni_forms.DIFONIAPP.models import Admin def check_active(request): return {"active" : Admin.objects.get(id=1).active} This is the code from my context_processors.py.And I added this line of code to my settings 'DIFONIAPP.context_processors.check_active' When I run the program i get the following error: No module named 'difoni_forms.DIFONIAPP'. I don't understand what I am doing wrong any helpis appreciated, ty in advance. -
I want to use Google docs in django site is there any security issues with directly copying the iframe tag
I want to use Google docs in my django site by embedding it with iframe tag Or the link provided by Google for embedding. Is there any security threat by using this method of embedding. -
django: access model field value without the primary key known
I have been boucing my head off the wall and cannot seem to figure out a way out of this probleme. I need to access a model object within a form. To identify which object to select, I only have access to one field (the name field), but that field is not the primary key. this is an issue because the django ways that I know only seem to work with the pk. In addition, I cannot modify the structure of the model because it messes up tenantmixin. here is the model: class Client(TenantMixin): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, default='') email = models.EmailField(default='') username = models.CharField(max_length=100, default='') ###### username password = models.CharField(max_length=100, default='') created_on = models.DateField(auto_now_add=True) auto_drop_schema = True and in the form I proceed as: field_name = 'email' obj = Client.objects.get(name= dbschema) field_object = Client._meta.get_field(field_name) field_value = field_object.value_from_object(obj) the issue is in the line: obj = Client.objects.get(name= dbschema) because it should be the primary that is the parameter inside the get() function. I cannot find a way to modify this statement to access the right object from the model. How could I tweak this to let me find the proper object from the name field? Thank you -
Django:how to convert class object to jsonfield
I Want to get Detail from Gitlab with python-gitlab library then save them to jsonfield (postgres) when I want to save it django error TypeError: Object of type ProjectIssue is not JSON serializable My code is : **The star field is my problem i have a json but in can not save as json field and say its not serializable i tried to fix it with dumps() , but the problem didnt fix! how can fix it? tnx from call.models import Issue, Merge, Project from django.core.management.base import BaseCommand import gitlab from datetime import datetime from django.utils import timezone import json class Command(BaseCommand): help = 'Displays Merge and Issue IDs' def handle(self, *args, **kwargs): project = gitlab.Gitlab( 'https://**************', private_token='****************' ) # project_name_input = input("Enter Project Name: ") projects = project.projects.list(search='gtlb') for project in projects: Project.objects.update_or_create(project_title=project.name) issues = project.issues.list(state='opened') merges = project.mergerequests.list(state='closed') issuesids = [] mergesids = [] merge_issue_cid = '' for issue in issues: issuesids.append(issue.id) Issue.objects.update_or_create( issue_id=issue.id, title=issue.title, issues_creator=issue.author.get("name"), issue_create_time = issue.created_at, issue_assigne = issue.assignee.get("name"), ****issue_data=issue**** ) mrs = issue.related_merge_requests() for mergeq in mrs: if mergeq.get("state") == "closed": # print(mergeq) merge_issue_cid = mergeq.get("id") merge = '' for merge in merges: mergesids.append(merge.id) # print(merge) if merge.id == merge_issue_cid: Merge.objects.update_or_create( merge_id=merge.id, title=merge.title, # … -
Django - Deployment with Gunicorn, Nginx issue gunicorn failing to start
d]9BquF[57AuZd_i Hi I have django app i am setting it up on Linux Server release 7.8 (Maipo). While starting the Gunicorn service getting the below error . > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/bin/gunicorn", line 8, in <module> > Jul 01 14:39:03 host4444 gunicorn[22034]: sys.exit(run()) > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", > l > Jul 01 14:39:03 host4444 gunicorn[22034]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/app/base.py", line > Jul 01 14:39:03 host4444 gunicorn[22034]: super().run() > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/app/base.py", line > Jul 01 14:39:03 host4444 gunicorn[22034]: Arbiter(self).run() > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/arbiter.py", > line > Jul 01 14:39:03 host4444 gunicorn[22034]: self.halt(reason=inst.reason, exit_status=inst.exit_status) > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/arbiter.py", > line > Jul 01 14:39:03 host4444 gunicorn[22034]: self.stop() > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/arbiter.py", > line > Jul 01 14:39:03 host4444 gunicorn[22034]: time.sleep(0.1) > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/arbiter.py", > line > Jul 01 14:39:03 host4444 gunicorn[22034]: self.reap_workers() > Jul 01 14:39:03 host4444 gunicorn[22034]: File "/mfg_automation/Pro/env/lib/python3.6/site-packages/gunicorn/arbiter.py", > line > Jul 01 14:39:03 host4444 gunicorn[22034]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) > Jul 01 14:39:03 host4444 gunicorn[22034]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> > Jul … -
How can I use python Django 3.0 for mobile app development?
Now I am studying Python, and I want to make something like twitter for my class but I dont know if can use Django for mobile apps? -
Twitter, follows function
I've created a new model in database: class UserProfile(models.Model): user = models.ForeignKey('auth.user', on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, null=True) follows = models.ManyToManyField(User, related_name="followed_by", blank=True) And try to add 'follow' feature in my app: class TweetDetailsView(View): def get(self, request, tweet_id): tweet = Tweet.objects.get(id=tweet_id) #likes is_liked = False if tweet.likes.filter(id=request.user.id).exists(): is_liked = True stuff = get_object_or_404(Tweet, id=self.kwargs['tweet_id']) total_likes = stuff.total_likes() #follows is_followed = False if User.followed_by.filter(id=request.user.id).exists(): is_followed = True return render(request, "twitter/tweet.html", locals()) def FollowUser(request, pk): user = get_object_or_404(User, id=request.POST.get('user_id')) if User.followed_by.filter(id=request.user.id).exists: User.followed_by.remove(request.user) is_followed = False else: User.followed_by.add(request.user) is_followed = True return HttpResponseRedirect(reverse('tweet', args=[str(pk)]), locals()) However, i receive a info that: 'ManyToManyDescriptor' object has no attribute 'filter' How can i do that? In case of likes, it worked. Does anyone has any idea? -
How to pass a javascript string variable to a django view?
This is the javascript part. The following store_token function is being called from this file and a string value eg "AasdfGth:Jl-Hjf...." is passed (browser token value) function store_token(token) { var data = {'reg_id':token}; console.log("Reg id", data); data = JSON.stringify(data); $.post('/api_call_for_django_view', data, function(response){}); }; The django view is - @csrf_exempt @api_view(['POST']) @permission_classes((AllowAny,)) def api_call_for_django_view(request): if request.method == 'POST': token = request.POST.dict() print("", token) #this gives a value {'{"reg_id":{}}': ''} registration_id = token['reg_id'] Don't know why the token value is not passed while it reaches the store_token function successfully! console.log("Reg id", data); gives the following value I want the reg_id string value i.e. token from javascript to get stored in to registration_id variable of django view -
django test client CRUD API, unit testing
I want to write pure unit tests for my CRUD APP in django. Everyone use django tests or pytests, but I am really confused. Should I use test client to testing eg. POST method? Unit tests should be isolate and class should be test independently. We should use mocks DB etc. So why this code from https://medium.com/@ksarthak4ever/test-driven-development-tdd-in-django-and-django-rest-framework-drf-a889a8068cb7 is unit tests? class PrivateIngredientsApiTest(TestCase): #Test the private ingredients api def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( 'ksarthak4ever@gmail', 'hakunamatata' ) self.client.force_authenticate(self.user) def test_retrieve_ingredients_list(self): #Test retrieving a list of ingredients Ingredient.objects.create(user=self.user, name='Potato') Ingredient.objects.create(user=self.user, name='Peas') res = self.client.get(INGREDIENTS_URL)ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) For me this is functional test, not unit test. I search all over the internet how to write unit tests for django, but I didn't find anything. -
How to silence Django fixed default date error W161
I have a DateField which I want to apply a default value to that has the same day and month, but different year dependent on the current date: q1_results_date = models.DateField( verbose_name='Q1 financial results', default=datetime.datetime( datetime.datetime.now().year, 3, calendar.monthrange(datetime.datetime.now().year, 3)[1] ), blank=False, null=True, ) This works as intended, however I get the following error: q1_results_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` How can I silence this error? -
Multiple-valued field in Django?
I have my model Room as follows: eid = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=25) I want to create another field user where user is a foreign key. Is to possible to create a field where multiple values can be added to a single row? For example: there are 3 users: user1,user2,user3. Now, I want a row to look like: {'eid':1,'name':'room1','user':[user1,user2,user3]} Is the above scenario possible or do I need to create separate rows for each user? -
Django REST Framwork API calls [closed]
Ive made an ecommerce project with an api backend. The api consist of customer, products, orders, orderitems and shipping adresses. They are all related to one another in different ways. I was wondering if i could make an API call where i find and order based on the users id. So what i mean is query : customerOrder = Order.objects.get( customer = request.user) Is there a way to make an api call inn where i can query the same result? -
How to use sql data in django without any templete tag such as for is i only have a single data
I am building a portfolio and i am just learning django i tried to bring data from About in sql and since i have only single piece of data i dont need for loop so i tried putting it directly but is seems i cannot do that. Any suggestion on how i can do it <section id="about"> <div class="container"> <div class="about-large d-none d-lg-block text-uppercase">About</div> <div class="about-me row mt-5"> <div class="my-image col-md-5"> <img src="{{ about.image }}" /> </div> <div class="my-description col-md-6"> <h3>About Me</h3> <h4>I am {{about.name}}</h4> <p>{{ about.about_me_one }}</p> <p>{{ about.about_me_two }}</p> <div class="cv-hire d-flex flex-start"> <button type="button" class="btn btn-dark font-weight-bold"> <a href="{{ about.cv }}">Download <i class="fas fa-download pl-2"></i></a> </button> </div> </div> </div> </div> </section> My Views .py from django.shortcuts import render from django.views.generic import TemplateView from .models import * class HomeTemplateView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['about'] = About.objects.first() context['services'] = Service.objects.all() context['works'] = RecentWork.objects.all() return context My models.py from django.db import models class About(models.Model): image = models.ImageField(upload_to="static/img") name = models.CharField(max_length=100,verbose_name="My Name") description = models.CharField(max_length=500, verbose_name="Description") description_two = models.CharField(max_length=500, verbose_name="Description", blank=True) cv = models.FileField(upload_to="static/document") class Meta: verbose_name = "About Me" verbose_name_plural = "About Me" def __str__(self): return "About Me" -
Does Django advanced courses affordable and with some support exist?
I recently graduated from as developper (academic institute course) and have been working since September as a junior developer in a research team in epidemiology. I am responsible for developing web applications for data collection and patient randomization. We use Python with the Django framework I trained 'alone' because neither Python nor Django were taught at academic institute Besides, only one person on my team knows a little Django without being a specialist but I have to manage on my own, really no code review, no follow-up, no skills sharing ... in short, I'm stagnating Now that I have mastered the basics of Django, I would like to acquire a little more advanced skills with a little support without necessarily going on a full-time course and without it costing me too much online training has its limits, I find, when it comes to becoming an 'expert' in a techno do you have affordable, even free, training advice and references that allow you to progress? in advance thank you for your feedback -
Django iregex to get best search using filter
I'm searching the title field using django filter uisng title__iregex and not able to get best result, can anyone help me creating best possible regex/ regular expression for the title search. Example: Search may be --> how are you OR hw are u OR how r you . Book.objects.filter(title__iregex=r'.*' + 'z b') -
Flask or Django or other? [closed]
I have a task for essentially building a word frequency calculator. The code is implemented but I would like to turn it in to a website. Should I use Flask or Django? Or any such tools? Thank you -
File upload using Django and Bootstrap not working
I am using an automatically generated Bootstrap form to allow the user to upload files to the database. The form is generated inside a modal like this: <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Dateien hinzufügen</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} {% bootstrap_form form %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button> <button type="submit" class="btn btn-primary">OK</button> </div> </form> </div> </div> </div> using a Django form and file structure that look like this: import django.forms as forms from .models import StandaloneFile # Create the form class. class StandaloneFileForm(forms.ModelForm): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = StandaloneFile fields = ['file', 'profile', 'description'] and from django.db import models # Create your models here. def file_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/<profile.abbr>/<filename> return '{0}/{1}'.format(instance.profile.abbr, filename) class StandaloneFile(models.Model): file = models.FileField(upload_to=file_directory_path) profile = models.ForeignKey('MeasurementProfile',on_delete=models.SET_NULL,null=True) description = models.TextField() date_uploaded = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file.name.split("/")[-1] Now if I click the submit button the fields file, profile and description should be send via POST however if I look at request.POST only the fields file and profile are send and the variable file … -
Data not changing after ajax call in Django
I have created an orders table that is taking the dates in datetime format and later on i am trying to get the data grouped by date so i have a total amount and numbers of orders made that particular day. Now, I am trying to change the data in table according to the date picked in the date range picker using Ajax call. But there seems to be some problem that is not making me get the data after ajax call is made. Can someone help me out pointing where I am going wrong? My views: from .models import orders from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def home(request): r_date = orders.objects.raw("SELECT id, SUM(amount) as amount, SUM(total) as total, (SUM(tax)*100/SUM(amount)) as rate, SUM(delivery_fee) as delivery_fee, SUM(tip) as tip, SUM(tax) as tax, SUM(sub_total) as sub_total, CONVERT(report_date, DATE) as report_date, COUNT(id) as count FROM orders Group By DATE(report_date) ORDER BY DATE(report_date) DESC;") r = round(r_date[1].rate, 2) t = [float(r), 0, 100] labels = ['net sales', 'deduction', 'tax'] context = {"r_date": r_date, 't': t, 'labels': labels} return render(request, 'dashboards/demo.html', context) @csrf_exempt def datepickerview(request): if request.method == 'POST': print(request.body) a = request.POST.get('fromDate') b = request.POST.get('toDate') # import code; # code.interact(local=dict(globals(), **locals())) print(a, …