Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python manage.py runserver command not working and error message not specific
I just started learning Django this day and I got stuck because when I ran python manage.py runserver it gave this message.... I've tried python manage.py migrate still nothing. I've waited an hour to see if it makes a difference and it doesn't. It seems stupid but I've been stuck here for a while. I have activated virtual environments and added python to Path ... I don't know what went wrong. File "C:\Users\owner\Envs\test\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute("args, *cmd_options) File "C:\Users\owner\Envs\test\lib site-packages\django\core management commands \runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\owner\Envs\test\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\owner\Envs\test\lib\site-packages\django\core management commands \runserver.py", line 68, in handle if not settings. DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init__.py", line 83, in getattr self._setup(name) File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init__.py", line 70, in _setup self. wrapped = Settings(settings_module) File "C:\Users\owner\Envs\test\lib\site-packages\django\conf\_init_.py", line 177, in __init__ mod = importlib. import_module(self.SETTINGS_MODULE) File "c:\python\python39\lib\importlib __init__.py", line 127, in import_module return _bootstrap. gcd_import(name [level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _ecd_import File "<frozen importlib. bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>" line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named "C:\Python' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\owner\Desktop\goals\viva … -
How to store paypal transaction email and id in my database
Here I am integrating braintee paypal payment in my django app. The payment works fine. But the problem I got is while saving the paypal transaction email and payer Id in my database. While printing the result I can get payment_instrument_type: 'paypal_account', But I am not being able to get this account email and payer id in my result. Is there anyone who can help me on this ? def braintree_payment(customer_kwargs, amount, nonce): gateway = braintree_config() customer_create = gateway.customer.create(customer_kwargs) result = gateway.transaction.sale({ "amount": amount, "payment_method_nonce": nonce, "options": { "submit_for_settlement": True, } }) return result view nonce_from_the_client = request.POST['payment_method_nonce'] customer_kwargs = { "first_name": payment_donar.first_name, "last_name": payment_donar.last_name, "email": payment_donar.email, } amount = payment_donar.donation_amount result = braintree_payment( customer_kwargs=customer_kwargs, amount=amount, nonce=nonce_from_the_client ) if result.is_success: data = { 'transaction_id': result.transaction.id, 'currency_iso_code': result.transaction.currency_iso_code, 'last_4': result.transaction.credit_card_details.last_4, 'card_type': result.transaction.credit_card_details.card_type, 'expiration_month': result.transaction.credit_card_details.expiration_month, 'expiration_year': result.transaction.credit_card_details.expiration_year, 'customer_location': result.transaction.credit_card_details.customer_location, 'cardholder_name': result.transaction.credit_card_details.cardholder_name, 'merchant_account_id': result.transaction.merchant_account_id, 'network_transaction_id': result.transaction.network_transaction_id, } Model.objects.create(**data) return redirect('home') this is the transaction result <SuccessfulResult {transaction: <Transaction {id: 'n0gxdkcf', graphql_id: 'dHJhbnNhY3Rpb25fbjBneGRrY2Y', additional_processor_response: None, amount: Decimal('10.00'), authorization_adjustments: [], authorization_expires_at: datetime.datetime(2021, 2, 23, 13, 59, 3), avs_error_response_code: None, avs_postal_code_response_code: 'A', avs_street_address_response_code: 'A', channel: None, created_at: datetime.datetime(2021, 1, 24, 13, 59), credit_card_details: <CreditCard {token: None, bin: None, last_4: None, card_type: None, expiration_month: '', expiration_year : … -
Name Error by python, name 'ArticleDetailView' is not defined
this is the problem File "C:\simpleblog\ablog\myblog\urls.py", line 8, in path('article/int:pk',ArticleDetailView.as_view(), name='article-detail'), NameError: name 'ArticleDetailView' is not defined my urls.py from django.urls import path from .views import HomeView urlpatterns = [ path('article/<int:pk>',ArticleDetailView.as_view(), name='article-detail'), ] In my views.py I have clearly defined it. below is my views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class HomeView(ListView): model = Post template_name = 'home.html' class ArticleDetailView(DetailView): model = Post template_name = 'article_details.html' So please help me to solve it. -
Error during deploying django app in Heroku
I am trying to deploy a Django application to Heroku. When I followed the documentation and tried the command git push heroku master, I am getting an error: failed to push some refs to 'https://git.heroku.com/sleepy-eyrie-25993.git'. I searched online and tried to use git pull. But it didn't work. I also tried using git push -f heroku master, but still getting the same error. Is there any other way to do it? I followed this doc https://devcenter.heroku.com/articles/python-support -
Backend Cache not Shared with Django
I've created a python package that does some expensive computation and uses lru_cache in order to save the result so the user don't have to wait too long for the result being calculated. import cachetools.func @cachetools.func.ttl_cache(ttl=60*60) def main_function(): # some expensive computations return result The code works pretty well when I call directly the function from a file or from the Python Shell, my issue is that when calling this package from my Django project, somehow it doesn't look up the already cached results. In my __init__.py file I'm calling main_function and then I try to call it again from my Django project but it does not return the cached response, instead it runs the function again. The package that I've created has a complex cache system, it works nice so I think this may be a problem with Django, that somehow I need to manage the caches from my Django project, any suggestions on how can I solve this? -
(NoReverseMatch at / Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:id>/']). please help me to remove this error
It is a multiple image program in which we can add multiple image at one time to see grouped photos. Error during template rendering In template C:\Users\a\dev\mysite\templates\base.html, error at line 15 I am able to open my admin panel but i am not able to my files. thus please help me to find error: models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=120) description = models.TextField() image = models.ImageField(upload_to='products/', null=True, blank=True) def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') def __str__(self): return self.post.title views.py from django.shortcuts import render, get_object_or_404 from .models import Post, PostImage def blog_view(request): posts = Post.objects.all() return render(request, 'blog.html', {'posts':posts}) def detail_view(request, id): post = get_object_or_404(Post, id=id) photos = PostImage.objects.filter(post=post) return render(request, 'detail.html', { 'post':post, 'photos':photos, }) admin.py from django.contrib import admin from .models import Post, PostImage class PostImageAdmin(admin.StackedInline): model=PostImage @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [PostImageAdmin] class Meta: model=Post @admin.register(PostImage) class PostImageAdmin(admin.ModelAdmin): pass base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> … -
withour server restarting changes not apply
after changing somthing in django for example views or models No changes are made without a restart. after restarting ubuntu / plesk server changes are appled. pls help me is there a way to apply changes on django withour server restart. -
Rendering images in Django ModelForm instead of __str__ representation
I have the following django models / forms / views / html setup. So I am rendering the InputFileForm in the html and the user should select from dropdown list a face_file that is saved in the Face model (preloaded via fixtures). I would like to have the face_file images to be rendered in the dropdown (alternatively a radio select would be fine as well) instead of the image str names - as it currently looks like the following: Image of current dropdown So in short: I would like to have an image rendered in the dropdown instead of the "Face 1", "Face 2",... Thanks in advance for your help! class Face(models.Model): face_id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) face_file = models.ImageField(upload_to='../media/faces', blank=True, null=True) def __str__(self): return self.name class InputFile(models.Model): input_id = models.AutoField(primary_key=True) input_flatlay_file = models.ImageField(upload_to='../media/flatlays', blank=True, null=True) input_face_file = models.ForeignKey(Face, null=True, blank=True, on_delete=models.CASCADE, related_name="inputs_using_this_face") input_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_inputs") class Prediction(models.Model): prediction_id = models.AutoField(primary_key=True) prediction_inputs = models.ForeignKey(InputFile, null=True, blank=True, on_delete=models.CASCADE, related_name="prediction_inputs") output_lookbook_file = models.ImageField(upload_to='../media/lookbooks', blank=True, null=True) prediction_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, related_name="user_predictions") I have a ModelForm for InputFile: class InputFileForm(forms.ModelForm): class Meta: model = InputFile fields = ['input_flatlay_file','input_face_file'] In my views.py: def prediction(request): form=forms.InputFileForm() if request.method == … -
is it required to manually create Django groups through programming?
I have doubt that after hoisting if groups are not created programmically, does it affect on login as my website have multiple user login of patient, doctor as well as receptionist. -
ValueError: invalid literal for int() with base 10: 'slug-1-2'
ValueError: invalid literal for int() with base 10: 'slug-1-2' 2nd time i am facing this error again. I am trying to allow users to edit their comments in any blog post but it seems that there is a problem with this line: comment = get_object_or_404(Comment, id=post_id) This has worked for other functions but not this one. Any idea how I can resolve this without changing the url etc. Thanks models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) views.py def edit_own_comment(request, post_id): context = {} comment = get_object_or_404(Comment, id=post_id) if request.method == 'POST': form = UpdateCommentForm(request.POST, instance=comment) if comment.name == request.user and form.is_valid(): obj = form.save(commit=False) obj.save() messages.success(request, 'Your comment has been edited', extra_tags='editedcomment') return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug })) form = UpdateBlogPostForm( initial = { "body": comment.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_comment.html', context) forms.py class UpdateCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] def save(self, commit=True): comment = self.instance comment.body = self.cleaned_data['body'] if commit: comment.save() return comment -
Page is not found
I have the following urls: path('login/', auth_views.LoginView.as_view(),name ='login'), path('logout/', auth_views.LogoutView.as_view()), path('password_change/', auth_views.PasswordChangeView.as_view(),name='password_change'),] In views for the first url I have this: user = get_object_or_404(User, username = username) posts = Post.objects.filter(author = user).order_by('-pub_date') return render(request,'profile.html', {'posts':posts,'user':user}) So when I go to the page login, logout or password_change I get the error "Page is not found" Request Method: GET Request URL: http://127.0.0.1:8000/password_change/ Raised by: posts.views.profile But if I comment the profile view and its url everything works just fine. Why does the url 'logout' etc goes to profile view? -
Why my annotation group by is not working as expected?
I wanna do a query like raw sql select count(b.status) from a left out join b on a.id = b.user_id group_by(b.status). I know how to get what I wanted using raw sql. But when I try to implement this using orm, it failed. Below is the code: query_kwargs_dict = {'id__in': [10000, 10001]} statistics = UserAuthModel.objects.filter( **query_kwargs_dict ).select_related( 'obbyuserinfomodel' ).values('obbyuserinfomodel__status').annotate(count=Count('obbyuserinfomodel__status')).query print('statistics', statistics) And the print statement output is: statistics SELECT `users_obby_info`.`status`, COUNT(`users_obby_info`.`status`) AS `count` FROM `users_auth` LEFT OUTER JOIN `users_obby_info` ON (`users_auth`.`id` = `users_obby_info`.`user_id`) WHERE `users_auth`.`id` IN (10000, 10001) GROUP BY `users_auth`.`id`, `users_obby_info`.`status` ORDER BY `users_auth`.`id` DESC What confusing me is the group_by. It should be grouped by the field specified in values. In my case, it is obbyuserinfomodel__status , but the output sql statement showed it was grouped by users_auth.id. Below are the two tables(I have omitted some fields for simplicity): class UserAuthModel(AbstractBaseUser): ... class ObbyUserInfoModel(models.Model): user = models.OneToOneField(UserAuthModel, on_delete=models.CASCADE) ... status = models.CharField(max_length=15, default=ACCOUNTSTATUS.UNACTIVATED.value, null=True) -
Multiple models in Django form
I have the following models: class Category(models.Model): label = models.CharField(max_length=40) description = models.TextField() class Rating(models.Model): review = models.ForeignKey(Review, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) rating = models.SmallIntegerField() class Review(models.Model): author = models.ForeignKey(User, related_name="%(class)s_author", on_delete=models.CASCADE) coach = models.ForeignKey(User, related_name="%(class)s_coach", on_delete=models.CASCADE) comments = models.TextField() I'd like to create a form which allows a user to review a coach, including a rating for some pre-populated categories. In my head, the form would look something like: Coach: _______________ # Selection of all coach users from DB, this works as standard Category: "Professionalism" # These would be DB entries from the Category model Rating: _ / 5 Category: "Friendliness" Rating: _ / 5 Category: "Value" Rating: _ / 5 Comments: _________________________________ _________________________________ Submit I've seen Django Formsets in the documentation but these appear to exist for creating multiple forms from the same model as a single form? Not looking for a full answer, but if someone could point me in the right direction, it'd be hugely appreciated. -
How do i access django form's image field in js code
I am building a BlogApp and I am Build a feature of preview image before save into Database. BUT at the last moment, I am stuck on a Problem. As i did before, I used to access image field in template like {{ form.image }} but i put js code in template for preview the selected image in Choose file. create_blog_post.html General method for choose image field Choose file in browser `{{ form.image }}. {{ form.image|as_crispy_field }} js code in create_blog_post.html <script> window.onload = function() { if (window.File && window.FileList && window.FileReader) { var filesInput = document.getElementById("uploadImage"); filesInput.addEventListener("change", function(event) { var files = event.target.files; var output = document.getElementById("result"); for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.type.match('image')) continue; var picReader = new FileReader(); picReader.addEventListener("load", function(event) { var picFile = event.target; var div = document.createElement("div"); div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>"; output.insertBefore(div, null); }); picReader.readAsDataURL(file); } }); } } </script> The Problem I have no idea , how to access {{ form.image }} attribute in js code, which can show both Preview before save and upload that image. What have i tried 1). I have … -
Django is not displaying items as it should
I'm building an ecommerce website with a template I'm using and I want the items to be displayed. I've created a database already and want to render them to the HTML, but when it renders, the item doesn't appear correctly. and this is how it should look like: I've tried putting the HTML like this: <section class="ftco-section bg-light"> <div class="container"> <div class="row justify-content-center mb-3 pb-3"> <div class="col-md-12 heading-section text-center ftco-animate"> <h2 class="mb-4">New Shoes Arrival</h2> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-12 col-md-6 col-lg-3 ftco-animate d-flex"> <div class="product d-flex flex-column"> <a href="#" class="img-prod"><img class="img-fluid" src='{% static "images/product-1.png" %}' alt="Colorlib Template"> <div class="overlay"></div> </a> {% for item in items %} <div class="text py-3 pb-4 px-3"> <div class="d-flex"> <div class="cat"> <span>{{ item.get_category_display }}</span> </div> <div class="rating"> <p class="text-right mb-0"> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> </div> </div> <h3><a href="#">{{ item.title }}</a></h3> <div class="pricing"> <p class="price"><span>${{ item.price }}</span></p> </div> <p class="bottom-area d-flex px-3"> <a href="#" class="add-to-cart text-center py-2 mr-1"><span>Add to cart <i class="ion-ios-add ml-1"></i></span></a> <a href="#" class="buy-now text-center py-2">Buy now<span><i class="ion-ios-cart ml-1"></i></span></a> </p> </div> </div> </div> and it … -
django-el-pagination: how to reload displayed paginated results based on user form input using AJAX without reloading the entire page?
Have scroll-based pagination working so far using django-el-pagination. Want to have a form textfield at the top of the page and then as users type, to send the search terms into the view using AJAX and have the updated queryset used for the pagination. I'd like the existing objects to be removed from the page and the objects from this updated queryset to get displayed in the template. The problem is I can send the form field values into the view using an AJAX GET-request which does filter the queryset inside the view, but the displayed paginated items are not getting changed. I don't think the queryset inside the template and sent to the pagination plugin is getting updated. Here's what I have so far (function-based views): def search_restaurants(request): template = 'search_restaurants.html' page_template = 'search_restaurants_list_page.html' restaurants = Restaurant.objects.all() name_initial_value = None if len(request.GET) !=0: name = request.GET.get('restaurant_name','') if name != '': restaurants = restaurants.filter(name__istartswith=name) name_initial_value = name if request.is_ajax(): template = page_template return render(request, template, {'restaurants':restaurants, 'name_initial_value':name_initial value} In the templates, just have what's required, ie. $.endlessPaginate({paginateOnScroll:true} Then to make the AJAX request in response to the formfield typing: $('#restaurant_name_form_field').on('input',function() { $.ajax({ type:'GET': url:'/search_restaurants/' data: { 'restaurant_name':(val here) //I've tried … -
How to prevent IntegrityError in case of using UUID in django
I want to use UUID as PK in my django model as follows (database is Postgresql): class Post(models.Model): pk = models.UUID(primary_key=True, default=uuid.uuid4, editable=False) ... Every time uuid.uuid4 generates a new UUID. My question is: Is it possible that uuid.uuid4 generate a duplicate UUID? And if it's possible, how to prevent IntegrityError in case of duplicate UUID generated? -
How to upload file in django
this might be a pretty stupid question. Also I am new to django. But I was trying to create a basic file upload approach with django where user uploads a file and it gets stored into the defined media path (or whatever that it's called) and that the file size, name, and some other attributes that are needed can be stored into the database. So I have the model ready which will help you understand the question better. class Document(models.Model): file_uid = models.CharField(max_length = 16) file_name = models.CharField(max_length = 255) file_size = models.CharField(max_length = 255) file_document = models.FileField(upload_to='uploaded_files/') uploaded_on = models.DateTimeField(auto_now_add=True) uploaded_by = models.CharField(max_length=16) Now it's clearly plain that we don't need to create all the fields in the form and that most them can be received from the file itself (like the name, size). for other attrs like uid and uploaded by those also will be added by the backend. So that's where I am stuck. I have searched for 2 days straight and still couldn't find a proper solution. As of now this is my views.py def uploadView(request): if(request.method == 'POST'): form = FileUploadForm(request.POST, request.FILES) uploaded_file = request.FILES['uploaded_file'] file_dict = { 'file_uid' : get_random_string(length=10), 'file_name' :uploaded_file.name, 'file_size' : … -
Cannot deploy django project with postgres database in azure
I know it may be a novice problem but I got stuck here for quite some time. In my azure account I wanted to deploy my django-postgresql project in a subdomain. so I did the following steps, Created a python webapp with linux resource Created a postgresql server (single server) with the same resource Setup CI/CD in Development center Also set the production.py file in my project and set those variable values in the Configuration of my App service. I successfully created my database in postgresql using azure CLI (This is the only step I use CLI in this process) Then I opened my SSH session and activated antenv. After that I ran the python manage.py migrate command and got the following error.... Traceback (most recent call last): File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/opt/python/3.8.6/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/opt/python/3.8.6/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting … -
IntegrityError (wrong) instead of ValidationError (correct)
Django Version: 3.1.5 Python Version: 3.6.9 Model class GoogleAnalytics(models.Model): counter = models.SlugField(max_length=17, null=False, default="", unique=True, verbose_name="Counter") tracking_code = models.TextField(null=False, default="", verbose_name="Tracking code", validators=[validate_google_analytics_tracking_code]) Form class CounterForm(forms.ModelForm): """ Validate if the value in counter field really corresponds to the tracking code for this counter. """ def clean(self): counter_manager = CounterManager() if "GoogleAnalytics" in str(self.Meta.model): counter_from_tracking = counter_manager.get_counter(self.cleaned_data['tracking_code'], Counters.GOOGLE_ANALYTICS) else: assert "YandexMetrika" in str(self.Meta.model) counter_from_tracking = counter_manager.get_counter(self.cleaned_data['tracking_code'], Counters.YANDEX_METRIKA) if self.cleaned_data['counter'] != counter_from_tracking: raise ValidationError("Код не соответствует счетчику") return self.cleaned_data class Meta: model = GoogleAnalytics exclude = [] Admin class GoogleAnalyticsAdmin(admin.ModelAdmin): form = CounterForm admin.site.register(GoogleAnalytics, GoogleAnalyticsAdmin) Traceback https://dpaste.com/6CUL2VZAW Well, unique constraint for counter field worked. But I extected a validation error rather than IntegrityError. Could you tell me how to fix that? -
Django queryset bulk_update with and without lookup
I was wondering what exactly is the difference between retrieving entries and then bulk updating in Django vs creating an array of the model objects and pushing it to bulk_update. NOTE: The entries with the given name are unique and always exist in the database. models.py from django.db import models class Subject(models.Model): name = models.CharField(max_length=30, unique=True) credits = models.FloatField() The updating entries logic: update_logic.py from my_app.models import Subjects def update_credits_without_lookup(subjects): """ This method will update credits without getting a resultset from the DB. eg: subjects = [ {"name":"Physics","credits":10}, {"name":"Chemistry","credits":10}, {"name":"Mathematics","credits":10}, {"name":"English","credits":5} ] """ subject_objects = [Subject(name=subject["name"], credits=subject["credits"]) for subject in subjects] Subject.objects.bulk_update(subject_objects, ['credits']) def update_credits_with_lookup(subjects): """ This method will update credits by first looking up in the DB. eg: subjects = [ {"name":"Physics","credits":10}, {"name":"Chemistry","credits":10}, {"name":"Mathematics","credits":10}, {"name":"English","credits":5} ] """ subject_entries = Subject.objects.filter( name__in=[[subject["name"] for subject in subjects]]) # I can make this better by ignoring/creating subjects that might have no resultset in the DB. # Please consider that the subjects passed are always there in the DB. for subject_entry, subject in zip(subject_entries, subjects): subject_entry.credits = subject["credits"] Subject.objects.bulk_update(subject_entries, ['credits']) Considering my NOTE is it advised to use the update_credits_without_lookup method, since it will save an extra lookup in the DB and the … -
how i can solve this error of url mapping in django
Reverse for 'edit_course_landing_page' with arguments '(UUID('7e12b860-c4a0-4037-ba7d-2a4f5297d510'),)' not found. 1 pattern(s) tried: ['edit_course_landing_page/uuid:data'] -
How to assign a group to user as the time of signup in class based view in django?
I am using class based views in my djanog project. i need to assign a group named 'customer' (from django.contrib.auth.Group) at the time of when a user signsup (register) this is my view for signup class UserSignup(SuccessMessageMixin, CreateView): template_name = 'users/signup.html' success_url = reverse_lazy('home') form_class = UserSignupForm success_message = 'Account Created with the name of %{first_name} %{last_name}' -
django db settings into a .env file with decouple
I want to put my django database settings into a .env file for production. While I successfully wrote SECRET KEY and DEBUG in my .env file, when I try to do the same thing for my database settings, I get an error in the webapp. Here is the way I went about it: SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) DATABASE_ENGINE ='django_tenants.postgresql_backend' DATABASE_NAME = config('DATABASE_NAME') DATABASE_USER = config('DATABASE_USER') DATABASE_PASSWORD = config('DATABASE_PASSWORD') DATABASE_HOST = config('DATABASE_HOST', cast=db_url) DATABASE_PORT = config('PORT', cast=int) and in my .env file SECRET_KEY = supersecretkey DEBUG = False DATABASE_NAME = mydb DATABASE_USER = me DATABASE_PASSWORD = greatpassword DATABASE_HOST =urlurl DATABASE_PORT = 5432 Previously I had my db settings written as such and everything was working great: DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': 'mydb', 'USER': 'me', 'PASSWORD' : 'greatpassword', 'HOST': 'urlurl', 'PORT': '5432', } } I am wondering if anybody has a clue on what I am doing wrong here? -
Django user model,Groups and profiles
well , I'm creating API with rest. and the front part is react based. each user have to login by phone number, and after the number verification, its becomes 'simple user'. after that this user can become a 'seller' or 'customer' by filling some forms. each rule in our app has a different profile and different permissions and access to views. i made a simple User Model in my account app like : class User(AbstractUser): groups = models.ForeignKey(Group, on_delete=models.CASCADE) phone_number = models.PositiveIntegerField(unique=True) and i made profile model for each user.like: class CustomerProfile (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField() email = models.EmailField() class ServiseProviderProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() id_card_num = models.IntegerField(unique=True) address = models.TextField() email = models.EmailField() now, I have to create groups, and somehow make relation between profiles and groups and user. but am confused... I have never worked with django before, so I have no idea how can i make it happened. APPRECIATE ANY HELP :)