Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create django default group by using modelviewset
I know we can create group by admin panel of django and also can give them permissions. I am trying to create group without django admin panel. I dont want access from django admin for create group. I wish to generate group by api. I searched for it but didn't found anything. Can I create and view group by modelviewset and view them in api . I does this views.py from rest_framework import viewsets from django.contrib.auth.models import Group class UserGroupModelViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = Group urls.py from django.urls import path,include,path from .views import UserGroupModelViewSet from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register('', UserGroupModelViewSet) urlpatterns = [ path('',include(router.urls)), ] How can I create and view the list of groups I created by django admin -
Wagtail removes the accented chars but should maintain it
I'm working with Wagtail in a project in PT-BR and when I'm typing characters like an ã or an é they're removed from the RichTextBlock of a StreamField. Until here I've tried to add the pt-br langague in WAGTAIL_CONTENT_LANGUAGES and LANGUAGES of settings.py but the problem remains. PS: When I'm using TextField the problem doesn't occurs. Gif of problem -
django factory boy: How to create dummy data with imagefield
I have the following model class Test(models.Model): photo = models.ImageField( upload_to="profile_pics", default="profile_pics/blank-avatar.png" ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) How to add random images to photo using factory boy -
incorporate other py files in django views and render in html
I am new to working with django as a local server. Thus I don't get the logic. How do I incorporate my own customfile.py files in the views? How can I include them to have the results from the customfile1-calculations outputted to the views and rendered in the index.html? Let's say I have: project1 -app1 --views.py --customfile1.py ---templates\app1\index.html How and what do I need to change in the views.py or perhaps somewhere else, too? I don't want to have the whole logic of the whole app written in the views.py adn rather separated into sub-files. -
Django: I'm trying to save ip address in field by logging in user, after I go to check if this has been added in the admin page but this remains empty
I've extend the User standard model to add an ip field (it works), after that when trying login an user it works but when i check in admin page the ip address field is still empty, the ip address is not saved admin.py class IpaddressInline(admin.StackedInline): model = IpAddress can_delete = False verbose_name_plural ="ipaddress" class UserAdmin(BaseUserAdmin): inlines = (IpaddressInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) In models.py class IpAddress(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, null=True, blank=True) ip = models.GenericIPAddressField() This is my login forms class AuthenticationForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password,) if not user: raise forms.ValidationError('Wrong username or password') return super(AuthenticationForm,self).clean(*args, **kwargs) The view def login(request): context = {} form = AuthenticationForm(request.POST) if request.POST: if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') ip_address = request.META.get('HTTP_X_FORWARDED_FOR') if ip_address : ipaddress = ip_address.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') get_ip = IpAddress() get_ip.user = request.user get_ip.ip = ipaddress user = authenticate(username=username, password=password, ip=ipaddress) get_ip.user.save()# login(request, user) return render(request, 'bloggo/Dashboard.html', context) return render(request, 'bloggo/Login_form.html', {'form': form}) -
Check Django Custom permissions from react
It's my first time creating a project with Django in the backend and React frontend. I have a custom user model with boolean fields as is_moderator & is_admin & is_poster. In the frontend, there's a certain button that should only be visible to admins and moderators. So my question is how to make that button only visible to them, I made Django custom permission like that class IsModerator(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: return True def has_object_permission(self, request, view, obj): if request.user.is_moderator: return True if request.user.is_admin: return True return False and add it to the view. In that case, it is available to all kinds of users so when normal users other than moderators and admin click the button it will display an error in the console, to avoid that error I made a condition in the react component checking if the user is logged in and is admin or moderator then display the button, otherwise don't display it, but by that condition, there's no point of the custom permission. Is there a better way to achieve it? -
Django Test Client sends values as a list instead of strings
I have a problem, I am not sure whether I had overlooked something, or simply doing something wrong. I am trying to test an endpoint that allows a user to register. My model: class Account(User): objects = UserManager() balance = models.FloatField(blank=True, default=0) rank_position = models.IntegerField(blank=True, null=True) rank_title = models.CharField(max_length=255, blank=True, default="Novice") Serializer: class AccountSerializer(ModelSerializer): class Meta: model = Account fields = '__all__ View: @api_view(['POST']) def register(request): try: acc = Account.objects.create(**request.POST) acc_srl = AccountSerializer(acc) return Response(data=acc_srl.data, status=status.HTTP_201_CREATED) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) And I am trying to use a Django test client in a following way: class TestAuthentication(TestCase): def setUp(self): self.c = Client() def test_register(self): data = {'username': 'test_user', 'password': '1234'} response = self.c.post('/api/register/', data) print(response.json()) self.assertEqual(response.status_code, 201) acc = Account.objects.get(username="test_user") self.assertEqual(acc.username, "test_user") self.assertTrue(isinstance(acc, User)) The function works as expected, but a strange thing happens. When I inspect request.POST both username and password are a list as so: <QueryDict: {'username': ['test_user'], 'password': ['1234']}> I am puzzled as I dont understand what causes this behavior. -
get column name and values from cursor query in django
'''def getMessageDetails(table, phone_number_rec): sql = "SELECT customer_id , org_id , business_unit_id , campaign_id FROM messages where (case when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 11 then concat('+', REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') ) when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 10 then concat('+1',REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') ) when length(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '')) = 12 and REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') like '%-%' then concat('+1', substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 1, 3), substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 5, 3), substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', ''), 9, 4)) else REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone_number,' ', ''),'-',''),'(', ''),')', ''),'/', ''),',', '') end) ='" + phone_number_rec + "' order by created_on desc limit 1" print(sql) with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() if row != '': response_data = {'status': 'Success', 'data': list(row)} else: response_data = {'status': 'Fail', 'message': 'Data not found.'} return response_data''' 1.try to get columm name and values 2.its same query work in php but in django dont return columm name 3.phone_no is maddotary -
Python - Django - Input validation
How can I make a validation for post fetch input? I manually validate is first digit has empty space or isalnum for update operation as below but I wonder is there better approach? def update_user_meta(request): if request.method == "POST": name = request.POST.get("name") if name is not None and name[0:1].isalnum() == True: selectedUser.name = name else: selectedUser.name = selectedUser.name -
Django: Download file as background task in client's machine
I have a working file download example that works fine: def download_file_view(request): output = download_file() response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=file.xlsx' return response def download_file(): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 'something') workbook.close() output.seek(0) return output But now I want the download process to continue as a background task. I did something with threading.Thread, but the download doesn't occur: def download_file_background_view(request): t = threading.Thread(target=download_file_background) t.setDaemon(True) t.start() return redirect('/') def download_file_background(): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 'something') workbook.close() output.seek(0) response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename=file.xlsx' return response Can somebody help me how to trigger the download process in the background and let the user do other things in the web? -
Server Error (500) in django admin in particularly one model
I'm getting Server Error (500) particularly in one model in the admin page. The rest are all opening fine. Any idea what could be causing this issue . -
Run django server with poetry
I have installed Poetry in my computer and now trying to run my django server with it. As there were changes in the poetry I run poetry shell and then python manage.py runserver This raises the following error: Traceback (most recent call last): File "manage.py", line 13, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 24, in <module> main() File "manage.py", line 19, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I'm assuming that my virtual environment is already running by executing the first command and so far (without using any virtual environment) haven't had any problem with my Django, so I would say it is properly installed and available. Can you see my what may cause this issue? -
django - imbedding variables within tags
Using pycharm Django. I’m passing a dictionary "myDict" “{'id': 1, 'abvName': 'xyz', 'Name': 'ABCDEF'}”. I would like to use a template statement which requires the id value as follows: Get id Rec But apparently, I can’t imbed a tag or a variable within a tag. I can pass the id separately from views.py but maybe I’m missing a better way to do this accessing the dictionary. -
Can I download source code which has deployed with github from Heroku?
I have deployed my django-app on heroku with Github. It is test server so I am using sqlitedb. But because of the dyno manager, my sqlitedb resets everyday. So I am going to download only db on heroku. I tried this command. heroku git:clone -a APP-NAME But this clones empty repository. And when I run heroku bash run command, I got ETIMEOUT error. Is there any other way to download the source code on heroku? -
Django makemigrations always create RemoveIndex operation, but I can't migrate them
So, I don't know how I got into this looping situation honestly. I think awhile ago I might have done some manual operation on my DB with index, or even through django itself...but the current scenario now is that django is detecting changes need to be applied. When I run makemigrations, what it does is to create the same RemoveIndex operations: Migrations for 'metrics': metrics/migrations/0003_auto_20211012_0918.py - Remove index metrics_eve_session_527503_idx from event - Remove index metrics_ses_user_id_4cfc6b_idx from session - Remove index metrics_ses_trainin_9122a5_idx from session - Remove index metrics_tra_course__643338_idx from training Here is the migration generated: class Migration(migrations.Migration): dependencies = [ ('metrics', '0002_auto_20211012_0900'), ] operations = [ migrations.RemoveIndex( model_name='event', name='metrics_eve_session_527503_idx', ), migrations.RemoveIndex( model_name='session', name='metrics_ses_user_id_4cfc6b_idx', ), migrations.RemoveIndex( model_name='session', name='metrics_ses_trainin_9122a5_idx', ), migrations.RemoveIndex( model_name='training', name='metrics_tra_course__643338_idx', ), ] If I try to migrate I get: django.db.utils.OperationalError: (1091, "Can't DROP 'metrics_eve_session_527503_idx'; check that column/key exists") Guess the indexes already have been removed, but then from where django is detecting this instruction from my models? I tried adding db_index=True to these specific fields in those models to see if it forcing to create the index would help, but no success. Here is a screenshot of these table structures regarding index: metrics_training session event Question is: how do I … -
Annotate sum is doubling value
The annotate sum is doubling the value. please have a look at this code. order_list_cases = order_list.values('user_id', 'shipped_address__name', 'shipped_address__phone', 'shipped_address__pincode__district__district_name','invoice__original_amount',)\ .annotate(dcount=Count('user_id'), customer_paid_sum=Coalesce(Sum('invoice__transaction_invoice__transaction_amount'), Value(0)), customer_gross_sum=Sum('invoice__original_amount')-Sum('invoice__discount_amount')+Sum('invoice__tax_amount')) I need the value of customer gross sum, but the value which I'm getting is double the value of the desired value but not in every case. -
Django quill editor | field name displays inside quill editor widget border in Django admin
I am new to Django + Python. I can't really figure out why my field name get displayed inside the Quill Widget in Django admin. It would be great if someone who already figured out this problem share their solution. Django==3.2.4 | django-quill-editor==0.1.22 My code: # models.py class Post(models.Model): post = QuillField("Post", null=True, blank=True) # admin.py @admin.register(Title) class TitleAdmin(admin.ModelAdmin): pass image of the problem - Sorry, I don't have enough reputation to embed an image. Many thanks, -
Please how can I resolve this error :"NoReverseMatch at /projects/?"
In my Django project, if i click on projects ,I will be getting NoReverseMatch Error[Error code -
Pass urls iteratively into django html template url tag
I have a home template with links to many other pages which I want to render iteratively: (this obviously does not work due to python syntax) {% for idx, category in enumerate(categories) %} <div class="box"> a href={% url 'category_links[idx]' %}> {{category}}</a> div> {% endfor %} I have the following urls which I also pass to my template from my view: category_links = ['journals', 'proceedings', 'books', 'articles_in_books', 'talks', 'poster', 'habilitations', 'phd_thesis', 'bachelor_master_diploma_thesis', 'lectures', 'conferences', 'calls_and_awards', 'telegrams_and_circulars'] I am aware of {{forloop.counter0}} but was unable to integrate it properly. I would greatly appreciate some help! -
Converting HTML to PPTX using Python
Is there a way to convert at least HTML text styling to PPTX? I'm using Django for an website, and I want to be able to export a page to PPTX. I tried using python-pptx, and I was able to inject the raw text into a PPTX template, but I also want to keep the text formatting (colors, font size), and ideally the slide would look exactly the same as the HTML website. -
Gitlab ci fails to run docker-compose for django app
I am setting up a gitlab pipeline that I want to use to deploy a Django app on AWS using Terraform. At the moment I am just setting up the pipeline so that validates the terraform and runs tests (pytest) and lynting. The pipeline uses docker in docker and it looks like this: image: name: hashicorp/terraform:1.0.5 entrypoint: - '/usr/bin/env' - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' stages: - Test and Lint Test and Lint: image: docker:20.10.9 services: - docker:20.10.9-dind stage: Test and Lint script: - apk add --update docker-compose - apk add python3 - apk add py3-pip - docker-compose run --rm app sh -c "pytest && flake8" rules: - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME =~ /^(master|production)$/ || $CI_COMMIT_BRANCH =~ /^(master|production)$/' The pipeline fails to run the tests due to a database error I think which is weird as I am using pytest to mock the django database. If I just run: docker-compose run --rm app sh -c "pytest && flake8" on the terminal of my local machine all tests pass. Any idea how can I debug this? p.s. let me know if I need to add more info. -
Django recurring record/payment calculation
I have a table of "expected payments" that either are a one-time payment, or recurring monthly, quarterly or yearly. The goal is to calculate the total amount of expected payments for each of the upcoming 12 months. The model looks like: class ExpectedPayment(models.Model): id = models.BigIntegerField(primary_key=True) period = models.BigIntegerField() date_start = models.DateField(blank=True, null=True) date_end = models.DateField(blank=True, null=True) amount = models.DecimalField(max_digits=1000, decimal_places=1000) Period 1 = Monthly recurring Period 2 = Every Quarter - Following the start date. (So started on February, next quarter is May) Period 3 = Yearly recurring - Also following the start date Period 4 = One time payment How can I properly calculate the total "amount" for each month, while taking into account when a payment should take place? Especially the quarterly payments.. I can't figure out how to incorporate when a payment has been started and ended, as it might have been started halfway throughout the year, ended 3 months later or was already finished in the first place. How do I know which month the quarterly should count as an expected payment, when it is always relative to its start_date. An example for a single month: (every monthly payment that is active in the current … -
How to add students to class in by teacher in one click in Django rest framework
I have models named Student and Teacher. Teacher will be able to see all the students through get api (students name). Now the requirement is, by just clicking one button on the side of the list of student name, teacher should be able to add the student to his class. How to associate students to teacher in this cases. Because same students can be added to other class by other teacher as well. class Student(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="student", on_delete=models.CASCADE) college_name = models.CharField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name class Teacher(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="teacher", on_delete=models.CASCADE) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name -
Django with reportlab pdf
The following code works and prints pdf as required, but everything prints on single page only, how I can automatically generate new pages when data builds up, seeking an advice def pdf_view(request): buf = io.BytesIO() c = canvas.Canvas(buf) c.setPageSize(landscape(A4)) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) rows = [] users = User.objects.filter(is_staff=False) for user in users: rows.append(( user.username, user.email, user.first_name, user.last_name, )) table = Table(rows, colWidths=46 * mm) table.setStyle([ ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 0), (-1, -1), "LEFT"), ]) table.wrapOn(c, width, height) table.drawOn(c, 10 * mm, 10 * mm) styles = getSampleStyleSheet() ptext = "Member List" custom_style = ParagraphStyle( "Normal", fontName="Helvetica-Bold", fontSize=16, parent=styles['Heading2'], alignment=1, spaceAfter=14 ) p = Paragraph(ptext, custom_style) p.wrapOn(c, 100 * mm, 100 * mm) p.drawOn(c, 100 * mm, 195 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='members.pdf') -
django model formset how to make formset from two tables(or with one to one field)
I would like to make page to verify users, simple page, just username and checkbox near. what i getting how look it now id like make ModelChoiceField look like simple username text, or ModelChoiceField disabled. My code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='id пользователя', related_name='model') phone = models.CharField(max_length=30, verbose_name='Номер телефона', blank=True) city = models.CharField(max_length=36, blank=True, verbose_name='Город') is_verified = models.BooleanField(default=False, verbose_name='Проверен') published_news = models.IntegerField(default=0, verbose_name='Количество опубликованных новостей') class UserVerifyView(View): def get(self, request): template_name = 'app_users/verify.html' formset = UserVerifyFormSet() context = {'title': 'Верификация', 'formset': formset} return render(request, template_name, context) {% block content %} <div class="container"> {% csrf_token %} {{ foromset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} </div> {% endblock %}