Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to active a venv in a Django app that created in windows and we want continue in linux?
I know the way that we active it in Linux: source venv/bin/activate and in windows it just venv/Scripts/activate.bat but i have a project that started in windows and both command didnt work Does anyone have a solution? -
Issues with migrating Models in Django after doing inspectdb from an external database
I connected my external postgreSQL database to Django and ran inspect db to import models into my app. While migrating the changes, I am getting the following errors: python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\prateek.jain\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\prateek.jain\OneDrive - XTRACAP FINTECH INDIA PRIVATE LIMITED\Desktop\XtraCap\django_api\api\models.py", line 1092, in <module> class Holidays(models.Model): File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 320, in __new__ new_class._prepare() File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 333, in _prepare opts._prepare(cls) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\options.py", line 254, in _prepare model.add_to_class('id', auto) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 2393, in contribute_to_class assert not cls._meta.auto_field, ( AssertionError: Model api.Holidays can't have more than … -
maximum recursion depth exceeded even if i use Depth = 1
I am trying to use Follow system in Django Rest Framework.Here is my code: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='follows') profile = models.ForeignKey(User,unique=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) Serializers.py class UserSerializer(serializers.ModelSerializer): following_set = serializers.SerializerMethodField() def get_following_set(self, user): return UserSerializer(User.objects.filter(follows__author=user), many=True).data class Meta: model = User depth = 1 fields = ('id','following_set','email','username') Even if i use Depth = 1 in Serializer,i still get this error: RecursionError at /api/users/ maximum recursion depth exceeded solution please? -
Django unable to display the logout template provided
I have the following problem; Im trying to set up user login and logout using the default contrib.auth views but the logout page that is displayed is the default page of django admin while the login page has no problem and displays the support template that I have provided it django-tutorial/urls.py from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('landingpage.urls')), path('articles/', include('articles.urls')), path('accounts/', include('accounts.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) accounts/urls.py from django.urls import path from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView, name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView, name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] login.html {% extends "landingpage/base.html" %} {% block page_content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'accounts:login' %}"> … -
Django FormView: Add if record does not exist and update if it does exist
I created a FormView and it works fine if the user executed the process the first time. However when it is executed the second time I get an error that the record already exist. This is expected as the user in the model is unique. How can I overcome this problem so that the current record is overwritten by the form.save if the record already exist. models.py class ttemp_selection(models.Model): select_account = models.ForeignKey(tledger_account, on_delete=models.CASCADE) date_from = models.DateField(default=datetime.today) date_to = models.DateField(default=datetime.today) user = models.ForeignKey(custom_user, on_delete=models.CASCADE, unique=True) def __str__(self): return self.select_account forms.py class Meta: model = ttemp_selection fields = ['select_account', 'date_from', 'date_to', 'user'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(SelectAccountForm, self).__init__(*args, **kwargs) user = self.request.user current_company = user.current_company self.fields['select_account'].queryset = tledger_account.objects.filter( company=current_company, gl_category='Cash and Bank') view.py class sasView(FormView): template_name = 'cashflow/select_account.html' form_class = SelectAccountForm success_url = 'home' def form_valid(self, form): form.save() return super().form_valid(form) def get_form_kwargs(self): kwargs = super(sasView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs I can determine the record by using ttemp_selection.objects.get(user=request.user) I know I can make use of the UpdateView class but that will create a problem when the record does not exist. It will also add an extra step that is unnecessary. Assistance will be appreciated. -
Migrate from multi-table inheritance model to abstract base classes in Django
My current project uses multi-table inheritance models: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) I want to switch to abstract base classes instead. Since my model is already deployed I need to write some custom migrations to convert the above schema to this one: from django.db import models class AbstractPlace(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: abstract = True class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) Does anyone have any advice on the steps to take to achieve this? -
Stock code request application in Django & SQL
I have a material excelfile and it has different type of material. Each category has start specific prefix like AB001 or BC001 I am planning to write a webservice for the request of this material stock codes. But I need to import the my old database and i have stucked how can i implement this? I have created a model in DJANGO like Materials, But i could not solve that if i import the my old excel file, the software how can understand the numbers will be correct. It must be consecutively. Like ( AB001 , AB002, AC001,AC002,AZ001) Thanks in advance! -
How can I connect my existing external PostgreSQL Database to automatically create my Models.py for a Django Rest Framework?
I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework. How do I display the tables in my Database as models in Django to further use them for the API? -
can i used model A field in model B as foregin key and model B field in model A as OnetoOneField in django
model A: field 1 field 2 --> foregin key model B model B: field 1 field 2 --> foregin key model A -
TypeError: unhashable type: 'dict' while annotate
for value in (annotated_qs.values('row', 'col').order_by('row', 'col').annotate(count=Count('row'))): print('---------value--------', value['row'],value['col]) -
How to use django rest framework [closed]
Thanks for your time. I'm a self taught Jr Developer and just re-done the Django rest-framework quick start for the third time. although i'm not beeing able to understand his usability and reasons. As far as i know the great part of a REST Full api is to receive the data as a common data format (ex: JSON, Xml, etc.), to be able to communicate with all type of API's. with the same database. allowing to comunicate with differents kind of OS. ----> Please correct me if i'm wrong <---- I'd like if i'm right and how to comunicate the rest framework system with the front end of the web api, should i use JS? is there any tutorial that you could recommend me to understand the whole picture of how a rest api should work and apply it on Django? -
Run server Django
I am trying to setup Django on my device but I am encountering issues. I am able to install python and setup a virtual environment, but I am unclear as to whether Django is established. I have tried reinstalling both Django and Python, but it does appear that Django is installed. The issue presents itself when I try to run the Django server in a virtual environment (or even not in a virtual environment). I am confronted by the following error: "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" Any advice would be gratefully received. Thanks. Screen shot -
Google sheets api- Python/Django, receive a hidden links from cells
enter image description here Hi, I have a problem with parsing a link from google sheets cells. I need to create parser that will parse sheets with links in cells. Here is a piece of code: range='Some Table!A2:J28', valueRenderOption='FORMULA').execute()``` But I received only the name from the cell. How can I receive a hidden link? -
Django REST Framework. How to get full url of a page with protocol, domain, and path?
There is Django REST framework. I need to unload the full path of the page into the tag. For example, there is a page: https://domain-name.com/category/article In serializers.py: class someClass(serializers.ModelSerializer): url = serializers.URLField(source='get_absolute_url', read_only=True) class Meta: model = onlyURL fields = ['url'] This does not work correctly, since I do not get the full url, only part: <url>**/category/article**</url> How to get full url with protocol, domain, and path? -
Django Template inheritance is not working
I am using base.html {% extends "base.html"%} but when i render them by using my block they are not rendering The own Content of file is not loading pls help -
Create nested pages-list from Postgresql database using Django
I want to store nested pages-list using Django models. I want to to use; page_id parent_page_id title fields. But ı dont know how to get pagelist as a json using recursive function like; -Page1 -Page1.1 -Page1.2 -Page1.2.1 Is there any method for this? Is it enough to use only parent_page_id ? -
Convert Javascript Datetime object to Django python3 datetime field
From the webpage I pass a JavaScript Datetime object to my Django(v2.2) function views.py Ex: sdate = new Date() Fri Dec 18 2020 13:09:19 GMT+0530 (India Standard Time) Using the datetime.datetime.strptime function I was able to match most of the object except the timezone difference (+0530 (India Standard Time)) Here is my code: datetime.strptime(sdate, "%a %b %d %Y %H:%M:%S %Z+0530 (India Standard Time)") How to match the +0530 and India Standard Time using any other datetime specifier? Because the incoming datetime objects are not always of IST time. -
Got AttributeError when attempting to get a value for field `phone_number` on serializer
AttributeError:Got AttributeError when attempting to get a value for field phone_number on serializer ListBusCompanyStaffSerializer. Bascially I have two models User and BusCompanyStaff, User consists of phone_number field BusCompanyStaff consists of following models fields class BusCompanyStaff(BaseModel): user = models.OneToOneField( BusCompanyUser, on_delete=models.CASCADE ) position = models.ForeignKey( StaffPosition, on_delete=models.SET_NULL, null=True, related_name='position' ) created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='created_by' ) staff_of = models.ForeignKey( BusCompany, on_delete=models.CASCADE ) I basically wants to list particular BusCompanyStaff from BusCompany so here is my serializer I tried till now class ListBusCompanyStaffSerializer(serializers.ModelSerializer): position = serializers.CharField() class Meta: model = BusCompanyStaff fields = ( 'id', 'phone_number', 'position', 'email', ) there is defintely Error as BusCompanyStaff dont consist of phone_number field but requirement is to put User phone number and email Here is my rest of code in views.py and usecases.py #usecases.py class ListBusCompanyStaffUseCase(BaseUseCase): def __init__(self, bus_company: BusCompany): self._bus_company = bus_company def execute(self): self._factory() return self._bus_company_staffs def _factory(self): self._bus_company_staffs = BusCompanyStaff.objects.filter(staff_of=self._bus_company) #views.py class ListBusCompanyStaffView(generics.ListAPIView): serializer_class = bus_company_user_serializers.ListBusCompanyStaffSerializer def get_bus_company(self): return GetBusCompanyUseCase( bus_company_id=self.kwargs.get('bus_company_id') ).execute() def get_queryset(self): return ListBusCompanyStaffUseCase( bus_company=self.get_bus_company() ).execute() how can I serialize in this format id , phone_number , position, email, -
DRF Help to solve nested serializers dependency
So, Here is my serializers structure in the Django Rest FrameWork: class FieldDataSerializer(serializers.ModelSerializer): class Meta: model = FieldData fields = '__all__' extra_kwargs = {'data_size': {'read_only': True}, } parent = DataSheetFieldSerializer(many=False, required=True) owner = MemberSerializer(many=False, required=True) class IndexedFieldDataSerializer(serializers.ModelSerializer): class Meta: model = IndexedFieldData fields = '__all__' field_data = FieldDataSerializer(many=False, required=True) class DataSheetFieldSerializer(serializers.ModelSerializer): class Meta: model = DataSheetField fields = '__all__' extra_kwargs = {'is_indexed': {'read_only': True}, } @property def field_size(self): return record_data_manager.get_field_size(self.data['id']) size = serializers.ReadOnlyField(source='field_size') data = FieldDataSerializer(many=True) indexed_data = IndexedFieldDataSerializer(many=True) owner = MemberSerializer(many=False, required=True) parent = DataSheetSerializer(many=False, required=True) class DataSheetsCategorySerializer(serializers.ModelSerializer): class Meta: model = DataSheetsCategory fields = '__all__' parent = ClusterSerializer(many=False, required=True) class DataSheetSerializer(serializers.ModelSerializer): class Meta: model = DataSheet fields = '__all__' @property def datasheet_size(self): return record_data_manager.get_datasheet_size(self.data['id']) size = serializers.ReadOnlyField(source='datasheet_size') fields = DataSheetFieldSerializer(many=True, read_only=True) parent = DataSheetsCategorySerializer(required=False, many=False) owner = MemberSerializer(required=True, many=False) class ClusterSerializer(serializers.ModelSerializer): class Meta: model = DataSheetsCluster fields = '__all__' extra_kwargs = {'total_size_limit': {'read_only': True}, } @property def cluster_size(self): return record_data_manager.get_cluster_size(self.data['id']) size = serializers.ReadOnlyField(source='cluster_size') members = MemberSerializer(many=True) roles = RoleSerializer(many=True) datasheets = DataSheetSerializer(many=True, read_only=True) owner = MemberSerializer(many=False, required=True) As you can see, I am having trouble because of my model's structure. I cannot reference the serializers below and hence am getting an unreferenced error, my serializers are nested. How … -
How to filter Double reverse filtering using Django ORM
Hello I am having following model structure class Product: size = models.CharField(max_length=200) class Make(models.Model): make_content = models.ForeignKey(Product, related_name='make_set') department = models.CharField(max_length=200) class MakeContent(models.Model): make = models.ForeignKey(Make, related_name='make_content_set') published = models.BooleanField() If I need to filter Product according to Make I can able to use related name qs = Product.objects.filter(make_set__department = "Sample") It's working fine Now what I need is I need to filter the Product according to MakeContent I have tried this qs = Product.objects.filter(make_set__make_content_set__published = True) This is not working , is there any other idea ? -
Can't delete old records from DB in Django
I have a code that makes a ip logs to DB like this. It should make the log when someone visit a page. The first part of code works and creates logs in my DB. def ClientIP(request, name="Default Name"): try: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') browser = request.META['HTTP_USER_AGENT'] except: return dt, tm = str(datetime.now().strftime("%Y-%m-%d&%H:%M")).split("&") if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') IpLogs.objects.create( date = dt, time = tm, ip = str(ip), page_name = str(name), browser = str(browser) ) max_date = IpLogs.objects.order_by('-date')[5] delete_qs = IpLogs.objects.filter(date__lt=max_date) delete_qs.delete() return In the last part of the code I'm trying to delete records, that are older than last 5 records. I'm getting this error TypeError: expected string or bytes-like object in this line delete_qs = IpLogs.objects.filter(date__lt=max_date) My model looks like this class IpLogs(models.Model): date = models.DateField() time = models.TimeField() ip = models.CharField(max_length=20) page_name = models.CharField(max_length=50) browser = models.CharField(max_length=300) def __str__(self): return self.ip class Meta: ordering = ['-date'] local variables are browser ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like ' 'Gecko) Chrome/87.0.4280.101 Safari/537.36') dt '2020-12-18' ip '192.168.71.58' max_date <IpLogs: 192.168.71.58> name 'DB tools' request <WSGIRequest: GET '/'> tm '14:52' What I'm doing wrong??? -
Djano filtering many-to-many results
I have an application where people can vote for multiple artists. On the results page I want to filter on country. In other words: I only wan't to show votes that are cast from a certain country. The count of votes works, but in the template still all the emails of the voters are shown and not only from the country in the filter. My model: class Artist(models.Model): id = models.AutoField(primary_key=True) name = models.CharField('Artist name', max_length=100) def __str__(self): return self.name class Vote(models.Model): email = models.EmailField(null=True) country = CountryField(default="US") artists = models.ManyToManyField(Artist, related_name='selectedartists') def __str__(self): return self.email The part of the view where the filtering is done: results = Artist.objects.filter(selectedartists__isnull=False) if countryquery == '' or countryquery == 'all': countryquery = 'all' results = results.annotate(total=Count('selectedartists', distinct=True)) else: results = results.filter(selectedartists__country=countryquery) results = results.annotate(total=Count('selectedartists', filter=Q(selectedartists__country=countryquery), distinct=True)) and this is my template {% if results %} {% for artist in results %} {{artist.name}} Votes:{ artist.total }} Voters: {{artist.selectedartists.all|join:', '}} {% endfor %} {% else %} <div class="noresults">No results</div> {% endif %} -
Rails Sorcery to Django Auth
I'm using Rails with "Sorcery" gem for authentication. https://github.com/Sorcery/sorcery Is it possible to migrate to Django default auth using the same model(DB Table)? I don't want to request all user to set new passwords. -
Access-Control-Allow-Origin header is missing despite using django-cors-headers
I'm trying to incorporate django-cors-headers into my project, but so far it doesn't seem to work - the Access-Control-Allow-Origin header is missing from the responses. I have added corsheaders to the installed apps: INSTALLED_APPS = [ ... 'corsheaders', ] And the middleware is at the top of the middleware list: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I've also tried both CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_ALL_ORIGINS = True but so far, the header is still missing. I also added CORS_ALLOW_CREDENTIALS = True to no avail. What could be the issue here? I've tried to follow the instructions from https://github.com/adamchainz/django-cors-headers#configuration but just can't get the header to appear in responses. -
Use the Dates from a text file as options for a drop-down list
Im doing a simulation of prices and creating a page for it. The page will ask what year the user would like to simulate and the type of simulation to do (Monthly/weekly) Based on the user's inputs, the page will open the text file that have filenames like this 2015_monthly.txt 2015_weekly.txt 2014_monthly.txt 2014_weekly.txt Each file contains dates of when the simulation would end. For instance in 2015_monthly.txt 2015-01-30 2015-02-28 2015-03-31 . . . What would i like to do is to ask the user to choose a date from the text file. I would like to do this in a dropdown list containing the dates from the file and use them as an options from a dropdown list. How can i translate this into a html code?