Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue when I want to send a request to an url with middleware applied even when I'm logged in, in Django
I have a Django project include rest API. since i have added middleware in my project i cant access my api through requests modules although i am logged in. but it is possible to access while i type the address in url. middlewares.py from django.http import HttpResponseRedirect from django.contrib import messages LOGIN_EXEMPT_URLS = [ '/api/', ] class LoginMiddleWare: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_authenticated and request.path not in LOGIN_EXEMPT_URLS: messages.error(request, 'You should login first!', 'warning') return HttpResponseRedirect('/api/') response = self.get_response(request) return response settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'djangoProject_app.middlewares.LoginMiddleWare', ] -
get data from request when creating object in django rest framework
I'm trying to verify email by sending a code, that's how i'm approaching the problem: I created a model named Email_for_Verification with two fields (email , code) the code is generated randomly, i create an instance of this model when the user enters his email, i send the generated code on email, in the second step, the user enters the received code, and i'm proceeding to the validation with a View named : Verify_code. but i'm encountring an error. i'm facing this error when trying to send email to the user when creating the Email_for_Verification instance 'Request' object has no attribute 'email' Here is my code Views.py class Verify_code(APIView): def post(self, request): data = request.data code = data.get('code') email = data.get('email') email_for_verification = models.Email_for_Verification.objects.get(email=email) if code == email_for_verification.code: return Response({"valid" : "Valid code", "email": email}, status=status.HTTP_200_OK) else : return Response({"invalid" : "Invalid code", "email": email}, status=status.HTTP_404_NOT_FOUND) class EmailForVerificationView(CreateAPIView): queryset = models.Email_for_Verification.objects.all() serializer_class = EmailForVerificationSerializer def create(self, request): created = models.Email_for_Verification.objects.create(email = request.email).save() if created: data = request.data email = data['email'] code = data['code'] send_mail( 'He is the code of verification', code, 'ivan@yandex.ru', [email], fail_silently=True, ) Models.py def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) class Email_for_Verification(models.Model): email = models.EmailField( max_length=100, … -
unable to get the docker interpreter in pycharm (running in windows 10)
Currently running docker desktop 2.5.0.1 in windows 10 ,I am trying to configure docker interpreter for my Django project in Pycharm , but I couldn't find any docker interpreter in the left hand side of the window. I have already added the Django plugins required for pycharm -
How to define a default value for a get parameters with Django?
I do not understand why I cannot define a default value for a get parameter even after reading the document about QueryDict. This is what I have: selected_zipcode = request.GET.get('zipcode', 75000) I can get my parameter if set in my url but if I do not define a zipcode parameter or if zipcode is not set, i do not get 75000 as value. -
i really cant find my problem.. but my problem is that i have something duplicated in my tuple
the error is : ERRORS: <class 'registerapp.admin.UserAdminConfig'>: (admin.E012) There are duplicate field(s) in 'fieldsets[1][1]'. <class 'registerapp.admin.UserAdminConfig'>: (admin.E012) There are duplicate field(s) in 'fieldsets[2][1]'. btw I have to inform that I have used mobileNumber as unique=True in my model from django.contrib import admin from registerapp.models import Members from django.contrib.auth.admin import UserAdmin class UserAdminConfig(UserAdmin): search_fields = ('email', 'name', 'mobileNumber',) list_filter = ('email', 'name', 'mobileNumber', 'nationalCode',) ordering = ('email',) list_display = ('email', 'familyName', 'mobileNumber', 'nationalCode', 'is_active', 'is_staff') fieldsets = ( (None, {'fields': ('name', 'familyName')}), ('User information', {'fields': ('email', 'name', 'familyName', 'mobileNumber', 'password', 'nationalCode')}), ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'groups')}), ) add_fieldsets = (None, { 'classes': ('wide',), 'fields': ('email', 'name', 'familyName', 'mobileNumber', 'password', 'nationalCode') }) admin.site.register(Members, UserAdminConfig) my model class customMemberManager(BaseUserManager): def create_user(self, email, mobileNumber, name, familyName, password, nationalCode, **other_fields): if not email: raise ValueError('YOU MUST ENTER VALID EMAIL') email = self.normalize_email(email) user = self.model(email=email, mobileNumber=mobileNumber, name=name, familyName=familyName, password=password, nationalCode=nationalCode, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, mobileNumber, name, familyName, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email, mobileNumber, name, familyName, password, nationalCode, **other_fields) … -
Django forms cleaned_data
I want to create a sort_by functionality in my django app and for that I tried the following way. First step: forms.py class SortForm(forms.Form): CHOICES = [ ('latest', 'Latest Notes'), ('oldest', 'Oldest Notes'), ('alpha_descend', 'Alpahabetically (a to z)'), ('alpha_ascend', 'Alpahabetically (z to a)'), ] ordering = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) Then views.py: def index(request): ################### Default, when form is not filled ################# notes = Note.objects.all().order_by('-last_edited') form = SortForm() if request.method == 'POST': form = SortForm(request.POST) if form.is_valid(): sort_by = form.cleaned_data['ordering'] if sort_by == 'latest': notes = Note.objects.all().order_by('-last_edited') elif sort_by == 'oldest': notes = Note.objects.all().order_by('last_edited') elif sort_by == 'alpha_descend': notes = Note.objects.all().order_by('title') elif sort_by == 'alpha_ascend': notes = Note.objects.all().order_by('-title') return redirect('index') context = { 'notes' : notes, 'form' : form, } return render(request, 'notes/index.html', context) models.py just in case: class Note(models.Model): title = models.CharField(max_length=100) body = models.TextField() last_edited = models.DateTimeField(auto_now=True) def __str__(self): return self.title It doesn't do anything when the form submit button is pressed and refreshes the index page with the default lookup defined above. -
To look if the date is within 7 days in Django
class Order(models.Model): date_ordered = models.DateTimeField(auto_now_add = True) I have date_ordered field inside order model. And now i want to check if the date_ordered and today's date is within 7 days or not inside views.py . For today's date i have used : current_day = datetime.datetime.now() ( if i need to use another, please suggest) Can anyone please help me. -
Django Custom BaseUserManager: overwritten create_user is not getting used, overwritten create_superuser is working flawless. How?
I am working on a Django project, where I have a custom AbstractBaseUser and a custom BaseUserManager. Logically I created those pretty early and since they were doing what they are supposed to, I went on in the project. Now I am at a point, where I want to add the atribute userTag to the custom User and I want to call the function generate_userTag, when an user is created (same for superuser). So I added the fuction to the create_user I already had "working"; at least I thought it would. Turns out, no changes I make in the create_user function are getting applyed or have any impact on the project. Its like the fuction never gets called. I added an ValueError that should raise erytime the function is getting called, but when I register a new user from the testsite, there is no error and the user gets created without the userTag. Now the weird part: I tested to create a superuser and to my surprise it was working flawlessly. The superuser gets created, with the userTag. Everything fine. So my question: What could cause Django to not call the custom create_user, when creating a user, but call the … -
Adding Django Groups Programatically
I have set up a very basic Django website and I am looking to create a moderator group. I am unsure how to go about creating this programatically. Mainly, I am worried about which file I would need to put it in, and whether or not when I create it, will it show up on my admin site as a group. Otherwise, how else can I confirm it is made? Can I create groups from any app? For example, I have an app called 'users' which doesn't contain any models. Can I simply create my moderator group with example code for a generic group below in views.py or will that not work? from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') ct = ContentType.objects.get_for_model(Project) permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Thanks for any help in advance! -
djongo.exceptions.SQLDecodeError
I am working on a Django project with MongoDB. for that I am using Djongo package. whenever I am running the command for migrate it will give me SQLDecoderError. This error from all auth migration file, my functionality is users can sign in with Twitter so that's why I am working on Django-allauth. Error in shell: Operations to perform: Apply all migrations: account, admin, auth, common, contenttypes, sessions, sites, socialaccount, users Running migrations: Applying account.0003_auto_20210915_1059... Traceback (most recent call last): File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 786, in __init__ self._query = self.parse() File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 878, in parse raise e File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 859, in parse return handler(self, statement) File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 891, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/home/nividata/projects/venv_latino/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 502, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "account_emailaddress" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most … -
How does 'likedit' in django_comments_xtd work from source code perspective?
In django comments extended framework, When user clicks on "likedit" for one comment, template file user_feedback.html will be rendered. {% if show_feedback and item.likedit_users %} <a class="badge badge-primary text-white cfb-counter" data-toggle="tooltip" title="{{ item.likedit_users|join:'<br/>' }}"> {{ item.likedit_users|length }}</a> {% endif %} <a href="{% url 'comments-xtd-like' item.comment.pk %}" class="{% if not item.likedit %}mutedlink{% endif %}"> <span class="fas fa-thumbs-up"></span></a> Based on above source codes, I can not figure out, How is the 'likedit' implemented, in other words, how is a HTTP request with POST method invoked ? I did not even find any thumb-up icon is included in above source code. -
Django Html get dictionary value from index
How can I get the value from my dictionary using the forloop counter? The current way that I'm doing it doesn't show anything. Extension.py @register.filter def get_item(dictionary, key): return dictionary.get(key) Views.py {% for project in projectList %} <tr> <td><h5>{{ project.id }}</h5></td> <td><h5>${{ project.allBudgets|get_item:forloop.counter0 }}</h5></td> </tr> {% endfor %} -
Query for favorites of user in Django
I want to query for the favorites a user has in Django. Every user has a profile (userprofile) and the favorites are stored in this userprofile Model. I want to be able to query for the favorites (they are userprofiles) only using the id of the user. This is what I have but does not work (it returns an empty query even though the user has 3 favorites): favorites = UserProfile.objects.filter(favorites__user__id=user_id) My User Model: class User(AbstractUser): usertype = models.PositiveSmallIntegerField(choices=constants.USER_TYPE_CHOICES ) profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=False) token = models.CharField(max_length=10, default='') My UserProfile Model: class UserProfile(models.Model): birth_date = models.DateField(default=datetime.date(1900, 1, 1)) favorites = models.ManyToManyField('self', symmetrical=False) How should I do this? Thank you a lot! -
Get Multiple fields in from an Annotate with Max in Django
I would like to get multiple fields from an 'annotate' in Django, with a Max and a Filter. So, I have this Query: w=Wherever.objects.prefetch_related('wherever2').filter(...).values(...).annotate(max_wherever2_field1=Max('wherever2__field1', filter=Q(wherever2__field2=False))) So, considering the highest value in field1, and the filter in Field2, I want to get the rest of fields of the same register in wherever2 table. How can I do it? -
Wagtail root page does not render body content
I created a wagtail site which is supposed to be in Spanish. The problem is that I cannot see the root page in 127.0.0.1:8000. However I can see it when I click on preview: Page when in preview When I click "View live", I do not see the content of the page. Also, I noticed that the wagtail user bar has only the option "Go to Wagtail Admin": Here is the page in live And finally, here is my page in admin panel: Page in admin panel At first, I thought I might have messed up with the languages. So I changed LANGUAGE_CODE to 'es' and LANGUAGES variable in settings and I also changed the locale from 'en' to 'es' in the Admin panel. But I do not know what else to try. Thanks for your time. -
how to change faster methods to optimize in django
how to change faster methods to optimize in django , Actually u used loop but its take more time to get output.. Anyone please help me to solve this problem MY looping result = dict() balace_amount =0 total_quantity =0 for item in sales_by_customer: invoice_date = item['order__created_on'] invoice_date = invoice_date.strftime('%m/%d/%Y') entity_name = Entities.objects.values_list('name',flat=True).filter(id=item['order__entity_id']).first() group_by_str = f"{item['order__entity_id']}" total_quantity +=item['order_quantity'] unit_price = item['price'] if percentage_amt: if float(percentage_amt) > 0: unit_price = float(unit_price) + (float(percentage_amt)*float(unit_price))/100 else: percentage_amt = float(percentage_amt) percentage_amt = abs(percentage_amt); unit_price = float(unit_price) - (float(percentage_amt)*float(unit_price))/100 unit_price_with_qty = unit_price * item['order_quantity'] balace_amount += unit_price_with_qty nyb_code = ProductCodes.objects.values_list('nyb_code',flat=True).filter(product_id=item['product_id']).filter(flavour_id=item['flavour_id']).filter(quantity_id=item['quantity_id']).first() if group_by_str in result: result[group_by_str]['invoice'].append({"entity_name": entity_name,"invoice_no": item['order__order_id'],"invoice_date": invoice_date,"product_title": item['product__title'],"flavour_title": item['flavour__title'],"quantity_title": item['quantity__title'],"nyb_code": nyb_code,'unit_price': unit_price,"entity_id": entity_name,"qty": item['order_quantity'],"sub_total": unit_price_with_qty,"balace_amount": balace_amount}) result[group_by_str]['total_amount'] = balace_amount result[group_by_str]['total_quantity'] = total_quantity else: result[group_by_str] = {'order__brand_id': item['order__brand_id'],'total_quantity': item['order_quantity'],'total_amount': item['total_price'],"entity_name": entity_name, 'invoice': [{"entity_name": entity_name,"invoice_no": item['order__order_id'],"invoice_date": invoice_date,"product_title": item['product__title'],"flavour_title": item['flavour__title'],"quantity_title": item['quantity__title'],"nyb_code": nyb_code,'unit_price': unit_price,"entity_id": entity_name,"qty": item['order_quantity'],"sub_total": unit_price_with_qty,"balace_amount": item['total_price']}]} sales_by_customer = list(result.values()) -
how to completely remove the recent action panel from Django admin UI
how to completely remove the recent action panel from Django admin UI I have done a lot of searching and all leads to how to clear the data in the panel from the database .. but what am looking to do is completely remove the panel from my admin Userinteraface .. any help on how to do this? what I've tried : tried to override the base_site.html for the admin and it worked for override colors and styles and other blocks but not working with the sidebar block {% extends "admin/base.html" %} {% load i18n static %} {% block title %}{{ title }} | {% trans "G-Attend" %}{% endblock %} {% block extrastyle %} <link rel="stylesheet" type="text/css" href="{% static 'custom_admin_styles/admin_override.css' %}"> {% endblock %} {% block branding %} <h1 id="site-name"> <b style="color: #1f76bc;size: 80;"> G </b> Attend </h1> {% endblock %} {% block sidebar %} <div id="content-related"> </div> {% endblock %} {% block nav-global %}{% endblock %} -
string to Q object
My string contains parenthesis for defining operations precedence. Operations are: and, or, eq (equal), ne (not equal), gt (greater than), lt (less than) example string: '(date eq '2016-05-01') AND ((number_of_calories gt 20) OR (number_of_calories lt 10))' How can I filter django models with given credentials? what is best way? Currently I have below solution but it's not good approach as it's vulnerable to SQL Injection: q_string = '(date eq '2016-05-01') AND ((number_of_calories gt 20) OR (number_of_calories lt 10))' query = convert_string(q_string) # query = '(date = '2016-05-01') AND ((number_of_calories > 20) OR (number_of_calories < 10))' Users.models.raw('SELECT * FROM Users WHERE ' + query) So I'm thinking about converting string to Q object something like: q_object = Q(q_string) Users.models.filter(q_object) how can I convert string to Q object? -
github workflow fails while testing a django app
I created a django rest api and I am setting up a github action that performs linting and testing only. I run the test locally using pytest, pytest-django and pytest-cov and all tests pass. Django creates the dummy database and the api is tested. when i run the github action I get an error (see below) and I think this is due to the fact the inside the github enviroment there is no database. this is the github action: name: Python package on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - name: Check out repository code uses: actions/checkout@v2 # Setup Python (faster than using Python container) - name: Setup Python uses: actions/setup-python@v2 with: python-version: "3.7" - name: Install pipenv run: | python -m pip install --upgrade pipenv wheel - id: cache-pipenv uses: actions/cache@v1 with: path: ~/.local/share/virtualenvs key: ${{ runner.os }}-pipenv-${{ hashFiles('**/Pipfile.lock') }} - name: Install dependencies if: steps.cache-pipenv.outputs.cache-hit != 'true' run: | pipenv install --deploy --dev - name: Lint with flake8 run: | pipenv install flake8 # stop the build if there are Python syntax errors or undefined names pipenv run flake8 . - name: Run Migrations run: pipenv run python django_api-project/manage.py … -
Frequent 'out of shared memory' exceptions
I'm maintaining a Django app that CRUDs data on a Postgres DB. I frequently get ERROR: out of shared memory HINT: You might need to increase max_locks_per_transaction. messages from time to time ... especially when i try to run some adhoc jobs. This is basically what my function (decorated as a Celery task) looks like: @app.task() def myfunc(params): LOGGER.info("Starting func.") col1, col2, col3 = transformer(params) count_new_records = 0 with transaction.atomic(): for item in my_iterable: template_obj, created = MyTable.objects.get_or_create( col1=col1, defaults={ 'col2': col2, 'col3': col3 } ) if not created: template_obj.col3 = template_obj.col3 + col3 template_obj.save() else: count_new_records += 1 LOGGER.info(str(count_new_records) + " new records created.") LOGGER.info("Ending func.") Is there an issue with my code that causes the errors? Maybe locks not getting released correctly? If so, how can I resolve this issue & avoid having to increase max_locks_per_transaction every time? -
Django i18n in production
I gotta bilingual project. It works properly in local development, but when I deploy it on heroku, it won't read the locale folder whereas it works on development As I found out, git automatically ignores .mo and .po files, How can I undo that gitignore? -
Django - get a queryset following relationships
Let's say I have 3 models that are linked by One-to-Many relationships: class Company(models.Model): [...] class Reporter(models.Model): reporter = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='reporters') [...] class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE, related_name='articles') [...] Is it possible to retrieve all articles linked to a specific company, starting from the company instance? I already know I can achieve that by doing: company = Company.objects.first() articles = Article.objects.filter(reporter__company=company) But could I directly use related names? Something like: company = Company.objects.first() articles = company.reporters... # directly starting from the "parent" -
Create many-to-many relations with bulk_create during file reading
I have trouble with the code architecture for adding many-to-many links when reading a file and creating new objects models.py class GS(models.Model): name = model.CharField() country_code = ManyToMany(Lang) class Lang(models.Model): code name I read the csv file and create new objects on each row file.csv **Name**,**Lang** name1,US; JP; AU name2,MX; ID; UA; CZ; ZA; HU; SK .... The Lang model is already in the database.I.e. I need to iterate through the file and create a new instance of GS and an intermediate model to link this instance with all the appropriate Lang objects. def handle(self, *args, **options): path = path_to 'file.csv' df = pd.read_csv(path) # set an empty queryset lang = Lang.objects.none() geo_segment = [] for i, row in df.iterrows(): # get list of language code lang_code = [c_c.strip(' ') for c_c in row['Lang'].split(';')] -> [MX, ID, UA, CZ .....] # get appropriate Lang objects langs = Lang.objects.filter(code__in=lang_code) # fulfill lang queryset distinct lang = lang | langs segment = GS(name=row['Name'] ) geo_segment.append(segment) # create new GS instancess but without realtions with Lang objects GS.objects.bulk_create(geo_segment) #SOME NEW LOGIC And here I'm lost, how to make the new created GS objects with all the corresponding Lang objects. In the for loop … -
Djangoform field is not displayed
i've got register form forms class RegisterForm(UserCreationForm): name = forms.CharField(max_length=255, label='Username', widget=forms.TextInput(attrs={'class': 'form-group'})) email = forms.EmailField(max_length=255, label='Email', widget=forms.EmailInput(attrs={'class': 'form-group'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-group'})) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput(attrs={'class': 'form-group'})) class Meta: model = User fields = ('name', 'email', 'password1', 'password2') views class RegisterFormView(FormView): form_class = UserCreationForm success_url = '/login/' template_name = 'blog/signup.html' def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) def form_invalid(self, form): return super(RegisterFormView, self).form_invalid(form) html <form method="POST" class="register-form" id="register-form" action=""> {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> i tried {{form.as_p}} and for field . in both cases email field doesn't shows and labels too. register is working -
Return response statement is not returning any response
I am creating a logout view to logout from my django restframework using simplejwt. There is no direct way to logout so only blacklisting the refresh token is the workarround. Those print statements works expectedly so it does blacklist the tokens but the return statement doesn't return anything, why is that and how may I return a Response?I am guessing the save function doesnt return anything, is it ture? class LogoutSerializer(serializers.Serializer): refresh = serializers.CharField() def validate(self, attrs): self.token = attrs['refresh'] return attrs def save(self, **kwargs): try: RefreshToken(self.token).blacklist() print('done') return Response({'msg':'token has been blacklisted'}) except TokenError: print('not done') return Response({'msg':'token is expired or blacklisted'}) views.py class LogoutAPIView(APIView): serializer_class = LogoutSerializer permission_classes = [IsAuthenticated] def post(self, request): serializer = self.serializer_class(data = request.data) serializer.is_valid(raise_exception = True) serializer.save() return Response(status = status.HTTP_204_NO_CONTENT)