Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter is not using the index on Postgresql JSONField
I have a Django model that contains a PostgreSQL jsonb field: class SocialUser(models.Model): id = models.BigIntegerField(primary_key=True) data = JSONField(blank=True, null=True, db_index=True) The data field contains a username attribute. I have indexed this attribute by CREATE INDEX ON users_socialuser ((data->>'username')); When I query it via Django ORM with the id, SocialUser.objects.get(id=123) and via the pgAdmin SELECT * FROM users_socialuser WHERE id = 123 they are both fast. But when I query with the JSONField's attribute username, pgAdmin SQL query SELECT * FROM users_socialuser WHERE data->>'username' = 'abc' is still equally fast, while SocialUser.objects.get(data__username='abc') is terribly slow. It seems that the Django ORM is not using the index on the username attribute. Why is that so? Can I explicitly force an index in Django ORM? Is there a workaround for this? -
Filter subset of a queryset in Django
I have these models: class Committee(models.Model): title = models.CharField("Title",max_length=50,null=False) members = models.ManyToManyField(User) class Meeting(models.Model): title = models.CharField("Title",max_length=50,null=False) date = models.DateTimeField("Date",null=False) committee = models.ForeignKey(Committee, on_delete=models.CASCADE) And I want my view to return all committees in which the logged user is in, and only the meetings that has already happened. I'm trying this code: class MeetingsView(generic.ListView): template_name = 'meetings/index.html' context_object_name = 'committees_list' login_required = True def get_queryset(self): return Committee.objects.filter(members__id=self.request.user.id,meeting__date__lte=timezone.now()) This returns me a queryset excluding the committees which has no meeting before today. What I want is to get all the committees, and the meeting_set to be filtered by the date. Is there another way to do it? -
NoReverse match at
Cannot find out why my web app keeps throwing this error. I am clueless NoReverseMatch at /new-orders/order-list/ Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Request Method: GET Request URL: http://localhost:8000/new-orders/order-list/ Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'order-sent' with arguments '('',)' notfound. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] Reverse for 'order-sent' with arguments '('',)' not found. 1 pattern(s) tried: ['new\\-orders/order\\-list/(?P<order_id>[0-9]+)/sent/$'] here is my views.py where I want to change the booleanField order_sent to True. def sent(request, order_id): order = get_object_or_404(Order, pk=order_id) try: selected_order = order.objects.get(pk=request.POST['order']) except (KeyError, Order.DoesNotExist): return render(request, 'new_orders/order-list.html', { 'order': order, 'error_message': "You did not select a valid Order",}) else: selected_order.order_sent = True selected_order.save() return render(request, 'new_orders/order-list.html', {'order': order}) here is my model.py: class Order(models.Model): order_user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='myuser') order_number = models.CharField(max_length=11, unique=True) order_sent = models.BooleanField(default=False) here is urls.py app_name = 'new_orders' urlpatterns = [ path("order-list/", views.index, name='order-list'), path("order-list/<int:order_id>/", views.detail, name='order-detail'), path("order-list/<int:order_id>/sent/", views.sent, name='order-sent'), ] and my order-list.html: <form action="{% url 'new_orders:order-sent' order.id %}" method="post"> {% csrf_token %} <ul> {% for order in all_orders %} <li><a href="{{ order.id }}"> User: <b>{{ order.order_user }}</b> | Order Type : <b>{{ order.order_type }}</b> | Device: <b>{{ order.order_device }}</b> | Count: <b>{{ order.order_count }}</b> … -
I tried to create an django hello world program then I got this error
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] I tried this code by seeing n online documentation and I see the code as same as the one in the documentation but I see the error and I can not start practicing django. from django.contrib import admin from django.urls import include, path urlpatterns = [ path('love/', include('love.urls')), path('admin/', admin.site.urls), ] Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in ad.urls, Django tried these URL patterns, in this order: ^love/ ^admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It is being shown on the web -
How to remove input and confirm password fields from the form to a separate page?
good day!I have a form for editing data, in this form there is a new password field and confirmation of a new password, how can I correctly put these fields on a separate page? lines in the form below password1 and password2. I will be very grateful for the tips! class PatientEditForm(CustomUserChangeForm): username = forms.CharField(label='Логин') last_name = forms.CharField(label='Фамилия') middle_name = forms.CharField(label='Отчество') first_name = forms.CharField(label='Имя') image = forms.ImageField(required=False, label='Изображение') email = forms.CharField(required=False) day_of_birthday = forms.DateField(label='День рождения', required=False, widget=forms.DateInput(attrs={'class': 'datepicker', 'type': 'date', 'placeholder': 'Выберите дату рождения'})) password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def __init__(self, *args, **kwargs): super(PatientEditForm, self).__init__(*args, **kwargs) self.fields.pop('password') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает', ) return self.cleaned_data def save(self, commit=True): user = super(PatientEditForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('username', 'last_name', 'middle_name', 'first_name', 'email', 'day_of_birthday') -
Cascading addition of linked models
There are several related models class Skillset(models.Model): """ Skill set """ name = models.CharField('skill_set', max_length=32, unique=True) class Technology(models.Model): """Technologies.""" tech_set = models.ForeignKey(Skillset, on_delete=models.CASCADE, related_name="skillset", blank=True, null=True) name = models.CharField('technology name', max_length=32, unique=True) class Skill(models.Model): """Information about an employee's skills.""" employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.CharField('common year using amount ', max_length=4) last_year = models.CharField('Last year of technology using ', max_length=4) level = models.CharField("experience level", max_length=64, choices=LEVELS) I need to make sure that the button is pressed to create instances of the Skills model related with a specific user. I wrote a function that creates one instance at a time using the form. template.html <form action="{% url 'add_skill_set' %}" method="post"> {% csrf_token %} Backend<input type="checkbox" name="back" value="back"> Frontend<input type="checkbox" name="front" value='front'> <input type="hidden" name="id" value="{{ employee.pk }}"> <input type="submit" value="Search"> </form> <div class="container my-5" id="about"> views.py def add_skill_set(request): id = int(request.POST.get('id')) back = request.POST.get('back', None) if request.method == "POST": if back: Skill.objects.create(employee=Employee.objects.get(id=id), technology_id=3) --> ADD CASCADE HERE return redirect('profile', pk=id) if front: ..... If the user chooses a checkbox, then after submitting the form, an instance of Skills is created that is associated with this user, but only one certain instance. Here I manually specify … -
Django I am unable to load the view I want to with a different URL
I am trying to create a new view which I can link to with a button on the index page. Clicking the button is changing the URL in the browser but is not changing the view. I tried to send an httpresponse in the view instead of trying to render a new html file hoping that that was the problem. Main urls urlpatterns = [ url(r'^$', include('posts.urls')), url('admin/', admin.site.urls), url('posts/', include('posts.urls')), url('forms/',include('posts.urls')) ] App urls urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<id>\d+)/$', views.details, name='details'), url(r'^forms/$', views.theform, name = 'forms') ] Views def theform(request): manystuff = ManyStuff.objects.all()[:10] context = { 'manystuff': manystuff } return render(request,'posts/randomform.html',context) I expect to click the button on the index and load randomform.html on the /forms url. All it does is change the url to forms and keeps the same view. -
I can't save an auth token sent from Django rest framework in my angular client side
I prepared the backend api in Django and am able to login/out and send a token when login is successful, so my problem is i can't build an http interceptor that is able to read the token and save it in local storage I have already tried some methods i found in the internet but with no success this is what i catch in the console token: "fd3e2c1f51d45066e291ad8209bdd7e7cb3b5398" __proto__: Object -
multiple database connection in Django
Issue with multiple database connections in django and assigning to a model As I need to create modules( which will only read records from the database) from diffrent source(MSSQL, ORACLE, CMS)I am trying to configure Database details in setting.py. For the setting of my MSSQL database, the connection was not happening when I look at the connection string that was created by django base.py file it is Driver={ODBC Driver 11 for SQL Server}; Server=, ; Trusted_Connection=yes; Database=; Passoword= but acctually the connection string will work only when the Trusted_Connection=yes comes after the database details like below Driver={ODBC Driver 11 for SQL Server}; Server=, ; Database=; Passoword= is there any thing Iam doing wrong in my DATABASE details. below is my database detail. 'MDMDB': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DATABSENAME', 'USER': '', 'HOST': 'HOSTNAME:PORTNAME', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, 'Trusted_Connection':'yes', } -
How can I execute a heavy-processing, background python code after submitting a form in a Django website?
I have a conceptual question regarding background tasks in Django. I am running a Python/Django site through PythonAnywhere. I have a webapp called "databooks" which is comprised of a form that has the following entries: Databook Name Folder Location/Link (which is on my PythonAnywhere file system) This databooks app then looks at the folder location and compiles all the miscellaneous files within to create one large PDF. However, due to the nature of merging pages and adding footers, etc, it is considered a "heavy process" by PythonAnywhere, which they define as a web worker that exceeds 5 minutes and which they respectively kill. My solution in mind would be to execute a background-python script after the form is submitted, which inputs the entires from the databooks views.py file into a backgrounddatabookgenerator.py file which can run independent of what a user does in the browser window. After looking at PythonAnywhere's diagnosis of this, I have been researching some options, but have been unsuccessful so far in implementing a background tasks (i.e., django-background-tasks). Is anyone familiar with a Django workflow I could implement to call another python file as a background task after a submit button is clicked? In doing so, I … -
Django model operations with foreign key and double underscore
I'm new to Django and just being curious to know more. Assuming I have two models defined as follows: class ModelA(models.Model): Item1 = models.Charfield() description = models.Charfield() class ModelB(models.Model): ItemTypes = models.CharField(ModelA, on_delete=models.CASCADE) When trying to reference or use the model, you use them like this (still assuming): something = ModelB.objects.filter(ItemType__Item) My question is on the double underscore __. I'm just curious to know: What does the code at the back end look like. Is there a valid syntax with a triple underscore or a single underscore? -
How to display only date from datetime field in modelAdmin in Django admin panel?
I have a model which has a column created_at which is actually a datetime field of this format 16.07.2019 12:26:37. I want to display only date present in this created_at field in admin panel in Django. I can display the whole field's value which is datetime if I mention the 'created_at' in list_display while creating modelAdmin. How can I display only the date value in results page like this 16.07.2019? Are there any inbuilt filters to do that while registering the modelAdmin? Python: 3.7.3 Django: 2.1.5 -
How to validate django form field while it is typing?
How to validate django form field while it is typing? For example for username field I am want to check if this username already exist def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise ValidationError("Entered username already exists") return username -
Getting { "user": [ "This field is required."] } on Postman everttime I try to post
I am trying to create a sign up api using createAPIView on Django rest Framework. Everytime I post data on Postman it returns the above error although it gets response when I run it in browser. Also the image field is causing problem in raw data on postman. I have tried a lot of things but nothng has seemed to work. What am I supposed to do? serializers class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(min_length=8) class Meta: model = User fields = ('id', 'first_name','last_name', 'email', 'username','password') extra_kwargs = {'user': {'required': False}} class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() code = serializers.CharField(read_only=True) avatar = serializers.FileField(use_url=False) class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} def create(self, validated_data): user_data = validated_data.pop('user',None) image = validated_data.pop('avatar') upr=UserProfile.objects.create(user=user_data, image=image**validated_data) return upr views class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer user_serializer = UserSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser,FileUploadParser) def post(self, request): serializer = UserProfileSerializer(data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How can i use fontawesome icon from django admin to template?
I would like to insert and choice fontawesome icon from django admin, that will show in template. What will be the model, view and template tag? -
How can I check the correctness of email end?
I need to check if there's a point in email after "@". if not email.endswith('.com'): args['reg_error'] = "Email is incorrect!" I need to do something like this, but with any end which has point after "@". -
'dict' object has no attribute 'pk' when using Django bulk_create() function
I have a table counters with 2 fields: date and value. I have a big list of objects which need to be inserted into table counters. But using serializer.save() for every row in list, there will a lot of inserts and if i have a lot of data, it will take some time until it the data has finished inserting. To solve this i looked into Django's documentation and i found that there is a function name bulk_create which can help me to insert into table a list of Objects in just 1 query. Now, here's my code: models.py: class CounterFileData(models.Model): date = models.DateTimeField() value = models.FloatField() serializers.py: class CounterFileDataSerializer(serializers.ModelSerializer): class Meta: model = CounterFileData fields = ['date', 'value'] and the code where i use bulk_create: objs = (CounterFileData(date=row.date, value=row.value) for row in parsed_data) batch = list(parsed_data) CounterFileData.objects.bulk_create(batch) row has the following schema. For example: { "date": "2018-12-31T22:00:00" "value": 9.23129792740622e-05 } When i try to do that CounterFileData.objects.bulk_create(batch) i get the following error: AttributeError: 'dict' object has no attribute 'pk' Can somebody tell me why it returns no attribute 'pk' ? I'm struggling with this thing some good hours and i still can't find a fix. Thanks in advance. -
writing a backend for authenticating users with account number after registration
I am creating a bank system that should authenticate users automatically after registration using email and password. Then, users should be assigned unique account numbers immediately they register. These account numbers are then to used for authentication during login. The problem arises when I try to login users with the assigned account numbers. It flags an error Account does not exist I have tried looking into my backends.py file to figure out errors. I realize that it seems my backend cannot fetch the user from the database. However, I cannot point out the exact error in the application. Kindly assist. models.py: class User(AbstractUser): username = models.CharField( _('username'), max_length=30, unique=True, null=True, blank=True, help_text=_( 'Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.' ), validators=[ RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username. ' 'This value may contain only letters, numbers ' 'and @/./+/-/_ characters.'), 'invalid'), ], error_messages={ 'unique': _("A user with that username already exists."), }) email = models.EmailField(unique=True, blank=True, null=True) contact_no = models.IntegerField(unique=False, null=True, blank=True) account_no = models.PositiveIntegerField( unique=True, validators=[ MinValueValidator(1000000000), MaxValueValidator(9999999999) ] ) balance = models.DecimalField( default=0, max_digits=12, decimal_places=2 ) GENDER_CHOICE = ( ("M", "Male"), ("F", "Female"), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICE) birth_date = models.DateField(null=True, blank=True) city = models.CharField(max_length=256, … -
Django DateField and Postgres
I'm using SQLite for development, but when deploying to production (using Postgres), I had the following error on a CreateView: Exception Type: ProgrammingError Exception Value: operator does not exist: character varying = date LINE 1: ...xxxx" WHERE "xxxxx"."date" = '2019-07... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. This is the field: date = models.DateField('Date', max_length=150, default='', blank=True, unique=True) Also, I use this in settings.py: DATE_INPUT_FORMATS = ('%Y-%m-%d') Do you have any ideas ? -
How can I prevent the escaping of HTML data in a DRF renderer?
I have a serialized my data in to Pandas DataFrame with the rest-pandas package. I can use the method to_html of this Dataframe to create a nicely formatted table in HTML. However, when I render its HTML is escaped and thus showing the HTML describing the formatted table instead of the table. I would like to prevent the renderer from escaping the HTML. There must be an option to set or method to override but I cannot find it. Has anyone have a suggestion? -
Android Virtual Machine management with Python for mobile applicaton security scanner
I want to develop an Android Mobile Application Vulnerability Scanner (Dynamic) to run android applciation to an android virtual machine and check out the vulnerabilities and report. In detail i should say that after the android application installation on virtual machine, a python script should run and check the application behaviour. I want to develop this scanner with python and django and I have problem on this subjects: Which Android Virtual Machine I should use. How can I connect python and android and my Django scripts to work which each other. How can I manage Android Virual Machine with Python. Thank you -
How can I get the length of a model when I create an instance of it in Django
I'm creating a model class named Project, and I wanted to use the length of the Project models. I mean when I create an instance of Project, if there are 10 instances, I wanna set the default value of order field is the length of the Project model. How can I get the current length of the model? this is my models.py code for Project model in models.py class Project(models.Model): title=models.CharField(max_length=50) order=models.IntegerField(default=0) isPublic=models.BooleanField(default=True) content=models.TextField() detailUrl=models.CharField(max_length=200) # where to upload image = models.ImageField(upload_to = createFileName, help_text="The recommended size of the images are 1x1") time=models.DateTimeField(default=timezone.now) view=models.IntegerField(default=0) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # self.order=models.IntegerField(default=0) # this works fine but this isn't what I want self.order=models.IntegerField(default=len(Project.objects.all())) # this is what I want but it gives me no response without emitting errors. -
How to aggregate on a foreign key and a specific field at the same time?
My table named Value has a one to many relationship with the table Country and the table Output_outcome_impact. I have a query that is working fine and gets what I want but then I need to do an average of the value field, but this average needs to be done for each unique id_output_outcome_impact and not the whole query. class Country(models.Model): country_name = models.CharField(max_length=255, primary_key=True) CONTINENTCHOICE = ( ('Africa', 'Africa'), ('America', 'America'), ('Asia', 'Asia'), ('Europe', 'Europe'), ('Oceania', 'Oceania') ) region = models.CharField(max_length=255) continent = models.CharField(max_length=255, choices=CONTINENTCHOICE) GDP_per_capita = models.IntegerField(null=True) unemployment_rate = models.FloatField(null=True) female_unemployment_rate = models.FloatField(null=True) litteracy_rate = models.FloatField(null=True) def __str__(self): return self.country_name class OutputOutcomeImpact(models.Model): output_outcome_impact_name = models.CharField(max_length=255, primary_key=True) TYPECHOICE = ( ('Output', 'Output'), ('Outcome', 'Outcome'), ('Impact', 'Impact'), ) type = models.CharField(max_length=255, choices=TYPECHOICE) description = models.TextField() TARGETGROUP = ( ('Standard', 'Standard'), ('Investors', 'Investors'), ('Local authorities and NGOs', 'Local authorities and NGOs'), ) target_group = models.CharField(max_length=255,choices=TARGETGROUP) question = models.TextField(null=True, blank=True) parent_name = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) indicator = models.ForeignKey(Indicator, on_delete=models.PROTECT) def __str__(self): return self.output_outcome_impact_name class Activity(models.Model): activity_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() product_service = models.TextField() output_outcome = models.TextField() outcome_impact = models.TextField() output_outcome_impacts = models.ManyToManyField('OutputOutcomeImpact') countries = models.ManyToManyField('Country') sectors = models.ManyToManyField('Sector') def __str__(self): return self.activity_name class Value(models.Model): value_name = models.CharField(max_length=255, primary_key=True) country … -
Issues with FileField not using upload_to location?
I believe I have some sort of bug with a FileField in Django. It is defined as follows: employees_csv_upload = models.FileField( _('Employees CSV Upload'), upload_to='csv/organisations/employees/', validators=[organisation_employees_csv_upload_validator], help_text='Allowed file formats: {}'.format('.csv'), null=True, blank=True ) I have an upload_to location specified. I then aim to upload the file named "employees.csv" from the Django admin area. Expected: When referencing self.employees_csv_upload.url in the model's save() call, it should be: '/uploads/csv/organisations/employees/employees.csv' Actual: However, when I go to reference self.employees_csv_upload.url on save() it is as follows: '/uploads/employees.csv' Surely this is a bug? What have I done wrong? What I have tried: On the same model, I have the following: logo = models.FileField(_('Logo'), upload_to='img/organisations/logos/', null=True, blank=True) When uploading a logo, all works fine: self.logo.url = '/uploads/img/organisations/logos/logo.png' -
Change Foreign key DropDown to Checkbox Django Admin
I have two models,linked through Foreign key. What I exactly want is I have created Table hobbies which has some hobbies and user can select hobbies listed in hobbies table inform of checkbox.When editing model 'UserModel', on admin site in field where I have applied FK it shows dropdown to 'Hobbies' Model.On admin site I want hobbies to be displayed in form of checkbox instead of opening a new popup window and selecting hobbies. models.py class hobbies(models.Model): hobbies_choices = ( ('CRR', 'Cricket'), ('POL', 'Politics'), ('FBL', 'FootBall'), ('TV', 'Television'), ('MOV', 'Movies') ) table_id=models.AutoField(primary_key=True) hobbies = MultiSelectField( choices=hobbies_choices, verbose_name='Hobbies', default=None ) def __str__(self): return str(self.hobbies) class UserModel(models.Model): username=models.ForeignKey( User, related_name='UserModel', on_delete=models.CASCADE, ) name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) hobbies=models.ForeignKey(hobbies,on_delete=None,related_name='of_user')\ On Admin Site When I Edit 'UserModel' ,I want to display 'hobbies' field from hobbies table in form of checkbox,But traditionally it display a plus sign and opens a new popup window.Could someone help me with it.Thanks