Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix url in python custom login
I have 2 django app. user and management. I have added dashboard/ in main app urls which redirects to user app urls. For this we need to login. All urls in user app is: dashboard/ and for login dashboard/login but it shows error in /login. ERROR: Page not found (404) Request Method: POST Request URL: http://localhost:8000/login Main app urls.py from user import urls as user_urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include(user_urls)) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) User app urls.py from django.urls import path, include from nh_user import views as users_views from management import urls as management_urls urlpatterns = [ path('login', users_views.user_login, name='user-login'), path('logout', users_views.user_logout, name='user-logout'), path('dashboard/', include(management_urls)), path('', users_views.index, name='user-index'), ] -
Django template loops (why different than Jinja)
I'm forced to do something like this for Django templates. {% for i in i|rjust:20 %} Why doesn't Django support something like this? {% for i in range(20) %} -
Add logic to PATCH on Django Rest Framework
In my very simple learning application, I would like to trigger some logic the moment that a model changes to 'complete'. Specifically, I pass the following payload to my viewset: { complete: true } which is as follows: class TestQuestionViewset(viewsets.ModelViewSet): queryset = TestQuestion.objects.all() serializer_class = TestQuestionSerializer I would like to trigger some logic server side that is triggered as soon as the complete flag is updated. Could I override the update method? If so, how could I do this? -
how to import django oscar catalogue with child categories?
hello people and happy easter, I use the oscar_import_catalogue command to import products into my shop. At this moment, I already modified the partner/importer.py and now I can add some attributes into the csv, here is my snipped: def _create_item(self, product_class, category_str, upc, title, description, co2, is_public, stats): # .... item.upc = upc item.title = title item.description = description item.product_class = product_class item.co2 = co2 item.is_public = is_public item.save() have a lot of products and it would be much easier to add the subcategories to the csv as well. Simple example: product_class: electronics. categories: mobile phones (1) > android phones (2) > samsung phones (3). Does somebody has any idea? Greetings -
how to make dependent dropdown form in django
i have three models and each three models are dependent with each other.while adding the Studentfee model through form when i select the student name then the course price should appear only related to that student's course selction models.py from django.db import models from django.db.models import CASCADE class Course(models.Model): title = models.CharField(max_length=250) basic_price = models.CharField(max_length=100) advanced_price = models.CharField(max_length=100) basic_duration = models.CharField(max_length=50) advanced_duration = models.CharField(max_length=50) def __str__(self): return self.title class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateField() def __str__(self): return self.name class StudentFee(models.Model): student = models.ForeignKey(Student,on_delete=CASCADE) total_fee = models.ForeignKey(Course,on_delete=CASCADE) # should dynamically generate in the form based on the selection of student.how ?? first_installment = models.IntegerField(blank=True) second_installment = models.IntegerField(blank=True) third_installment = models.IntegerField(blank=True) remaining = models.IntegerField(blank=True) def __str__(self): return self.total_fee -
Is there a way to inject list values into queryset as a custom aggregated column
I'm looking for a way to query data from models such as Author with fields [pk, name] and Book [pk, author, name, published] so, in the end, I'd have got something like that [ { 'pk': 'author_pk_1', 'name': 'author__name_1', 'books': [ { 'pk': 'book__pk_1', 'title': 'book_name_1', 'published': 'book_published_1', }, { 'pk': 'book__pk_2', 'title': 'book_name_2', 'published': 'book_published_1', } ] } ] At the moment I achieved this by iterating through QuerySet and manually grouping them, but it does not look good at all: authors = Author.objects.values('pk', 'name') grouped = list() for author in authors: entry = dict() entry['pk'] = author['pk'] entry['name'] = author['name'] entry['books'] = list(Book.objects.filter(author=author['pk']).values('pk', 'title', 'published')) grouped.append(entry) -
Django How do I show Author (user) name instea of ID?
I have a custom user model (CustomUsers) on one app called users, and then I have a model called Bookings from which I have created a ModelfForm called BookingsForm. In the Bookings model (and ultimately the BookingsForm), I have a field called booking_author which has a ForeignKey inherited from the CustomUsers model. Now I have been able to successfully call the booking_author field into my bookingscreate view and make it uneditable/read only as I had wanted. The issue now is that the field is displaying the id of the author instead of the name of the author. Is anyone able to help me resolve this? views.py @login_required def bookingscreate(request): bookings_form = BookingsForm(initial={'booking_author': request.user }) context = { 'bookings_form': bookings_form } return render(request, 'bookings_create.html', context) -
Loading 2 form on one page and saving them
I have a system, and I need to change, I want to take the option pets, and by it in a table separates, why will have more than one type of user that would use it. But I'm not able to make it appear along with the other form on the same page and then I need you to save both forms at the same time. remembering that every time you register the form, a user is created in the system by the UserCreationForm I would need help to be able to show and save both form at one time summing up: * PetForm and UserForm loading on same page * PetForm and UserForm saving with a single post method *and the Pets picking up the user that will be created from the UserForm models.py class Pets(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) pets = models.CharField(max_length=255, choices=PET_CHOICES) class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(blank=False) forms.py class PetsForm(forms.ModelForm): pets = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=PET_CHOICES, ) class Meta: model = Pets fields = '__all__' class UsuarioForm(UserCreationForm): nome = forms.CharField() sobrenome = forms.CharField( widget=forms.TextInput( attrs={ 'placeholder': 'Sobrenome'})) email = forms.EmailField( widget=forms.TextInput( attrs={ 'placeholder': 'Email Válido', 'id': … -
Unable to dumpdata periodically in django 1.10.3
I'm trying to dumpdata automatically every month . I am following the instructions given in the https://github.com/hzdg/django-periodically. After step 3, I am getting the following error: (BPS_SE~1) C:\Users\Gopal Gautam\PycharmProjects\bps_g>python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x03EA0B30> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\periodically\__init__.py", line 3, in <module> from .utils import get_scheduler_backend_class File "C:\Python27\lib\site-packages\periodically\utils.py", line 4, in <module> from .models import ExecutionRecord File "C:\Python27\lib\site-packages\periodically\models.py", line 14, in <module> class ExecutionRecord(models.Model): File "C:\Python27\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\Python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Additional information: Python version : 2.7, django version : 1.10.3, OS : windows 10. How can I solved the issue or is there any method through which i can dumpdata periodically -
Why isn't Django displaying my dynamic background images on my template
I am displaying dynamic content from my database on my templates using django. When I check the image url in the google developer console it shows that the url of the image I am trying to display is correct but it still doesn't display the image on the page. template = loader.get_template("selling/shop.html") if Product.objects.exists(): products = Product.objects.all() for product in products: productimages = product.productimage_set.all() for productimage in productimages: imageurl = productimage.product_images.url context = { "products" : products, "imageurl" : imageurl, } <div class="container" id="storediv" > <div id="noproducts"> {% if products %} {% for product in products %} <div class="holla2 col-sm-12 col-lg-3" id="holla" style="background-image: url('{{ product.productimage_set.first.product_images.url }}');"> <div class="alltext" id="textcontainer"> <p class="alltext" id="one">{{ product.title}}</p> <p id="two">${{ product.price }}</p> <!-- <p id="three">{{ product.product_description }}</p> --> </div> </div> {% endfor %} {% else %} <h2>There don't seem to be any products now. Please check back later! To further clarify, where it says: style="backgroundimage:url('{{product.productimage_set.first.product_images.url }}');" is working correctly and displaying the image url but the image isn't showing up on the page. -
raise exception and return response
I need to raise exception inside the validate() method of a Serializer. So I did something like below, class SampleSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = SampleModel def validate(self, attrs): foo_value = attrs['foo'] if foo_value > 100: raise ValueError("foo_value cant be grater than 100") return attrs It raising an exception, but as server error. How can I raise the exception and safely return some message to the API response? -
Sending post request to papal to get access token in Django
Am trying to send a post request to PayPal to get the access token to start doing some more requests. it gives me 401 Unauthorized Error, here is my code def buy_confirm(request, amount, price, server_name, char_name): if request.method == 'POST': client_id = 'xxxxxxxxxxxxxxxxxxxxx' client_secret = 'xxxxxxxxxxxxxxxxx' headers = { 'Content-Type':'application/x-www-form-urlencoded', 'Authorization':"Basic " + client_id + ' ' + client_secret } body = { 'grant_type':'client_credentials' } r = requests.post("https://api.sandbox.paypal.com/v1/oauth2/token",body, headers) print(r.status_code, r.reason) return render(request, 'buy_confirm.html') -
How does Django implement `filter`? Is it selecting everything then filtering?
I just want to return where x = y with Something.objects.get(x=y). I've read there might be a filter thing in Django, but I'm weary of weather Django is doing something stupid under the hood like selecting everything from the database in memory and then picking off thing that don't match with python (like the way rails does it). Is this what Django is doing? If so I'll just run raw SQL. The only thing I see in Django docs about multiple is MultipleObjectsReturned being an exception. Lol what? -
Save exactly 100 entries from API call
im currently trying to fetch the prices of coinmarketcap.com through the API they are providing but after a couple of updates i trigger with celery, more then 100 entries are gettings saved for some reason. I guess the reason for that is that the rank is of a speficic coin is changing... Anyways i guess i only have to clear the table at the DB for every update i run against the coinmarketcap API but how do i do that? @periodic_task(run_every=(crontab(minute='*/1')), name="Update Crypto rate(s)", ignore_result=True) def get_exchange_rate(): api_url = "https://api.coinmarketcap.com/v1/ticker/" try: exchange_rates = requests.get(api_url).json() for exchange_rate in exchange_rates: CryptoPrices.objects.update_or_create( key=exchange_rate['id'], symbol=exchange_rate['symbol'], defaults={ "market_cap_usd": round(float(exchange_rate['market_cap_usd']), 3), "volume_usd_24h": round(float(exchange_rate['24h_volume_usd']), 3), "value": round(float(exchange_rate['price_usd']), 3) }) logger.info("Crypto exchange rate(s) updated successfully.") except Exception as e: print(e) thanks for any help :) -
How to get foreign key value instead of key in an ExtJS grid, using Django models?
I'm creating a simple 'task manager' web application using Django 1.11 and ExtJS4 as a client side. Each user created entry will have its own category. Now i have a problem - in the ExtJS grid, every category of an entry displaying as an 'id' value of category. And this is fair because i use Foreign key to id. How can i display a type field instead of id in the ExtJS grid table? I've tried to use django 'to_field = type' option and it's actually works, instead of 'category_id = id', i got a 'category_id = type'. But my teacher said that it's not a solution for this case and at backend part i should operate with an 'id'. models.py class Entry(models.Model): headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) class Category(models.Model): type = models.CharField(max_length=255, unique=True) In views.py i'm sending JSON format for ExtJS client side views.py def JS_entries_list(request): list_of_entries = Entry.objects.all().values() context = { 'data': list(list_of_entries) } return JsonResponse(context) And here is my ExtJS model which i use for grid's store. Here, as you can see i receiving 'category_id' as an 'int' Ext.define('Entry', { extend: 'Ext.data.Model', idProperty: 'entryID', fields: [{ name: 'id', type: … -
__init__() takes 1 positional argument but 2 were given what is wrong is here?
What is wrong is here? TypeError at /accounts/login init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 2.2 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: /Users/user/miniconda3/envs/Djangoenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response, line 113 Python Executable: /Users/user/miniconda3/envs/Djangoenv/bin/python Python Version: 3.7.3 Python Path: ['/Users/user/Desktop/Dp1/mysite', '/Users/user/miniconda3/envs/Djangoenv/lib/python37.zip', '/Users/user/miniconda3/envs/Djangoenv/lib/python3.7', '/Users/user/miniconda3/envs/Djangoenv/lib/python3.7/lib-dynload', '/Users/user/miniconda3/envs/Djangoenv/lib/python3.7/site-packages'] Server time: Sun, 21 Apr 2019 13:11:48 +0000 models.py class Post(models.Model): author = models.ForeignKey('auth.User',on_delete='') title = models.CharField(max_length=200,blank=True,null=True) text = models.TextField(blank=True,null=True) create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) class Comment(models.Model): post = models.ForeignKey('blog.Post',related_name='comments',on_delete='') author = models.CharField(max_length=256) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author','title','text') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium- editor-textarea postcontent'}) } class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ('author','text') widgets = { 'author':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium- editor-textarea'}) } app/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), re_path('accounts/login',views.LoginView,name='login'), re_path('accounts/logout',views.LogoutView,name='logout',kwargs=`{'next_page':'/'}),` ] urls.py urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), re_path('post/(? P<pk>\d+)',views.PostDetailView.as_view(),name='post_detail'), re_path('post/new',views.CreatePostView.as_view(),name='post_new'), re_path('post/(?P<pk>\d+)/edit',views.PostUpdateView.as_view(),name='post_edit'), re_path('post/(?P<pk>\d+)/remove',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), re_path('post/(?P<pk>\d+)/comment',views.add_comment_to_post,name='add_commnet_to_post'), re_path('comment/(?P<pk>\d+)/approve',views.comment_approve,name='comment_approve'), re_path('comment/(?P<pk>\d+)/remove',views.comment_remove,name='comment_remove'), re_path('post/(?P<pk>\d+)/publish',views.post_publish,name='post_publish'), ] views.py class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model … -
Creating Search in a CBV ListView
I am building a search API for my project using the Class based View ListView. I have a problem getting into my get_queryset the value to be searched. ProjectSearchListView: class ProjectSearchListView(ListView): model = Project template_name = 'projects/user_project_list.html' context_object_name = 'projects' paginate_by = 2 def get_queryset(self): query = request.GET.get('q') if query: projects = Project.objects.filter(Q(name__contains=query) | Q(description__contains=query)).order_by('-date_created') else: projects = Project.objects.all().order_by('-date_created') return projects Here is my SEARCH Form: <form class="form my-2 my-lg-0" method="GET" action="{% url 'search-project' %}" > <div class="input-group"> <input class="form-control " type="text" name="q" value="{{ request.GET.q }}" aria-label="Search" placeholder="Search"> <span class="input-group-btn"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="Search"> Search </button> </span> </div> </form> -
Why Django creates an object of type parent implicitly in multi-table inheritance?
I am trying to understand the multi-table inheritance in django and using the code samples from official django docs: 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) When executing the following in the python console. it seems that django create a Place object implicitly whenever creating a Restaurant object: >>> Place.objects.all().count() 0 >>> Restaurant.objects.all().count() 0 >>> Restaurant.objects.create(serves_pizza=True) <Restaurant: Restaurant object (1)> >>> Restaurant.objects.first() is Place.objects.first() False Can someone please explain what's going on? -
Ho to get custom fields at registration?
I'm using djnago User model and registration system. I've created another Model for custom user infos. I want to show this fields at registration step. Here are my codes: My model: def upload_image_location(instance, filename): return "%s/%s" %(instance.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True,verbose_name="Açıklama") city = models.CharField(max_length=30, blank=True,verbose_name="Vitrin Fotoğrafı") avatar = models.FileField(blank=True,null=True,upload_to=upload_image_location,verbose_name="Vitrin Fotoğrafı") def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance)' Here is my forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='İsminizi giriniz.', label="Ad") last_name = forms.CharField(max_length=30, required=False, help_text='Soyisminizi giriniz.', label="Soyad") email = forms.EmailField(max_length=254, help_text='Geçerli bir mail adresi giriniz.', label="Mail") class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) Here is my views.py part: class SignUp(generic.CreateView): form_class = SignUpForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' Now I want to get city, description and avatar fields at registration step. What is the right way to do this? -
How to interpret npm debug log for django-react tutorial
I am trying to run the tutorial project from the django rest framework website. I built the project inside a PyCharm venv. https://www.valentinog.com/blog/drf/#Django_REST_with_React_what_you_will_learn The code repo is here: https://github.com/valentinogagliardi/django-drf-react-quickstart I have the following debug log: 0 info it worked if it ends with ok 1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe', 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', 1 verbose cli 'run', 1 verbose cli 'dev' ] 2 info using npm@6.4.1 3 info using node@v10.15.1 4 verbose run-script [ 'predev', 'dev', 'postdev' ] 5 info lifecycle django-drf-quickstart@1.0.0~predev: django-drf-quickstart@1.0.0 6 info lifecycle django-drf-quickstart@1.0.0~dev: django-drf-quickstart@1.0.0 7 verbose lifecycle django-drf-quickstart@1.0.0~dev: unsafe-perm in lifecycle true 8 verbose lifecycle django-drf-quickstart@1.0.0~dev: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\david\PycharmProjects\django-drf-quickstart\node_modules\.bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Docker\Docker\Resources\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files (x86)\Brackets\command;C:\Program Files\PuTTY\;C:\Users\david\AppData\Local\Programs\Python\Python37-32\;C:\Users\david\AppData\Local\Programs\Python\Python37-32\Scripts\;C:\Users\david\.windows-build-tools\python27\;C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\david\AppData\Roaming\npm\node_modules\windows-build-tools\node_modules\.bin;C:\Users\david\AppData\Roaming\npm\node_modules\.bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Docker\Docker\Resources\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files (x86)\Brackets\command;C:\Program Files\PuTTY\;C:\Users\david\AppData\Local\Microsoft\WindowsApps;C:\Users\david\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\david\AppData\Roaming\npm;C:\Users\david\Anaconda3\Scripts;C:\Program Files\MongoDB\Server\4.0\bin;C:\Program Files\JetBrains\PyCharm 2019.1\bin;C:\Users\david\AppData\Local\atom\bin;C:\Program Files\erl10.3\bin; 9 verbose lifecycle django-drf-quickstart@1.0.0~dev: CWD: C:\Users\david\PycharmProjects\django-drf-quickstart 10 silly lifecycle django-drf-quickstart@1.0.0~dev: Args: [ '/d /s /c', 10 silly lifecycle 'webpack --mode development ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js' ] 11 silly lifecycle django-drf-quickstart@1.0.0~dev: Returned: code: 2 signal: null … -
django COMPOSITE FOREIGN KEY and CHECK constraints (2019)
What's the 2019 status on composite foreign keys and check-constraints with Django? I see projects like the following: https://pypi.org/project/django-composite-foreignkey/ https://github.com/rapilabs/django-db-constraints The last hasn't been updated since 2017 and has all of 32 stars on Github. If Django doesn't support these kind of things, how can I automate the SQL to to add these constraints and modify tables in migrations? -
Shrink many dict's to one with combined keys
I try to implement my own SubdomainMiddleware in Django cause I'm not satisfied with the ones you can download (django-subdomain, django-hosts). Now I try to make a dict of all subdomains the user provides. It is a bit like the urlpatterns-list in urls.py. You can include other urlpatterns from other apps. I want to implement the same for the subdomains. A little example: /myproj/hosts.py subdomains = { None: host('myproj.urls'), 'www': host('myproj.urls'), 'app1': include('app1.hosts'), 'app2': include('app2.hosts'), } /app1/hosts.py subdomains = { None: host('app1.urls'), 'www': host('spp1.urls'), 'subdomain1': host('app1.module1.urls'), 'subdomain2': { 'subdomain3': host('app1.module2.module2-1.urls'), }, } /app2/hosts.py subdomains = { None: host('app2.urls'), 'www': host('app2.urls'), } So, in the end, I have this dict: subdomains = { None: host('myproj.urls'), 'www': host('myproj.urls'), # app1 'app1': { None: host('app1.urls'), 'www': host('spp1.urls'), 'subdomain1': host('app1.module1.urls'), 'subdomain2': { 'subdomain3': host('app1.module2.module2-1.urls'), }, } # app2 'app2': { None: host('app2.urls'), 'www': host('app2.urls'), } } But I need this: subdomains = { None: host('myproj.urls'), 'www': host('myproj.urls'), # app1 'app1': host('app1.urls'), # www needs to be in front of the subdomain 'www.app1': host('app1.urls'), 'subdomain1.app1': host('app1.module1.urls'), 'subdomain3.subdomain2.app1': host('app1.module2.module2-1.urls'), # app2 'app2': host('app2.urls'), 'www.app2': host('app2.urls'), } Has someone an idea how to best loop over this dict's and always put 'www' to the front? This is … -
Display the groups created and joined by user in user profile
In djnago, I have provide the user the functionality to create group dynamically by clicking create group link and then entering the name and pressing enter to successfully create a group. I want to display the groups created or joined by the user in user profile, simply by clicking the display groups link in user profile. I have no clue how to do that, please help. -
why its showing me multivaluedictkeyerror on 'icon' nad plzz ignore indendent error
@login_required def create(request): if request.method=='POST': if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']: product=Product() product.title=request.POST['title'] product.body=request.POST['body'] if request.POST['url'].startsswitch('http//') or request.POST['url'].startswitch('https//'): product.url=request.POST['url'] else: product.url='http//' + request.POST['url'] product.icon=request.FILES['icon'] product.image=request.FILES['image'] product.pub_date=timezone.datetime.now() product.hunter=request.user product.save() return redirect('../') else: return render(request,'create.html',{'error':'fill all the details'}) else: return render(request,'create.html') -
How to auto calculate fields in django?
This is my model: class Stockdata(models.Model): quantity = models.PositiveIntegerField(null=True,blank=True) rate = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) opening = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) stock_name = models.CharField(max_length=32) I want to do something like: opening = quantity * rate in my django form template. I have tried the following: <script type="text/javascript"> $(document).ready(function() { $('#id_Quantity').keyup(function() { var a = $('#id_rate').val(); var b = $(this).val(); $('#id_opening').val(a * b); }); }); </script> But it is not not giving ne the result My template: <form method="POST"> <div class="form-group row"> <label class="col-lg-2 col-form-label">Stock Name<i class="material-icons" style="font-size:16px;color:red">*</i></label> <div class="col-lg-10"> {{ form.stock_name.errors }} {{ form.stock_name }} </div> </div> <div class="form-group row"> <label class="col-lg-2 col-form-label">Quantity<i class="material-icons" style="font-size:16px;color:red">*</i></label> <div class="col-lg-10"> {{ form.Quantity.errors }} {{ form.Quantity }} </div> </div> <div class="form-group row"> <label class="col-lg-2 col-form-label">Rate<i class="material-icons" style="font-size:16px;color:red">*</i></label> <div class="col-lg-10"> {{ form.rate.errors }} {{ form.rate }} </div> </div> <div class="form-group row"> <label class="col-lg-2 col-form-label">Opening Balance<i class="material-icons" style="font-size:16px;color:red">*</i></label> <div class="col-lg-10"> {{ form.opening.errors }} {{ form.opening }} </div> </div> </form> Any one have any idea about how to perform this? Actually I am very much new to jquery so having some basic problems. Thank you