Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Assertion error 400 in the following problem?
I am working on Django project. I am writing a test case for the following model: class Meeting(models.Model): team = models.OneToOneField("Team", on_delete=models.CASCADE) created_at = models.DateTimeField() def __str__(self) -> str: return self.team.name The code for Test case is as follows: class MeetingTestCase(BaseTestCase): def test_meeting_post(self): self.client.force_login(self.owner) meeting_data = { "team": self.team.id, "created_at": "2023-01-12T01:52:00+05:00" } response = self.client.post("/api/meeting/", data=meeting_data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Inside .setup() function, I have created a team object: self.team = factories.TeamFactory(name="Team", organization=self.organization) This is my factory class: class TeamFactory(factory.django.DjangoModelFactory): class Meta: model = models.Team But My test case is failing and I have following assertion error: self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 which means there is something wrong with my request. What wrong am I doing? -
I have problem with updating profile photo in Django
I am trying to update Profile photo with Django According to yt tutorials I created form for updating photo: class UserProfileForm(forms.ModelForm): class Meta: model = User_Model fields = ["profile_photo"] And this is my class to Change photo in views: class UpdatePhoto(TemplateView): template_name = "Messenger/update_photo.html" profile_form = UserProfileForm def post(self, response): data = response.POST file_data = response.FILES profile_form = UserProfileForm(data, file_data, instance=response.user.profile) if profile_form.is_valid(): profile_form.save() return redirect("/") print("rere") context = self.get_context_data(profile_form=profile_form) return self.render_to_response(context) My Model: class User_Model(models.Model): user = models.OneToOneField( User, null=True, on_delete=models.CASCADE, related_name="profile" ) profile_photo = models.ImageField( upload_to="images/", default="default_photo.jpg", null=True, blank=True ) chats = models.ManyToManyField(User, related_name="chats", blank=True) blocked_list = models.ManyToManyField(User, related_name="blocked_list", blank=True) I was trying with and without 'response.POST', result was the same, it does not update. However when I try to print 'file_data' I get something like this: <MultiValueDict: {'Browser': [<InMemoryUploadedFile: thumb.jpg (image/jpeg)>]}> Main Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "static/" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" And main urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("Messenger.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to check if a function parameter is a database model class?
I have a Django database models like: from django.db.models import Model class Student(Model): ..... class Grade(Model): ..... If I have a function that takes a model class as a parameter. How to check if the input parameter is a generic class that inherits from Model class? def do_stuff(model_class): ## check if model_class is a child class of Model -
Can I make changes in manage.py?
I am doing a django project where I want my manage.py to run the server automatically(python manage.py runserver command) if its called. I believe that manage.py uses "execute_from_command_line". So is it possible or I have to find some other way to solve my problem. I want my manage.py to run the server automatically -
Where to create .aws/config in my django project?
how to add .aws/config in django project on this file structure Hello I'm Studying Front-End Development and I was proceeding E-commerse Project with pre-made API, and Design. but they suddenly shut down the server and gave me away the backend Code without any explaination. the thing is I have no idea what to do. So I excute following command from README Install Virtual Environment & Dependency # ./backend python -m venv .venv source .venv/bin/activate pip install -r requirements.txt python manage.py githooks once I excute python manage.py githooks it says botocore.exceptions.NoCredentialsError: Unable to locate credentials Set AWS Profile vi ~/.aws/config ... [profile incourse-commerce] aws_access_key_id=** aws_secret_access_key=** region = ap-northeast-2 I think I should add my IAM credentials on this application but I dont know where to add ./aws/config on this file structure enter image description here please help ㅠㅠ -
Как можно реализовать GET запрос в Django на определенный URL и в качестве результата вывести в шаблон нужные поля из JSON?
Во views создал функцию, на чистом Python нужный резуальтат есть, не получается прокинуть в шаблон нужные поля и дальше перебрать их, пробовал с JsonResponse def index(request): str_input = 'https://upload.peertube.datacenter.by/w/h3e6b9MaFqbc5u4cZUxyQh' new_str = str_input.replace('/w', '/api/v1/videos') response = request.GET.get(new_str) links = json.loads(response) return render(request, 'hls_links/index.html', {'links': links}) -
Django form update optimistic locking, version based
I've got django model and view implemented like here: (+mysql db) class MyModel(models.Model): name = models.CharField(max_length=100) version = models.IntegerField(default=1, editable=False) def updateModel(request, id): toUpdate = MyModel.objects.get(pk=id) if request.method=='POST': form = MyModelForm(request.POST, instance=toUpdate) if form.is_valid(): actual = MyModel.objects.get(pk=id) if (actual.version == form.instance.version): form.instance.version = form.instance.version+1 form.save() return redirect('somewhere') else: #some error form = MyModelForm(instance=toUpdate) return render(request, 'somwhere2/createupdate.html', {'form':form}) The scenario is, - current model value is name="aaa", version=1 2 users open edit form, first, changes name "aaa" to "bbb", and saves, second changes name "aaa" co "ccc" and saves. I'd like that versioning mechanism to prevent such scenario, but I'm unable to achieve it... How to implement it? I've read everything I could about django optimistic locking etc, but unable to achieve it, -
Access SharePoint Folder using Service account
I have a SharePoint folder where the url looks like: "team..com/sites//Documentation/Forms/All items.aspx Now the requirement is to access this url using a service account and Django. Can you help me a way? Thanks in advance We have looked for different cases but haven't been successful at all. -
Pagination does not seem to be working in Django rest api with GET method
I have been trying to paginate by json response but in vain. below are my code snippets. views.py This gives me the entire result. The reason i'm converting to a dataframe is that i want to do some data cleaning and minipulation. class LogsNewAPI(APIView): pagination_class=CustomPagination def get(self,request, *args, **kwargs): envid = self.kwargs.get('envid') nodeid = self.kwargs.get('nodeid') startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=PegaAlerts.objects.filter(envId=envid, serverId=nodeid, generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') df = read_frame(filter_list) json = df[['generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso') return HttpResponse(json, content_type = 'application/json') i have also tried as below and that gives the error: LogsAPI requires either a 'template_name' attribute or a get_queryset() method that returns a QuerySet class LogsAPI(ListView): pagination_class=CustomPagination def get_queryset(self): startdatetime = self.request.GET.get('startdatetime') enddatetime = self.request.GET.get('enddatetime') filter_list=Alerts.objects.filter(envId=self.kwargs['envid'], serverId=self.kwargs['nodeid'], generateddatetime__lte=enddatetime, generateddatetime__gte=startdatetime,).order_by('generateddatetime') df = read_frame(filter_list) json = df[[ 'generateddatetime','msgid','fullLine']].to_json(orient='records',date_format='iso') return HttpResponse(json, content_type = 'application/json') pagination.py class CustomPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' page_query_param = 'page_number' not sure if I'm missing something. Any suggestions or redirection would be of great help..Thanks!! -
How to create an registration form in django and create an qr code for the given data also store data in mysql database
create an platform with Django that gets input from the user about their name, states and cities in India and create QR code for it , also the data needs to be stored in Mysql database. The states and cities should be in dependent dropdown. If anyone can create this project, please send the code to me via email. Thanks for accepting! -
How to make the list into table Django
I have got an a list: [{'name': 'WEB-Разработчик/программист (SEO-правки)', 'description': 'Hastra Agency ищет разработчика с опытом работы с связи с ростом отдела SEO-продвижения. Требуемый о...', 'key_skills': ['HTML', 'CSS', 'MySQL', 'PHP', 'SEO'], 'employer': 'Hastra Agency', 'salary': 'None - 60000 RUR', 'area': 'Москва', 'published_at': '2022-12-12', 'alternate_url': 'https://hh.ru/vacancy/73732873'}, {'name': 'Веб-разработчик golang, react, vue, nuxt, angular, websockets', 'description': 'Обязанности: Стек: react, vue, nuxt, angular, websockets, golang Поддержка текущего проекта с сущест...', 'key_skills': [], 'employer': 'МегаСео', 'salary': '150000 - None RUR', 'area': 'Москва', 'published_at': '2022-12-12', 'alternate_url': 'https://hh.ru/vacancy/73705217'}, ....., ...... array is with 10 list's How can i make it into table? csv file? columns - name, description, key_skills, .... rows - 1, 2, 3, 4, 5 ... I need to make this table in Django, how can i do it? -
How To Make A Payment Gateway, With Both Python 3 And Django?
How do i make a payment gateway templet, That accepts both Debit, Creddit card (Visa, Mastercard, and American express), Cryptocurrencies (Bitcoin, Ethereum, Dogecoin, and Monero), By using both Python 3, And the Django framework, For my e-commerce website? It will be an open-source payment gateway templet, That could communicate directly with both Visa, Mastercard, American express, Coinbase, and Monero... themselves (I think). -
How to access static files when using URL dispatcher in django
How can I access the static files in Django when using URL dispatcher In the below code. I was unable to access static files In settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] In urls.py path('userupdate/<int:id>',UserOperation.updateInfo,name='update'), The static files is accessible when I am not sending the User.ID in url -
Can't change user profile image in django
I am really new to django and I am building a website for internal use in my company. I have extended the user model with another model called "profile" in order to store extra information about each user, including a profile picture. I have set up a form.py class with the data i'd like to be able to modify: class UserForm(forms.ModelForm): class Meta: model = Profile fields = ['office','role', 'userImage'] The form in the html is as follows: <form class="form" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__group"> <label for="Profile.userImage">{{ field.label }}</label> {{ field }} </div> {% endfor %} <div class="form__action"> <a class="btn btn--dark" href="{% url 'user-profile' request.user.id%}">Cancel</a> <button class="btn btn--main" type="submit">Update</button> </div> </form> And in the views.py, here is the function that takes care of this: def update_user(request): user = request.user profile = request.user.profile if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('user-profile', pk=user.id) else: form = UserForm(instance = profile) return render(request, 'base/update-user.html', {'form': form}) And the profile model is: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) job= models.TextField(max_length=50, blank=True, verbose_name="Centro") role= models.TextField(null=True, max_length=50, blank=True, verbose_name="Cargo") userImage = models.ImageField(upload_to='profileImages/', default='profileImages/happy.jpg', verbose_name="Profile Image") @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): … -
How to make Nested Models in django
I am new to django. My task is to make a feature on shared documents in backend. Documents can have folders, like google docs.We will have list of documents within list of folders. I created following model classes: class Folder(models.Model): name = models.CharField(max_length=128, unique=True) def __str__(self) -> str: return self.name class File(models.Model): folder_name = models.ForeignKey(Folder, on_delete=models.CASCADE) docfile = models.FileField(upload_to='documents/%Y/%m/%d') def __str__(self) -> str: return self.name So first, a folder will be created. Then a file will be uploaded in that folder. My Questions are: In google docs, we can have folders inside folders. How can I update my model if I want to add this feature of adding folder inside folder and then storing file on it. What does FileField attribute actually do? I want to store the data in postgres database, not in my local storage. How to deal with that? What additional features should I add in my model for this purpose? -
How can i successfully implement django amp on my site
Please I'm trying to implement Django AMP in my site so According to the docs here https://django-amp-tools.readthedocs.io/en/latest/installation.html. I have added the required to my settings.py but still getting this error below (my_venv) ~/my_venv/amp $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/data/data/com.termux/files/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/__init__.py", line 4, in <module> from amp_tools.settings import settings File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 25, in <module> class defaults(object): … -
Integration of Django-PayPal subscription based payment system
I am trying to implement a Subscription-based payment method in Django with paypalrestsdk, and even the Django-Paylpal library. Integration with Django-Paypal Library. But with this, somehow it is not working for me. I am new to Django python and I am not able to integrate it so please help me with this. -
Flatten Nested QuerySet to a Pandas DataDrame
I am trying to fetch records of all devices with their related owners for the data as below Device ====== .Id .Name .owner_id Owner ===== .Id .Name How I try to get the data in django: data = Device.objects.select_related('owner').values() Now I would need the data of devices and their owner in a flattened pandas' DataFrame. e.g. a column like 'owner.name' is created in the dataframe. How can I do that? Tried 'from_records' didn't work. Tried 'json_normalize' but cannot convert queryset to json first. Thanks -
Folium Django popup with multiple lines
I have a code from map import test def create_popup(data1,data2,data3): popup = Popup(f" Location : {data1}" " Last Time : {data2}" " Last Status : {data3}", max_width=200) return popup But when i input let say popup1 = create_popup("X",test.data2,test.data3), it seems like my Popup only receive data 1 which is x and resulted Location : X Last Time : {data2} Last Status : {data3} test refer to test.py. Is there anyway to fix this code? Thanks, i am using PyCharm I would like to make a popup folium with 3 lines : Location : data1 Last Time : test.data2 Last Status : test.data3 -
Using ast and whitelists to make Django's definition sentences joined by periods safe?
I want to know how to define a sentences joined by period and also use a function in a HTML using an ast and a whitelist. In Django, sometimes files are defined in this way. "xxx.storage.LocalStore" Also, in a html, Django can define like below. {% is_something params %} So I would like to avoid these cases. Do you have any idea? -
How to apply aggregation to item in the QuerySet
There are a lot questions similar to this one but none of them worked for me. Let's assume that I have the following models: class Cafe(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Food(models.Model): class SoldStatus(models.TextChoices): SOLD_OUT = "SoldOut", "Sold out" NOT_SOLD_OUT = "NotSoldOut", "Not sold out" name = models.CharField(max_length=50) cafe = models.ForeignKey(Cafe, related_name="foods", on_delete=models.CASCADE) status = models.CharField(choices=SoldStatus.choices) def __str__(self): return self.name In my QuerySet, I want to retrieve all cafes with the following fields in each: 'cafe name', 'total number of foods', 'total number of not sold foods', and 'percentage of not sold foods' Is there any way to achieve the above result with Django ORM? -
Django Rest Framework adding import in settings.py causes 403 error
I have a Django Rest Framework application with custom render and parse classes, set in settings.py: REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": ( "djangorestframework_camel_case.render.CamelCaseJSONRenderer", "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer", ), "DEFAULT_PARSER_CLASSES": ( "djangorestframework_camel_case.parser.CamelCaseFormParser", "djangorestframework_camel_case.parser.CamelCaseMultiPartParser", "djangorestframework_camel_case.parser.CamelCaseJSONParser", ), } And at this point everything works fine. But if I add import statement in settings.py like this: from djangorestframework_camel_case.render import CamelCaseJSONRenderer REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": ( "djangorestframework_camel_case.render.CamelCaseJSONRenderer", "djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer", ), "DEFAULT_PARSER_CLASSES": ( "djangorestframework_camel_case.parser.CamelCaseFormParser", "djangorestframework_camel_case.parser.CamelCaseMultiPartParser", "djangorestframework_camel_case.parser.CamelCaseJSONParser", ), } I start to get 403 error. Why is that? How may I fix it? Just in case it somehow matters my installed apps: INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.postgres", "django.contrib.sessions", "django.contrib.staticfiles", "corsheaders", "django_filters", "rest_framework", "my_porject.my_app", ] -
SQLalchemy LIKE queries for encrypted database
My MySql and Postgres databases have some columns which been encrypted by some custom encryption function. How it works? I have implemented get_prep_value and from_db_value methods for encryption and decryption using custom field in Django orm. I have also flask application which access to the databases, so in flask I have created new custom type and implemented process_bind_param and process_reuslt_value methods for encryption and decryption. The result - I didn't need to change anything in my codebase and everything should works as regular and before the encryption. But I have an issue which I don't know how it can be solved in this situation when my DB is encrypted and this is all LIKE queries in my code base, when I'm using __contains and __icontains - it is not works as before. How can be the DB encrypted also for fields which I need to access them by LIKE queries? At the moment since I don't have any idea how to solve it, I have decrypted my DB for these fields I lookup with LIKE queries so the code will work as expected and as before. I'm actually expect to encrypt these fields and in spite of encryption, be able … -
ImportError: cannot import name 'url' from 'django.conf.urls' after using from django.urls import re_path as url
In my program i am getting (error cannot import name 'url' from 'django.conf.urls) despite of trying different methods which you have mentioned.my django is latest i am expecting that url can import and my program can run the server this is my code and below is error -
Delete django models object with duplicate field
I want delete django models object with duplicate field. for example: ProgrammingQuestionAnswer.objects.filter(accept=True, programming_question=programming_question) here, maybe a user has 2 accept in the question. I want to count those duplicates once thanks