Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remov bullets from Django MultipleChoiceField
Im trying to figure out how to remove bullets from Django's MultipleChoiceField. So far I have tried this very popular solution by changing my css file that basically states to input this code in my css file ul { list-style-type: none; } This didnt work and I also tried: li { list-style-type: none; } This also didnt work. Is there something Django specific why the list keeps on showing up with bulletpoints? I also tried adding the style in my forms class but also without success class SearchForm(forms.Form): job_industry = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple(attrs={'class': 'form-check', 'style': 'list-style:none;'}), choices=industry, ) I noticed that whatever attrs I enter to the forms.CheckboxSelectMultiple it only gets passed to the <label> tag and not the <ul> or <li> tag of the list. Im using Bootstrap5 if that makes any difference. How to delete bulletpoints from Django forms.MultipleChoiceField? -
How to get latest id in many to many field django
class Recept(models.Model): naslov = models.CharField(max_length=100) sestavine = models.CharField(max_length=100) priprava = models.TextField() datum = models.DateTimeField(default=timezone.now) avtor = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name="blog_recept") def last_like(self): return self.likes.latest('id') So I want to return latest id of field likes but this code returns latest id of Users how can I get the latest id of likes? -
ValueError: Missing staticfiles manifest entry on Heroku with Docker, django-pipeline, whitenoise
I am trying to deploy a Django project on Heroku using Docker, django-pipeline, and whitenoise. The container builds successfully, and I see that collectstatic generates the expected files inside container-name/static. However, upon visiting any page I receive the following 500 error: ValueError: Missing staticfiles manifest entry for 'pages/images/favicons/apple-touch-icon-57x57.png' Below are my settings.py, Dockerfile, and heroku.yml. Since I'm also using django-pipeline, one thing I'm unsure of is what setting to use for STATICFILES_STORAGE? I tried STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' but that lead to the file paths 404ing. Any advice is appreciated. Thank you. #settings.py ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DJANGO_DEBUG", default=False) ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.admindocs", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # Third-party "allauth", "allauth.account", "debug_toolbar", "django_extensions", "pipeline", "rest_framework", "whitenoise.runserver_nostatic", "widget_tweaks", # Local ... ] MIDDLEWARE = [ "debug_toolbar.middleware.DebugToolbarMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = "/static/" # STATICFILES_DIRS = [str(BASE_DIR.joinpath("code/static"))] STATIC_ROOT = str(BASE_DIR.joinpath("static")) MEDIA_URL = "/media/" MEDIA_ROOT = str(BASE_DIR.joinpath("media")) # django-pipeline config STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" DEBUG_PROPAGATE_EXCEPTIONS = True STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "pipeline.finders.PipelineFinder", ) ... # Dockerfile # Pull base image FROM python:3.8 # Set environment variables and … -
how to allow the owner of data to edit or delete in django?
I displaying the logged user expenses in my page,Now I want to let current logged user to edit their own expense.I am getting an error while doing that. I have also attached the error here. view.py def update(request,pk): expenses = expense.objects.get(id=pk) form = expenseform(instance=expenses) if request.method=="POST": form=expenseform(request.POST,instance=expenses) if form.is_valid(): form.save() return redirect('budget_home') return render(request,'budget/expenseform.html',{'Form':form}) models.py class expense(models.Model): Expensecat=(('food','Food'), ('transportation','Transportation'), ('education','Education'), ('health','Health'), ('clothes','Clothes'), ('beauty','Beauty'), ('hosuehold','Household'), ) ExpenseAmount=models.FloatField(max_length=100) Category=models.CharField(max_length=200,choices= Expensecat) Description=models.TextField(max_length=200) Date=models.DateTimeField(default=timezone.now) user=models.ForeignKey(User,on_delete=models.CASCADE) urls.py urlpatterns = [ path('',views.home,name='budget_home' ), path('chart/',views.chart,name='budget_chart'), path('income/',views.income_entry_form,name='budget_incomeform'), path('expense/',views.expense_entry_form,name='budget_expenseform'), path('update/',views.update,name='update_form'), ] Error TypeError at /update/ update() missing 1 required positional argument: 'pk' Request Method: GET Request URL: http://127.0.0.1:8000/update/ Django Version: 3.1 Exception Type: TypeError Exception Value: update() missing 1 required positional argument: 'pk' Exception Location: C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response Python Executable: C:\Users\Sri Dhar\Envs\test\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\Sri Dhar\\Dproject\\expensetracker', 'C:\\Users\\Sri Dhar\\Envs\\test\\Scripts\\python38.zip', 'c:\\python\\DLLs', 'c:\\python\\lib', 'c:\\python', 'C:\\Users\\Sri Dhar\\Envs\\test', 'C:\\Users\\Sri Dhar\\Envs\\test\\lib\\site-packages'] Server time: Mon, 08 Mar 2021 16:07:17 +0000 Traceback Switch to copy-and-paste view C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\Sri Dhar\Envs\test\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars -
Get latest payment from related model in Django Admin
I'd like to draw a table using Premises model in Django Admin. In addition I'd like include the output in this table of an additional column, say "last utility payment". There may be no payment in the database so admin should able to see either an empty cell or the date of payment. I was able to write a DB query that displays the information I need. Its abbreviated and significant part is given below: SELECT jp.id, jp.number apartment, jp.building_number building, jp.rent, jp.arrears, jpm.last_payment FROM jasmin_premises jp LEFT JOIN ( SELECT pm.premises_id, max(pm.paid) last_payment FROM jasmin_payment pm GROUP BY pm.premises_id ) jpm ON jp.id = jpm.premises_id; And the output is similar to the following: id | apartment | building | rent | arrears | last_payment -------------------------------------------------------------- 170 | 1X | 6-A | 297.43 | 2.57, | NULL 72 | 2 | 4 | 289.66 | -678.38 | 2021-01-31 173 | 3Z | 7 | 432.86 | 515.72 | 2021-02-04 73 | 4 | 8-B | 292.25 | 515.44 | 2021-02-04 74 | 5 | 8-B | 112.42 | 3249.34 | NULL 75 | 6A | 122 | 328.48 | 386.23 | 2021-02-04 76 | 7 | 42 | 482.06 | … -
how can i place django rest api data into a jquery variable
I have serialized my django model data, I now want to add the data to a variable in jquery , how can i do this ? the variable in jquery named 'trackUrl' needs to read a list of the audio source urls, if you see in my API tracks page I have the data for each user, but I'm not sure in how to approach this, any ideas ? serializers.py class MusicSerializer(serializers.ModelSerializer): class Meta: model = Music fields = ['track', 'title', 'artwork', 'artist', 'date_posted'] class TrackSerializer(serializers.ModelSerializer): class Meta: model = Music fields = ['track'] views.py class TrackViewSet(viewsets.ModelViewSet): queryset = Music.objects.all() serializer_class = TrackSerializer def get_queryset(self): user = self.request.user songs = Music.objects.all().filter(artist=user) return songs Django Rest API root page Api Root The default basic root view for DefaultRouter GET /music/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "music_all": "http://127.0.0.1:8000/music/music_all/", "tracks": "http://127.0.0.1:8000/music/tracks/" } Django Rest API: tracks Track List GET /music/tracks/ HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "track": "http://127.0.0.1:8000/media/path/to/audio/1-05_Isnt_She_Lovely.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_-_We_Will_Rock_You_1.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/08_Dont_Give_Hate_A_Chance.MP3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_Closer.mp3" }, { "track": "http://127.0.0.1:8000/media/path/to/audio/01_Empty_Garden.mp3" } ] jquery <script> $(function() { var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, … -
Getting ProgrammingError 42000 when migrating using django
I am currently working on a project were we are using the djano-rest framework. I recently started working on the authenication and authorization, and after following the step-by-step guide https://dj-rest-auth.readthedocs.io/en/latest/installation.html and https://pypi.org/project/django-rest-authtoken/ for implementing the auth solution i get this error after calling python manage.py migrate (after makemigrations, which works fine): django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Column 'hashed_token' in table 'rest_authtoken_authtoken' is of a type that is invalid for use as a key column in an index. (1919) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)"). This is the code i hav added to the models.py file: class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = … -
Trying to resolve internal server error using waitress - django - heroku
A lot of the posts regarding this issue is really old and nothing has worked for me and I'm not sure what else to do. I have a Django app that finally seems to deploy okay to Heroku. I cant use Gunicorn because I am working from a windows machine so I am using waitress. After a lot of time trying to get the correct Procfile done I finally have it where I can run on local. The problem is that when I pull up localhost on the web I get an internal server error. When I look at the trceback it gives me this: ERROR:waitress:Exception while serving / 2021-03-08T15:24:27.479552+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/channel.py", line 350, in service 2021-03-08T15:24:27.479553+00:00 app[web.1]: task.service() 2021-03-08T15:24:27.479554+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/task.py", line 171, in service 2021-03-08T15:24:27.479554+00:00 app[web.1]: self.execute() 2021-03-08T15:24:27.479555+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/task.py", line 441, in execute 2021-03-08T15:24:27.479556+00:00 app[web.1]: app_iter = self.channel.server.application(environ, start_response) 2021-03-08T15:24:27.479557+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/proxy_headers.py", line 65, in translate_proxy_headers 2021-03-08T15:24:27.479557+00:00 app[web.1]: return app(environ, start_response) 2021-03-08T15:24:27.479624+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=myapp.herokuapp.com request_id=28663c12-b4e0-41b4-b723-5193e6fbb98f fwd="208.104.195.105" dyno=web.1 connect=2ms service=9ms status=500 bytes=269 protocol=https 2021-03-08T15:24:27.479801+00:00 app[web.1]: TypeError: 'module' object is not callable I thought it might be something in my urls so I ran python manage.py check and there was a small … -
Django Advanced Python Scheduler task is running twice
I'm working on a Django project and I need it to run a function every morning at 10 AM. So I used the cron feature from Advanced Python Scheduler to do it. Here is the code that create the cron : from apscheduler.schedulers.background import BackgroundScheduler from .launcher import test def start(): print("[+] Starting task") scheduler = BackgroundScheduler() scheduler.add_job(test, 'cron', day="*",hour="18",minute="23") scheduler.start() updater.py And I used the file apps.py in order to iniate the task like so : from django.apps import AppConfig class StoreConfig(AppConfig): name = 'store' def ready(self): import store.signal from . import updater updater.start() apps.py And all of this works , the task starts but it starts two times (as you can see with the two "[+] Starting Task"): debian@lab:/var/www/$ python3 manage.py runserver 127.0.0.1:8000 [+] Starting task [+] Starting task Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 08, 2021 - 16:43:40 Django version 3.1.3, using settings 'beta.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The strange thing is that when I do a quick modification in a file and django reload itself, it starts only one task : /store/launcher.py changed, reloading. [+] Starting task Watching for … -
Some get__absolute_url_() methods in django model
Today I faced with a problem of some get_absolute_url() methods in dj model. I was creating a todo app, For my todo I have 2 methods: set that todo is completed and delete todo, for both methods I use id of todo, then I add 2 <a/> with href for both methods: First: href="{{ task.get_absolute_url }} Second: href="{% url 'todo_completed' id=task.id %}, so this works fine, but as you can see I used 'not a good practice' at the second condition as dj says. My question is how to avoid this, maybe there is other decision for this, finally: At this app I don't want to use javascript methods like ajax, axios or fetch, thanks! I`ve the such url file urlpatterns = [ path('', todo_list, name = "todo_list_url"), path('completed/<int:id>/', todo_complete, name = 'todo_completed'), path('add/', todo_add.as_view(), name="todo_add_url"), path('delete/<int:id>/', todo_delete, name="todo_delete_url"), ] I`ve a model class TodoList(models.Model): task = models.CharField(max_length = 100, blank = False, verbose_name = "New task") completed = models.BooleanField(default = False) created_at = models.DateTimeField(auto_now_add = True, help_text = "Time when the task was created") def __str__(self): return self.task def get_absolute_url(self): return reverse('todo_delete_url', kwargs = {'id': self.id}) and my HTML file <div class="tasks"> <h2>Todoes list: ({{tasks|length}})</h2> <form class="tasks__create" action="{% url … -
How to use setup python social auth for web app and for mobile app?
We have An existing Django backend with Python social auth for signing in with Google, providing web-based application and an API for the mobile app. An iOS mobile app with GoogleSignIn pod. Now we would like to allow mobile app users to sign in with Google inside the app, and then authenticate them on the backend, so that they can access their personal data via the app. So my idea of the algorithm is: App uses the GoogleSignIn and finally receives access_token. App sends this access_token to the Backend. Backend verifies this access_token, fetches/creates the user, returns some sessionid to the App. App uses this sessionid for further requests. The problem is with the third step: token verification. I found two ways of verifying: 1. Python social auth flow As described in the docs: token = request.GET.get('access_token') user = request.backend.do_auth(token) if user: login(request, user) return 'OK' else: return 'ERROR' This would be a preferred flow, since it already have all the required steps and is working perfectly with the web app (like, accounts creation, defaults for newly created users, analytics collection, etc.). But the problem is that the backend and the app use different CLIENT_IDs for the auth. This is … -
Displaying sub-category of a category in Django
I want to list my products like this Category Sub-Category Product1 Models.py class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Category1', 'Category1'), ('Category2', 'Category2'), ('Category3', 'Category3'), ('Category4', 'Category4'), ('Category5', 'Category5'), ('Category6', 'Category6') ] PRODUCTS_SUB_CATEGORY = [ ('NA', 'NA'), ('Sub-Category1', 'Sub-Category1'), ('Sub-Category2', 'Sub-Category2'), ('Sub-Category3', 'Sub-Category3'), ('Sub-Category4', 'Sub-Category4'), ('Sub-Category5', 'Sub-Category5') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_sub_category = models.CharField( max_length=100, choices=PRODUCTS_SUB_CATEGORY, default='NA') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name The current views.py is used to display the products in the following way Category1 Product I want additional code that gives me a different view(below) along with the above view in the same views.py function Category Sub-Category Product1 views.py def product(request): allProds = [] catprods = Product.objects.values('prod_category', 'id') cats = {item['prod_category'] for item in catprods} for cat in cats: prod = Product.objects.filter(prod_category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds': allProds, 'ster_prods': ster_prods} return render(request, 'website/products.html', params) -
Django Celery - How to make constance settings dynamic
I noticed that while using constance for settings management of my django app, celery does not seem to recognize any changes until restart. Why that? All I want is Celery to be able to read the settings live and in real-time instead of a cached vaule that just gets set during the application start-up ... I tried using constance trough redis and also trough a database table, with no noticeable change to the problem, celery will use old vaules. also see: https://github.com/jazzband/django-constance Can somebody give me a hint onto this issue? Kind regards and thanks in advance. -
How to save data total amount in model
Views def Booking(request): if request.method == 'POST': form = Bookingform(request.POST) if form.is_valid(): a = form.save() print(form.data["Number_of_Persons"]) Number_of_Persons = int(form.data["Number_of_Persons"]) Total_Amount = (Number_of_Persons * 100) print(Total_Amount) a = Booking(Number_of_Persons=Number_of_Persons, Total_Amount=Total_Amount) a.save() return HttpResponse(str(Total_Amount)) else: form = Bookingform() return render(request, 'ticketbooking.html', {'form': form}) -
Django templates: data filtering by foreign key
Im new to Django and I have a problem i can't seem to solve. Long story short, I created a text based app that helps me create a mealplan and generates a shopping list. And I'm trying to recreated with django. Here are my models: class Recipe(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class IngredientSet(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.SET_NULL, null=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.DO_NOTHING) quantity = models.FloatField() def __str__(self): return self.ingredient.name Now, on my List Views I want to display the names of stored recipes as links. Each recipe link should call a Detail View which will display selected recipe's sets of ingredients. I can't figure out how to access those by their foreign key(which points to a recipe). -
Conditional annotations with Aggregation over only some fields in Django
So lets assume i have two databases in my Django project class Article(models.Model): name = models.CharField(max_length=200) # .. class Price(models.Model): article = models.ForeignKey('Article') date = models.DateTimeField(auto_now_add=True) price = models.DecimalField() # .. There exist multiple Price entries per day for the same article. Now I want to annotate an article queryset with the average price of every article on the previous day. But I have no idea on how to do this in one efficient query. What I have done is this: articles = Articles.objects.all().select_related().filter(price__date__exact=datetime.datetime.now() - datetime.timedelta(days=1)).annotate(avg_price=Avg('price__price')) This works, if every article would have at least one price each day. But that isnt always the case. Articles that have no price for the previous day should have None or 0 or some default as avg_price. Does anybody know how to achieve this? -
Django context data is not transferred via vagrant
setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pythondb', 'USER': 'python', 'PASSWORD': 'python123', 'TEST': { 'NAME': 'test_portfolio', }, } } part1: runserver I have an application that simply extracts values from a database. part2: Vagrant However, it doesn't work via vagrant Question Why can't context_data be transferred via vagrant? -
Django - CSV Arabic language encoding
I'm working on Django Python and trying to export data in CSV format as some of the columns are in Arabic and facing issue on encoding my HttpResponse code HttpResponse(content_type='text/csv charset=utf-8') and CSV file how can I solve this Issue ? -
Passing matching value from view to html in django
So i have tried various ways from passing the value from view to html page in django. Depending upon the user logged in by matching the email I want to retrieve some information of the user in the html. In few I have faced error such as AttributeError at /user_profile'QuerySet' object has no attribute 'name' For the above method in views.py i was using # user profile def user_profile(request): user_data = UserProfile.objects.filter(emailID = request.user.email).values() context = { 'name' : user_data.name, 'emailID' : user_data.emailID, 'phone' : user_data.phone, 'college_name' : user_data.college_name, 'branch' : user_data.branch } return render(request, 'user_profile.html', context) My UserProfile model looks like this # User profile class UserProfile (models.Model): name = models.CharField(max_length=100) emailID = models.CharField(max_length=100) phone = models.CharField(max_length=15) college_name = models.CharField(max_length=200) branch = models.CharField(max_length=100) And I was using the {{context.college_name}}} in html code. If I just return the JsonResponse in the views.py I get the output properly as seen below. {"Matched data" : [{"id": 4, "name":"sample", "emailID":"lav@test.com", "phone": "1234567890", "college_name": "Dummy", "branch": "CS"}]} But while passing it to html either I am getting some error or the values are just not bein displayed. Passing the dictionary is resulting in empty dictionary being passed. # user profile def user_profile(request): user_data = … -
Track progress of individual functions running Python Django Websocket
I need to implement a live progress control using python. I have n-number of tasks being run parallel in my application, is there a way to get the Total Count of tasks being run which will help me to count the progress percentage based on Total Count. Example: 1% out of 100 2% out of 100 ' ' ' 99% out of 100 I am not understanding how to get the total_count at one place which will help me to analyse the progress of individual tasks running asynchronously. -
Django on different user login render different html pages
On logging one user with sales role he should be shown sales html page and if marketing person logs in then the page for marketing will be shown. In same way I will be having 30 different logins and so 30 different pages. -
Django 3 - Align Radio Button Horizontally
I have created user signup form in Django3. In the form I want to have a radio button based choice selection for the user. The forms.py looks like class SignUpForm(UserCreationForm): .... subscription_choice = ( ('yearly', 'Yearly'),('monthly', 'Monthly'), ) subscription_type = forms.TypedChoiceField( choices = subscription_choice, widget = forms.RadioSelect(attrs={ "style": "display: inline-block" }) The model file looks like. class SignUp(AbstractBaseUser): subscription_choice = ( ('yearly', 'Yearly'),('monthly', 'Monthly'), ) email = models.EmailField(unique=True) firstname = models.CharField(max_length=150) lastname = models.CharField(max_length=150) phonenumber = models.CharField(max_length=14,primary_key=True) referral_code = models.CharField(max_length=150, default="None") subscription_type = models.CharField(max_length=10, default="monthly", choices=subscription_choice) .... I have tried some css tricks as suggested in some answers on SO but no luck. The result I am getting is vertical aligned (messy) radio buttons. Need some help. -
Edit ManyToMany Inline fields with self relationship in Django Admin change form
How can I get a model's fields to be editable in the Inline in a ManyToMany relationship when the relationship is with itself? class MyModel(models.Model): children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False ) class MyModelChildAdminInline(admin.TabularInline): """Inline for the intermediate table""" model = MyModel.children.through # Number of child-forms shown at the bottom of the Profile detail view extra = 0 fk_name = 'from_mymodel' raw_id_fields = ("to_mymodel",) fields = ('to_mymodel', 'field1', 'field2', 'field3', ) readonly_fields = ('field1', 'field2', 'field3',) def field1(self, obj): return obj.to_mymodel.field1 def field2(self, obj): return obj.to_mymodel.field3 def field3(self, obj): return obj.to_mymodel.field2 @admin.register(MyModel) class MyModelAdmin(VersionAdmin): inlines = (MyModelChildAdminInline, ) exclude = ('children', ) -
Django Cassandra Engine( Multiple keyspaces)
I have a django project in which I am using cassandra database, there are multiple cassandra keyspaces available in that project. I am basically using an id as an identifier to detect which keyspace the app should be using for different users. I tried to implement this approach through django multiple database router methods such as db_for_read() and db_for_write() but was gwtting an exception when I tried so: cassandra.cqlengine.CQLEngineException: Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query. The code in my settings file is: DATABASES = { 'interview_service_1': {'ENGINE': 'django_cassandra_engine', 'NAME': 'interview_service_2', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': {'replication': {'strategy_class': 'SimpleStrategy', 'replication_factor': 1}, 'connection': {'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3}}}, 'interview_service_2': {'ENGINE': 'django_cassandra_engine', 'NAME': 'interview_service_3', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': {'replication': {'strategy_class': 'SimpleStrategy', 'replication_factor': 1}, 'connection': {'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3}}}, 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'assessment_service', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 } }, 'connection': { 'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3, 'load_balancing_policy': DCAwareRoundRobinPolicy(local_dc='datacenter1') } } } interview_service_1 and interview_service_2 are the keyspaces names which I am returning from my database router file. Is there a way through which … -
DJANGO: How can I duplicate attribute from other class?
I want to duplicate an attribute from other class. class PedidoCliente(Pedido): total_pagado = models.DecimalField(blank=True, max_digits=10, decimal_places=2,default = 0,verbose_name="Pagado $") # default 0 para el error for += int barril_encargado = models.DecimalField(blank=True, default=0, max_digits=10, decimal_places=2,verbose_name="Barr. entregados") fecha_entrega = models.DateField(verbose_name="Fecha Entrega") class DetallePedidoCliente(DetallePedido): comments = models.CharField(max_length=300, verbose_name="Comentarios") precio_venta = models.DecimalField(max_digits=16, decimal_places=2, default = 0) pedido = models.ForeignKey(PedidoCliente,on_delete=models.CASCADE) fecha_entrega = the same from PedidoCliente I'm new at OPP so sorry if it's a silly question. Thanks!