Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does transaction.atomic cover the called function too?
I'm working with Django / Celery and I would like to know if transaction.atomic on my create function cover also the called function (createUserTenant) too this is an example (as you can see i'm calling createUserTenant whiche contains some queries) : @transaction.atomic def create(self, request): formSerializer = CustomUserSerializer(data = request.data) if formSerializer.is_valid(): NewUserRecord = formSerializer.save() if createUserTenant.delay(NewUserRecord.id, connection.schema_name): return Response(TeamSerializer(Team.objects.all(), many=True).data, status = status.HTTP_201_CREATED) return Response(formSerializer.errors, status.HTTP_400_BAD_REQUEST) As you can see I have some transactions here @shared_task def createUserTenant(userid, current_schema): state = True try: with schema_context(current_schema): addUserInTeam = Team.objects.create(user = CustomUser.objects.get(pk=userid)) with schema_context('public'): userInQuestion = CustomUser.objects.get(id=userid) # create your first real tenant tenant = Client( schema_name=str(userInQuestion.username), name=userInQuestion.first_name + '_' + userInQuestion.last_name, paid_until='2014-12-05', on_trial=True) tenant.save() # migrate_schemas automatically called, your tenant is ready to be used! # Add one or more domains for the tenant domain = Domain() domain.domain = str(userInQuestion.username) + settings.BASE_URL # tx.domain.com domain.tenant = tenant domain.is_primary = False domain.save() except: state = False return state -
Celery, relation "x_x" does not exist
Issue with Celery during the query This is my code : from apps.teams.models import Team @shared_task @transaction.atomic def createUserTenant(): addUserInTeam = Team.objects.create(user_id = 1) this is the error : return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "teams_team" does not exist LINE 1: INSERT INTO "teams_team" ("user_id") VALUES (1) RETURNING "t... Since every thing is OK when move the same query to my views it works fine but in celery -
How does a user stay signed in when accessing a class based view?
I'm currently implement Microsoft Login using Graphs. Using the code below, I am able to navigate to different parts of the website while staying in: context = initialize_context(request) user = context['user'] return render(request, 'Login/newclaim.html/', context) How do I implement this is a Class Based View? I am currently using django-tables2 to generate a datatable using this view: Views.py: from django_tables2 import SingleTableView from .models import SaveClaimForm from .tables import ClaimsTable class ClaimListView(SingleTableView): model = SaveClaimForm table_class = ClaimsTable template_name = 'login/existingclaims.html' -
Updating static files of docker volume
I have a Django website running in a docker image in my server, I need to update my static files without changing anything else, can I run a dockerfile just with that command or do docker exec COMMAND for that? What is the best practice in this case? If I run my dockerfile again, all the steps are in the cache memory and if I put the option of no-cache I am afraid that it will overwrite my media volume again, where I have images of the users. I think I have tried once without the cache but it did not update my volume of the static files. RUN python manage.py collectstatic --no-input --clear That is the command I think I need to run, but I am not sure if it works. -
The modal does not work when executing the following code and I can not type my username and password
In this code,i can not type username and password when i click on login button,The modal form is displayed but not accessible and the black screen is blurred. This project is written for Django. If I log in from my page, there is no problem, but I tried any method this way, but I could not fix it. The form starts from the {% else %} part and continues to the {% endif %} part. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0", shrink-to-fit='no'> <title>{% block title %}XXX{% endblock title %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">XXX</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">YYY <span class="sr-only">(current)</span></a> </li> {% block news %} <li class="nav-item active"> <a class="nav-link" href="{% url 'news_list' %}">ZZZ <span class="sr-only">(current)</span></a> </li> {% endblock news %} <li class="nav-item active"> <a class="nav-link" href="#">AAA <span class="sr-only">(current)</span></a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-1 my-sm-0" type="submit">Search</button> </form> </div> <div class="d-flex flex-column flex-md-row … -
how to access the id of a ManyToManyField object?
my models: class Aula(models.Model): nome_aula = models.CharField(max_length=255) descricao_aula = models.TextField() ... def __str__(self): return self.nome_aula class Modulos(models.Model): numero_modulo = models.CharField(default="Módulo 1",max_length=400) aulas = models.ManyToManyField(Aula) def __str__(self): return self.numero_modulo my views: def aulasdomodulo(request, id): mod = get_object_or_404(Modulos, pk=id) aulas = mod.aulas.all() return render(request, 'wtic/aulasdomodulo.html', {'aulas':aulas, 'mod':mod}) def conteudodaaula(request, id): mod2 = get_object_or_404(Modulos, pk=id) aula = mod2.aulas.all() ... return render(request,'wtic/conteudo_aula.html', {'aula':aula}) my html where it shows the objects assigned that module accesses them {% for aula in aulas %} {{aula.nome_aula}} <a href="/aula/{{aula.id}}">Acessar</a> {% endfor %} but when I try to access classes I get it how can i access these objects one per page? -
Python Django, Convert Image object to File object
so basically i am trying to convert PIL Image object to File object so django can process it, this is what i have tried so far in views.py: if request.method == 'POST': title = request.POST.get('title','') fil = request.FILES.get('fil') img=Image.open(fil) img = img.resize((500,500)) img_bytes=io.BytesIO() img.save(img_bytes, format='PNG') img = io.TextIOWrapper(img_bytes) pt = Pt.objects.create(title=title,fil=img) basically this will return an error when trying to upload an image: -
tuple' object has no attribute 'is_valid'
I'm just new at coding and I tried to create a user registration and watch the tutorials on youtube, I followed all the steps but suddenly got an error in views.py and this is the message error I got from django.contrib.auth.forms import UserCreationForm from django.contrib import messages # Create your views here. from fyeah import f def register(request): if request.method =='POST': form = UserCreationForm(request.POST), if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('I-grade-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form})``` this is where my error appears ``` if form.is_valid():``` -
Django push notifications: InvalidRegistration with correct registration_id
I'm trying to send push notifications with my Django App and the library django-push-notifications to specific Android devices using FCM. I always get the same error: {'multicast_id': 7577544316157180554, 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration', 'original_registration_id': <token>}]} I'm using a registration_id provided to me from an actual Android Device. I've tested that registration_id using the Firebase dashboard to send a test message and it works perfectly there. But my Django request never works. Is there anything else I'm missing from configuration? Do I need to enable something else to be able to send the push from besides the test tool of Firebase? -
Django multiple user roles in Admin panel
I am trying to build an electronic information system for one teacher and students. Using the tutorial shown here: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html , in my models.py I have implemented the student and teacher models this way: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) f_name = models.CharField(max_length=20) l_name = models.CharField(max_length=30) parent_tel_numb = models.CharField(max_length=13) parent_f_name = models.CharField(max_length=20) parent_patronimic = models.CharField(max_length=30) parent_l_name = models.CharField(max_length=30) group = models.ForeignKey(Group, to_field='id', on_delete=models.SET_NULL, blank=True, null=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) In settings.py I have added AUTH_USER_MODEL = 'main.User' Meanwhile, I am not sure about the proper way to register these models in admin.py. Do I need to register all of them just as basic models? For now I have only registered the User model: from django.contrib import admin from .models import User admin.site.register(User) After entering the Admin panel of my app I noticed that the User model is not located in AUTHENTICATION AND AUTHORIZATION section, but is in the MAIN section instead. Please, can someone suggest what is the proper way to implement this? I have just started learning Django and am really new to this -
PostgreSQL full text search weight/priority
I am using Full Text Search in PostgreSQL through Django. I want to associate weights to searchterms. I know it is possible to associate different weights to different fields, but i want to have different weight on searchterms. Example: from core.models import SkillName vector = SearchVector( "name", ) search = SearchQuery("Java") | SearchQuery("Spring") search_result = ( SkillName.objects.all() .annotate(search=vector) .filter(search=search) .annotate(rank=SearchRank(vector, search)) .order_by("-rank") ) for s in search_result.distinct(): print(f"{s} rank: {s.rank}") And now i want "Java" to be more important than "Spring" and get ranking accordingly. I guess i could do 2 different searches and multiply the ranks with factors, but is there a better way ? Is it really that weird to want to associate different priority to searchterms ? Generated SQL for reference, i honestly dont think this is possible in Django right now anyway and we might need the help of a PostgreSQL-guru. SELECT DISTINCT "core_skillname"."id", "core_skillname"."name", to_tsvector(COALESCE("core_skillname"."name", '')) AS "search", ts_rank(to_tsvector(COALESCE("core_skillname"."name", '')), (plainto_tsquery('Java') || plainto_tsquery('Spring'))) AS "rank" FROM "core_skillname" WHERE to_tsvector(COALESCE("core_skillname"."name", '')) @@ (plainto_tsquery('Java') || plainto_tsquery('Spring')) ORDER BY "rank" DESC;``` -
Unable to translate timezone for Django
I am following the polls tutorial. " While you’re editing mysite/settings.py, set TIME_ZONE to your time zone. ... TIME_ZONE='UTC' " I tried 'UTC-08:00' [per my pc's timezone] but that gave me an error. I viewed the link in the tutorial for a list of timezones, and found mine stated in the following way: US +433649−1161209 America/Boise Mountain - ID (south); OR (east) Canonical −07:00 −06:00 I am unsure of how to translate the above into an input for Django. -
How to solve a post request error on django
I encountered certain post request error on django. When I click on the form submit button the error pops up stating that django can't find the page I'm asking for. Please I want to know where I'm getting it wrong because I'm still a beginner in django. def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Account' message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) urlpatterns = [ path('account/register', views.account_register, name='register'), path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate') ] urls.py(main django app) urlpatterns = [ path('', include('account.urls', namespace='account')), ] views.py def account_register(request): if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Account' message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) -
How to return single object as a json response inside django function?
I just want to get a single object of User model as a json response. I couldn't figure out how can i do that.. right now i'm getting an error that 'User' object is not iterable Here is my function: def some_view(username_to_toggle): print(username_to_toggle,"User to togle") user = User.objects.get(username__iexact=username_to_toggle) print(user,"User object") user_json = serializers.serialize('json', user,many=False) print(user,"User json") return HttpResponse(user_json, content_type='application/json') -
Neovim for Django: metaclasses are not recognized
Image of Error Message in Neovim I have been trying to configure my neovim for django development and everything seems fine except for this issue I am having with fields in metaclasses. the image provided gives a snapshot and the code is as follows: class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) the linting error indicates that it cannot access member objects for the Snippet class. I am using coc-pyright with default settings. I tried playing around with the settings by enabling pylint and installing pylint-django in my project as a dev dependency but that was unable to resolve the issue. How would I fix this issue? Does anyone have a recommended setup for Django development in nvim? -
django-ckeditor change upload path prefix
I want to change the prefix of upload path in django-ckeditor. By default it generates subdirectories by using username and date so something like: /media/uploads/username/year/month/day/uploaded_file The documentation says: Set the CKEDITOR_RESTRICT_BY_USER setting to True in the project’s settings.py file (default False). This restricts access to uploaded images to the uploading user (e.g. each user only sees and uploads their own images). Upload paths are prefixed by the string returned by get_username. If CKEDITOR_RESTRICT_BY_USER is set to a string, the named property is used instead. After few tries, still can't figure out how to configure this to handle prefix of uploaded files. Thanks for any help. -
How to manage a Django Rest Framework codebase when API versions change?
There's plenty of topics about api versioning. But many don't discuss how versioning affects the codebase. How do you go about managing the codebase when the version changes? Examples would be appreciated. Example: codebase for version 1 Default versioning: NamespaceVersioning Model: class Book(models.Model): name=models.CharFiedl(max_length=20) pages=models.IntegerField() view: class BookView(views.ViewSet): def List(self, request): books = Books.objects.all() return Response(BookSerializer(books, many=True).data) serializer: class BookSerializer(serializers.ModelSerializer): class Meta: fields = ['name', 'pages'] What would the code and folder structure for version 2 look like when breaking changes are introduced? -
Python SQLite3 - Is there a way to search for a table based on user input without injection risk?
I have a website where a user can select from multiple tables to browse data, but I am having trouble accomplishing this in a way that doesn't expose my website to injection since you cannot do parameterized searches for tables, columns ect. What I want to do is this: cursor.execute("SELECT * FROM ?", (selected_table,)) which returns an error and forces me to do this to make it work: cursor.execute("SELECT * FROM {0} ".format(selected_table)) which exposes my server to injection. Is there any way around this? -
AJAX Call Prompting Up the "Print Page" Option
I have a dropdown that on change, calls an AJAX function, which just stores the dropdown value into the session (this is not the issue, I've commented it out and same issue occurs), and when this AJAX function comes back successfully, it seems to prompt up the Print Page feature. I feel like this help with some answers: the url is "/app/newgroup/230/2/ajax_settings_dropdown?dropdownValue=224". I mention this because based on that second number (in this URL, it is 2), it'll prompt the print page that amount of times every time something is selected. Dropdown and AJAX fnc: <div class="form-group"> <b><label>Choose settings from existing project:</label></b> <select class="form-control" id="ProjectSelect"> <option selected="selected" disabled value=0> Select a setting </option> {% for sID in settingsInfo %} <option value="{{ sID.1 }}"> {{sID.0}} </option> {% endfor %} <option value=0> None </option> </select> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $('#ProjectSelect').on('change', function () { var units = { dropdownValue: $(this).val() }; $.ajax({ url: 'ajax_settings_dropdown', async: true, data: units, success: function () { print("SUCCESS"); }, error: function () { print("Oops"); } }); }); </script> views.py: def update_settings_dropdown(request, project_id, groups_num): dropdownValue = request.GET.get('dropdownValue') if dropdownValue != 0: currG_sID = request.session.get('createdGroups_sID') currG_sID.append(dropdownValue) request.session['createdGroups_sID'] = currG_sID return render(request, 'EmptyPage.html') urls.py path('app/newgroup/<str:project_id>/<str:groups_num>/ajax_settings_dropdown', views.update_settings_dropdown) -
django custom Func for specific SQL function
I'm currently performing a raw query in my database because i use the MySQL function instr. I would like to translate is into a django Func class.I've spend several days reading the docs, Django custom for complex Func (sql function) and Annotate SQL Function to Django ORM Queryset `FUNC` / `AGGREGATE` but i still fail to write succesfully my custom Func. This is my database from django.db import models class Car(models.Model): brand = models.CharField("brand name", max_length=50) #then add the __str__ function Then I populate my database for this test Car.objects.create(brand="mercedes") Car.objects.create(brand="bmw") Car.objects.create(brand="audi") I want to check if something in my table is in my user input. This is how i perform my SQL query currently query = Car.objects.raw("SELECT * FROM myAppName_car WHERE instr(%s, brand)>0", ["my audi A3"]) # this return an sql query with one element in this example I'm trying to tranform it in something that would look like this from django.db.models import Func class Instr(Func): function = 'INSTR' query = Car.objects.filter(brand=Instr('brand')) -
How can i check if my query was done successfully
I'm working on a small project using Django/Rest with Tenants-Package and Celery so i would like to know if my tenants has been created successfully or no how can i check ( any way to return true or false ) by cheking if is saved or no ? this is my code : @shared_task @transaction.atomic def createUserTenant(userid): with schema_context('public'): userInQuestion = CustomUser.objects.get(id=userid) # create your first real tenant tenant = Client(schema_name=str(userInQuestion.username), name=userInQuestion.first_name + '_' + userInQuestion.last_name, paid_until='2014-12-05', on_trial=True) tenant.save() # migrate_schemas automatically called, your tenant is ready to be used! # Add one or more domains for the tenant domain = Domain() domain.domain = str(userInQuestion.username) + settings.BASE_URL domain.tenant = tenant domain.is_primary = False domain.save() -
Drawing graphs based on data in the database
I need to draw graphs based on data from models. How can this be done? Model adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True) carnumber = models.CharField(max_length=150) amountoftime = models.IntegerField() price = models.FloatField() telephone = models.CharField(max_length=20) email = models.EmailField(null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True) expirationdate = models.DateField(null=True) expirationtime = models.TimeField(null=True) enddateandtime = models.DateTimeField(null=True,blank=True) I need to create a schedule for a certain period of time(month, day, week) -
How do I integrate a filter into my Django website?
I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download. So far, it's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature). So, for example, I want to add radio buttons where, before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, it should take that into account when it's writing to the file that it presents for the user to download. I would provide some code, but I'm just not sure where to start. So far, I've created most of the site in views and my template. Can I do all of this in views? Should I put the files of the characters I want to filter in my static files? Should I do it through a … -
"placeholder-shown" selector not working with django forms
I have input fields that lower label when something has been typed in it. paste bin css <div class="form__group"> <input type="text" class="form__input" id="name" placeholder="Full name" required="" autocomplete='off' /> <label for="name" class="form__label">Full Name</label> </div> But, when I use django forms, they don't work at all <div class="form__group col"> {{createSet.title}} <label for="id_title" class="form__label">Title</label> </div> -
django - Foreign key not getting created from model
I have created below model with foreign key but migration file does not have any foreign key and hence in sql server database also foreign key relationship is not getting created models.py class RetailerMaster(models.Model): id = models.PositiveIntegerField(unique=True) name = models.CharField(max_length=1000) address = models.CharField(max_length=4000) city = models.CharField(max_length=100) state = models.CharField(max_length=100) pincode = models.CharField(max_length=100) contact_name = models.CharField(max_length=500) email = models.EmailField() phone = models.CharField(max_length=15) erp = models.CharField(max_length=1000) remark = models.CharField(max_length=4000) def __str__(self): return self.id class FileUpload(models.Model): retailer_id = models.ForeignKey(RetailerMaster, on_delete=models.CASCADE), file = models.FileField(upload_to='files') file_upload_datetime = models.DateTimeField() file_name = models.CharField(max_length=1000) migrations file migrations.CreateModel( name='FileUpload', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(upload_to='files')), ('file_upload_datetime', models.DateTimeField()), ('file_name', models.CharField(max_length=1000)), ], ) What am i doing wrong that foreign key is not getting created. Basically, what i am implementing is, for one RetailerMaster record multiple files can be uploaded.