Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get json data from frontside as a input in django?
Actually I m working on Django celery. my leader assign a task that using celery u have to create a task using celery and take Json data as a input from front side and using this celery task then store that Json data in a file. -
how do I the functionality of add new friends reject and delete friend in my user app using django?
Want to Add Friend, Send Friend Request, Accept Friend Requests features in my Django website This is my users>> models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) this is my models>> views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) kindly help me out to add friends request functionalities to my project as I'm new to Django, help … -
Bulk update of a model field based on a condition
I have a 5 column model with around 10,000+ lines of data. Now I want to update one column of all the lines based on other column values. -
Failing to get user logged in user object in django
How can I get logged in user in django. When I tried i get the following error 'User' object is not iterable. My code is as follows def createRoom(request): return HttpResponse(request.user) -
html files for django-rest-passwordreset package
I need to set a password reset URL for our website and I used Django rest framework package "django-rest-passwordreset" , I followed the documentations but there is no HTML file to send email in it named "user_reset_password.html", does anybody have it? thank you so much -
'Settings' object has no attribute 'TRANSLATABLE_MODEL_MODULES'
I changed computer. 'Settings' object has no attribute 'TRANSLATABLE_MODEL_MODULES' when I try to run my project on windows computer.I am getting the error. how can i get over this -
Getting Error In Live server TemplateDoesNotExist in django project but in local server same code worked
Hi Every on i am getting error on live server (TemplateDoesNotExist) but when used same code on local server there is no issue found infact rest of all tempalate working, issue face on only one tempalate, can anyone help me out. forms.py class IncentiveForm(forms.ModelForm): start_date = forms.DateField(label='Start Date', required=True, widget=forms.DateInput( attrs={'placeholder': 'Start Date', 'class': 'datepicker form-control'})) end_date = forms.DateField(label='End Date', required=True, widget=forms.DateInput( attrs={'placeholder': 'End Date', 'class': 'datepicker form-control'})) incentive=forms.CharField(label='Incentive Amount', max_length=50, required=True) no_of_trips=forms.CharField(label='No. of Trips', max_length=20, required=True) city = forms.ModelChoiceField(required=True, queryset=City.objects.all()) class Meta: model=Incentive fields= ['start_date','end_date','no_of_trips','incentive','city'] def __init__(self,*args,**kwargs): # self.request = kwargs.pop('request', None) super(IncentiveForm,self).__init__(*args,**kwargs) views.py def incentive_form(request): if request.method == "GET": form=IncentiveForm() return render(request,'hiringprocess/incentive.html',{'form':form}) else: form=IncentiveForm(request.POST) if form.is_valid(): form.save() # uid=Incentive.objects.last() messages.success(request,'Incentive data Created successfully!') urls.py path('incentive/add',views.incentive_form,name="incentive_form") hiringprocess/incentive.html <form roll="form" method="POST" action="/fleet/incentive/add" autocomplete="off"> {% csrf_token %} <div class="box-body"> <div class="col-md-6"> {{ form.start_date|as_crispy_field}} </div> <div class="col-md-6"> {{ form.end_date|as_crispy_field}} </div> <div class="col-md-6"> {{ form.no_of_trips|as_crispy_field}} </div> <div class="col-md-6"> {{ form.incentive|as_crispy_field}} </div> <div class="col-md-6"> {{ form.city|as_crispy_field}} </div> <div class="row"> <div class="col-md-6"> <button type="submit" class="btn btn-primary" style="margin-bottom:20px;"> <span class="glyphicon glyphicon-ok-circle"></span> <span id="btn_txt">Created</span> </button> </div> </div> </div> </form> -
Django migration cannot create model table in DB
I have a model admin_portal.User. I can make migrations files for it, I can see 0001_initial.py under admin_portal/migrations. However, when I run python3 manage.py migrate, I got Operations to perform: Apply all migrations: admin_portal, auth, common_app, contenttypes, knox, sessions Running migrations: Applying admin_portal.0001_initial... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying knox.0001_initial...Traceback (most recent call last): File "/home/lexl/.local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist In the DB, I only see these tables List of relations Schema | Name | Type | Owner --------+------------------------+-------+-------- public | auth_group | table | user public | auth_group_permissions | table | user public | auth_permission | table | user public | django_content_type | table | user public | django_migrations | table | user Why the user table is not created? admin_portal.0001_initial is applied, I shouldn't have permission issue to create tables, right? -
How to add ordering to Case, When conditions in django
There are two fields: start_date and end_date. (DateField). Standard for sorting. Both start_date and end_date are empty values. (start_date = Null, end_date = Null) Start_date Most recently and end_date is empty values (start_date = not null, end_date = Null) If both start_date and end_date have values, end_date most recently (start_date = not Null, end_date = not Null) If both start_date and end_date have values, start_date most recently (start_date = not Null, end_date = not Null) Ex) I want start end 1. null null 2. null null 3. 2021-10-01 null 4. 2021-09-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 I tried Model.objects.annotate( order1=Case( When(Q(start_date__isnull=True) & Q(end_date__isnull=True), then=0), When(Q(start_date__isnull=False) & Q(end_date__isnull=True), then=1), When(Q(start_date__isnull=False) & Q(end_date__isnull=False), then=2), output_field=IntegerField() ), ).order_by('order1') result start end 1. null null 2. null null 3. 2021-09-01 null # change 3, 4 4. 2021-10-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 How can I solve the complicated order by in django? -
Django_googleapi_project: AttributeError at /profile Exception Value: 'User' object has no attribute 'userprofile'
I have been following this video to learn django: https://www.youtube.com/watch?v=_vCT42vDfgw. I have followed to the end, have run the server at <localhost port 8000>. I can signup users but when I try to update a user profile (clicking the 'Update User Profile' link in the view, I get an 'AttributeError at/profile' which I have not been able to resolve despite checking in with the tutor's source code (everything looks the same) looking up answers to similar questions on stack overflow here. Any help would be much appreciated...** Here' the error test: <!-- language: lang-none --> Environment: Request Method: GET Request URL: http://localhost:8000/profile Django Version: 3.2.9 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users'] Installed 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'] Traceback (most recent call last): File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\django_googleapi_project\users\views.py", line 48, in profile_view up = user.userprofile File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\utils\functional.py", line 247, in inner return func(self._wrapped, *args) Exception Type: AttributeError at /profile Exception Value: 'User' object has no attribute 'userprofile' Here's the code sample in the users\views.py file that contains the 'userprofile' object: from django.shortcuts import render, … -
Sqlite - Django: table has 13 columns but 14 were supplied
I am trying to export a .csv file into my database and the .csv file has 13 columns but for some reason when I try to export it is saying that I have 14 columns instead. I don't know if it is an issue with how I set up the ForeignKey and PrimaryKey but I can't figure this out. models.py class Dealer(models.Model): dealersName = models.TextField(('DealersName')) zipcode = models.CharField(("zipcodex"), max_length = 15) zipcode_2 = models.CharField(("zipCode"), max_length = 15) state = models.CharField(("state"), max_length=5) address = models.TextField(("Address")) ids = models.BigIntegerField(("ids"), primary_key=True) def __str__(self): return self.dealersName class DealershipListing(models.Model): vincode = models.CharField(('vinCode'), max_length=255, primary_key=True) price = models.IntegerField(('price')) msrp = models.IntegerField(('msrp')) mileage = models.TextField(('mileage'), max_length=9) is_new = models.BooleanField(('isNew')) first_seen = models.DateField(("first_seen")) last_seen = models.DateField(("last_seen")) model = models.CharField(("Models"), max_length= 255) make = models.CharField(("Make"), max_length=255) year = models.CharField(("Year"), max_length= 4) ids = models.ForeignKey(Dealer, on_delete=CASCADE) color = models.CharField(("ExtColor"), max_length=255, null=True, blank = True) intcolor = models.CharField(("IntColor"), max_length=255, null=True, blank=True) def __str__(self): return self.year + " " + self.make + " " + self.model and the csv file has vincode,price,msrp,mileage,is_new,first_seen,last_seen,model,make,year,dealerID,ExtColor,IntColor as columns. I would appreciate every help I can get. -
Django Rest Framework API sets image to default image even if user uploads an image
When I try to create a new user through DRF, the avatar field displays the default image even if the user uploads an image. When I try to create a user with an image through the admin panel it works fine. So I'm assuming that I'm missing something in my serializer. Custom User Model class myAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email') if not username: raise ValueError('Users must have an username') user = self.model( email = self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password=password, username=username, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) profileimage = models.ImageField(default='default.jpg') date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = myAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True User serializer UserModel = User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], email=validated_data['email'], ) return user class Meta: model = UserModel # Tuple … -
queryset in admin.py never gets executed in django 2.2
My code was originally implemented for Django 1.8 now (after necessary changes) I'm running it with Django 2.2. Seems that the following was planned to show non-super-user only his/her own files: class Tiedostot3Admin(admin.ModelAdmin): fields = ['otsikko', 'kuvaus', 'tiedosto'] list_display = ('otsikko','paivitetty') inlines = [ Liitet3Inline, ] def queryset(self, request): print("queryset, request.user", request.user) qs = super(Tiedostot3Admin, self).queryset(request) if request.user.is_superuser: return qs return qs.filter(owner=request.user) def save_model(self, request, obj, form, change): print("save_model, request.user", request.user) obj.owner = request.user obj.save() When saving new files I can see save_model() executed, but I don't know how to get queryset() executed. It seems that it always shows the same list for all users. models.py: class Tiedostot3(models.Model): otsikko = models.CharField(max_length=250) kuvaus = RichTextField(blank=True) paivitetty = models.DateTimeField(auto_now_add=True, verbose_name="Päivitetty") tiedosto = models.FileField(upload_to='poytakirjat', verbose_name="Tiedosto", blank = True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) class Meta: ordering = ['-paivitetty'] verbose_name = "tiedosto" verbose_name_plural="tiedostot" def __unicode__(self): return unicode(self.otsikko) class Liite3(models.Model): otsikko = models.CharField(max_length=250) tiedosto = models.FileField(upload_to='poytakirjat') doku = models.ForeignKey(Tiedostot3, related_name="liitteet", on_delete=models.CASCADE) class Meta: verbose_name_plural="Liitteet" def __unicode__(self): return unicode(self.otsikko) the page: -
change background with Css
I want to change my background site so at first it changed but when I trying to change it again to another color it not happen I link my code file with style.css file with this code {% load static %} style.css (code):in my style.css folder body{ background-color: blue;} first I changed the background to brown then I want to change it to blue but it doesn't change (also when I go to my site it still brown also when I use this code in style.css (body{ background-color: blue} when I click on inspect it appears to me body{ background-color: brown} ) -
Customize Django ListView Pagination
im implementing a Django ListView for a Search View. The search is done using Elasticsearch and django-elasticsearch-dsl. Im actually getting a pagination of just 10 items because thats the amount of contents that Elasticsearh answers by default. I could ask elasticsearch to get all the contents but it would be really unnefficient since im only showing like 50 of them. Is there any way that Django reads the pagination information from other than the queryset? This is what my view looks like: from .elastic import search class SearchView(ListView): template_name = "search/index.html" paginate_by = 50 def get_queryset(self): keyword = self.kwargs['keyword'] lang = get_language() return search(keyword, lang) -
Upgrading Oracle XE from 11g to 21c broke django's ability to talk to TNS Listener
I have an old application that is running django 1.10 with an oracle XE 11g back end. We are trying to upgrade the XE to 21c. The issue is that django cannot find the TNS listener even though it is there and running. sqlplus works correctly so there is no issue with the listener itself. The django application and the XE database are both running on the same server so there is no networking issue. The main change as far as I can tell between the 11g and 21c is that the newer oracle database has plugin databases and needs to be addressed via the easy connect naming mechanism. Is that supported by django 1.10? Directly using cx_Oracle to connect to the database from python3 also works without throwing errors. Any pointers appreciated. -
Add html tag and style on CKEditor Textarea
I'm using django ckeditor, is it possible to add html and css on textarea? Something like this: -
How to track frontend app screens in backend
I have a application with django rest and flutter. In frontend there are 20 screens. Now i want track each screen like if user uninstall app and comeback after 1 year he will able to land on previous screen. So suggest me good approach form backend perspective -
Failed to save in SQLite database django
I have the following codes: models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField() freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(auto_now_add = True, null = True) date_modified=models.DateTimeField(auto_now = True, null = True) version=models.IntegerField(default = 1) class Job_removed(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField(null = True) freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(null = True) date_modified=models.DateTimeField(default=timezone.now) version=models.IntegerField(null=True) views.py def job_delete(request,pk): job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) if request.method == "POST": jobr = JobRemovedForm(request.POST) if jobr.is_valid(): jobr.jobname = job.jobname print(jobr.jobname) jobr.owner = job.owner print(jobr.owner) jobr.enabled = job.enabled print(jobr.enabled) jobr.start_date = job.start_date print(jobr.start_date) jobr.start_time = job.start_time print(jobr.start_time) jobr.date_added = job.date_added print(jobr.date_added) jobr.version = job.version print(jobr.version) jobr.save() return redirect('/job/', {'job':Job.objects.all}) else: jobr = JobRemovedForm() return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr}) return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail}) Output of my powershell for those print commands: In the database (SQLite): What I am trying to do is to copy from the entry from … -
Finding median in annotation django
Im using MySQL server as database and need to find median price in query like this: price_query = Product.objects \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(avg_price=Avg('Price'), std_price=StdDev('Price'), count=Count('Price'), max_price=Max('Price'), min_price=Min('Price'), median='???') \ .order_by('dt') response is look like this {"date":"2021-05-01T00:00:00Z","avg_price":4326.666666666667,"std_price":20.548046676563168,"min_price":4300.0, "max_price":4350.0,"count":3} Any help is highly appreciated. -
Django - Getting all URLs for folders and subfolders
I am building an image gallery application that does not require a database. The user places a folder containing images and its subfolders into the '/media' directory, and python scripts gather data such as the full path, the name of the directory, the image path/names inside, and the subfolders and their images, it sends this data to the view and it's rendered in the template. The first folders all work, I can access them, see their content, but I can't access the subfolders inside those galleries. I want the url to look something like this but the subfolder part isn't cooperating. website.com/directory/<folder1>/<subfolder>/ The first folder is working with str:data, it displays. pagination works, the images are rendered to the template, but I don't know how to get the urls to work for all subsequent directories. path(r"directory/<str:data>/", views.directory, name="directory"), This is what the code looks like for that right now, I thought slug would be appropriate considering the file names can be a variety of different things. urls.py path(r"directory/album/<slug:item>", views.album, name="album") view.py def directory(req, data): sl = MyClass() dir = data albums = sl.folder_path(data, include_gallery=True) img_list = sl.list_files(dir) paginator = Paginator(img_list, 9) page_number = req.GET.get('page') page_obj = paginator.get_page(page_number) return render(req, "galleries/galleries.html", … -
Where do POST request from a form send the data to in django
Suppose I have created a login page and a register page. both have forms with same name attribute say "username" in the input tag. login page calls views.login function and register page calls views.register function. Now in register page I am submitting a form with some username and saving it in a variable in views.register something like this username = request.POST["username"] views.login too have the same code username = request.POST["username"] My query is where will the username go? only in the views.register function or in views.login function too? -
Using get_model in a custom slug generator raises django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I created a custom slug generator function to use in multiple models across multiple apps. To achieve this I pass the relevant django app name and django model as string parameters to the function, so the function can check if the slug is unique for that model: def slug_generator(django_app, django_model, field_name, slug_len, prefix=""): unique_pk = False model = apps.get_model(django_app, django_model) while not unique_pk: random_pks = random.sample( string.ascii_uppercase + string.digits + string.ascii_lowercase, slug_len) new_pk = ''.join(random_pks) search_query = {field_name: new_pk} try: if not model.objects.filter(**search_query).exists(): unique_pk = True except: if not model.objects.all().exists(): unique_pk = True return prefix + new_pk called in models.py like so: class Form(models.Model): form_id = models.CharField( max_length=25, default=slug_generator('forms', 'Form', 'form_id', 25)) The function was working fine when I only was using it for a single model (so i wasn't using get_model, I just hard coded the model it was for). Since adding get_model, this error is thrown on startup django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I tried putting the following before my function: import django django.setup() It only led me to a new error RuntimeError: populate() isn't reentrant, so it makes me think that there is a better way to write the function. Is what I am trying to achieve … -
htmx and django Class Based Views
I was traying to convert the countdown tutorial from here[1] to Class Based Views but I do not know what is missing. [1]https://htmx-django.com/blog/how-to-implement-countdown-timer-in-django-via-htm views.py class TimeDifferenceView(TemplateView): delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now() template_name = 'base.html' days = delta.days seconds = delta.seconds % 60 minutes = (delta.seconds //60) % 60 hours = delta.seconds // 3600 def get_context_data(self,*args, **kwargs): # Call the base implementation first to get the context context = super(TimeDifferenceView, self).get_context_data(*args, **kwargs) # Create any data and add it to the context. context['days'] = self.days context['seconds'] = self.seconds context['minutes'] = self.minutes context['hours'] = self.hours return context base.html <div id= "time" class="d-flex justify-content-between" hx-get="{% url 'time_difference' %}" hx-trigger="every 1s" hx-select="#time" hx-swap="outerHTML" > <div> <h5>Days</h5> <p> {{days}} </p> </div> <div> <h5>Hours</h5> <p> {{hours}} </p> </div> <div> <h5>Minutes</h5> <p> {{minutes}} </p> </div> <div> <h5>Seconds</h5> <p> {{seconds}} </p> </div> </div> -
How do I resolve "Invalid service account certificate. Certificate must contain a "type" field set to "service_account"" error to run a Django server?
I'm trying to run a Django server. I have installed python 3.8.2 and the rest of the requirements are installed through a requirements.txt file in the project folder. After installing the requirements, I've tried to run the server but it generates the following error: ValueError('Invalid service account certificate. Certificate must contain a ' ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account". I have tried re-installing python, re-installing the requirements, running it in a virtual environment but nothing has worked so far. It would be really great if someone guides me how to resolve this error and run the server. Error with complete traceback: https://drive.google.com/file/d/1nZdOXKjDgOnd96yJBfhZbWSZ_jdDjTuK/view?usp=sharing Manage.py: https://drive.google.com/file/d/1eXXvy8Jm2GmqmYD0pmG9CJUF-QEYchS-/view?usp=sharing Requirements.txt: https://drive.google.com/file/d/1hOsZrYactHs4nTmfbshPvIV2xAvzuaq4/view?usp=sharing