Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have multiple return statement in python django?
In my Views.py, I try to download the csv file first to client side then only wish to redirect to another page. Below was my code def main(request): ... ... url = '//file1.km.in.com/sd/recipe/' +"/"+ model + "_" + code + ".csv" filename=model + "_" + code + ".csv" download_csv(url,filename) data = {"TableForm": TableForm, "devicelist": devicelist_1} time.sleep(10) return redirect('/ProductList/BetaTest', data) def download_csv(url,filename): csv = process_file(url) response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename return response def process_file(file_handle): df = pd.read_csv(file_handle, index_col=False) return df.to_csv(index=False) However, download function didn't work but it directly redirect to BetaTest page. I try to edit to below code, and now the download function is work but it cannot redirect to another page: def main(request): ... ... data = {"TableForm": TableForm, "devicelist": devicelist_1} csv = process_file(url) response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename return response time.sleep(10) return redirect('/ProductList/BetaTest', data) Is there any ideas to overcome this issue? -
object carousel in django
{% for object in obj %} {{ object.title }} {{ object.sub_title }} Previous Next {% endfor %} -
Django Matching query don't exist in AddProduct.objects.get(Name=productname[i])
I have a model AddProduct and StockIn. When a new stock are purchased from dealer than all purchased product are get added in StockIn model. And Existing products are updated in AddProduct model. My AddProduct models are as follows class AddProduct(models.Model): Name = models.CharField(max_length=120,verbose_name="name") Description = models.CharField(max_length=120, verbose_name="description") Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit') purchaseRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="purchase rate") AvgRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="avg rate") OpnStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="Opening stock") ClosingStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="closing stock") StoreLocation = models.CharField(max_length=120,verbose_name="store location") MinStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="minimum stock") ReOrder = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="reorder") MaxStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="maxstock") Group = models.ForeignKey(ProductGroup,on_delete=models.CASCADE,max_length=150,verbose_name='productgroup') CGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="CGST") SGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="SGST") IGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="IGST") Validity = models.IntegerField(verbose_name="validity") Updated = models.DateTimeField(auto_now=True) while my StockIn model are as follows class StockIN(models.Model): GrnNo = models.IntegerField(verbose_name="GrnNo") Date = models.DateTimeField(default=timezone.now) Supplier = models.ForeignKey(AddSupplier,on_delete=models.CASCADE,max_length=150,verbose_name='supplier') InvoiceNo = models.IntegerField(verbose_name="invoice No") InvoiceDate = models.DateTimeField(default=timezone.now, verbose_name="Invoice Date") ProductName = models.CharField(max_length=120,verbose_name="productName") Quantity = models.IntegerField(verbose_name="quantity") Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit') Rate = models.CharField(max_length=120,verbose_name="rate") Value = models.CharField(max_length=120,verbose_name="value") DisPer = models.CharField(max_length=120,verbose_name="disper") DisValue = models.CharField(max_length=120,verbose_name="disvalue") Taxable = models.CharField(max_length=120,verbose_name="taxable") CGSTPER = models.CharField(max_length=120,verbose_name="cgstper") CGST = models.CharField(max_length=120,verbose_name="cgst") SGSTPER = models.CharField(max_length=120,verbose_name="sgstper") SGST = models.CharField(max_length=120,verbose_name="sgst") IGSTPER = models.CharField(max_length=120,verbose_name="igstper") IGST = models.CharField(max_length=120,verbose_name="igst") NetAmt = models.CharField(max_length=120,verbose_name="netamt") I recieving a list of product details from template. So after submiting the request i am getting the result … -
Django, editable help texts of form field
I want to edit help texts of each form field on the frontend, is there any method to accomplish this? -
Product sorting based on prize in ecommerce
I am trying to perform a prize sorting(low to high and vice versa)on product varients on my e-commerce website. since I am new to this, I am a bit confused. Here is my model: class Product(models.Model): Name = models.CharField(max_length=250) Description = RichTextField(null=True) Features = RichTextField(null=True,default=None) Varient_Type = models.ForeignKey(VarientType,on_delete=models.CASCADE) Product_Category = models.ForeignKey(Catogory,on_delete=models.CASCADE) Product_Brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True,null=True) related_product=models.ManyToManyField('Product',blank=True,null=True) status = models.CharField(default='Active',max_length=20, choices=( ('Active','Active'), ('Inactive','Inactive') )) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "Products" ordering = ['-created_at'] def __str__(self) -> str: return self.Name class Product_Varients(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) Sku_Code=models.CharField(max_length=100) Varient_Values = models.ForeignKey(VarientValues,on_delete=models.CASCADE) Selling_Prize = models.DecimalField(max_digits=12,decimal_places=2) Display_Prize = models.DecimalField(max_digits=12,decimal_places=2) Product_stock = models.PositiveIntegerField(blank=True,null=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(default='Active',max_length=20, choices=( ('Active','Active'), ('Inactive','Inactive') )) class Meta: db_table = "Product_Varients" ordering = ['-created_at'] class ProductImage(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) Thumbnail_image = models.ImageField(upload_to='Products',null=True) I am passing all products to the template and iterating the product varients of each product and displaying only the first varient. here is my template code: <div class="col-md-9 product-model-sec"> {% for product in products %} {% for pro in product.product_varients_set.all %} {% if forloop.first %} <div class="product-grid love-grid"> <div class="more-product"><span> </span></div> <div class="product-img b-link-stripe b-animate-go thickbox"> <div class="shrt"> <a href="javascript:void(0)" data-id="{{pro.id}}" class="button add-Cart add-to-wish-btn" title="Add to Wishlist"></span>Wishlist</a> </div> {% for img in product.productimage_set.all%} {% if forloop.first %} <a href="{% url … -
django views pass a list in aggregate function
So I have a list and I want to pass it on to .aggregate() so it looks like .aggregate(riasec_avg) but instead I get type error views.py riasec_avg =[Avg('realistic'),Avg('investigative'),Avg('artistic'),Avg('social'),Avg('enterprising'),Avg('conventional')] context['riasec_male'] = Riasec_result.objects.filter(user__profile__gender='M').aggregate(riasec_avg) context['riasec_female'] = Riasec_result.objects.filter(user__profile__gender='F').aggregate(riasec_avg) I also have tried () instead of [] -
How to enforce user permissions using user Groups in Django Class Based Views
In my Django app, I have created Groups and assigned (selectively) Permissions the Groups. And later assigned the Groups to the Users. These steps were carried out in the app's admin. Now I am trying to restrict certain views to the users (using CBV) like as under: class UomListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): template_name = "..." context_object_name = 'unit_meas' model = U_o_M permission_required = 'myapp.view_u_o_m' def get_queryset(self): return U_o_M.objects.order_by('uom') As expected I am able to restrict access to the view to users who are assigned the permission "myApp.view_u_o_m". My understanding of the system is that if a user is attached to a Group which has permission "view_u_o_m" should be automatically assigned the privilege of accessing the view. To quote (from Admin > Change User page): The groups this user belongs to. A user will get all permissions granted to each of their groups. However, when I remove the line permission_required = 'myApp.view_u_o_m', anticipating that the user Permission will hold good but it doesn't and I get an error saying View is missing the permission_required attribute. Define... or override .get_permission_required(). Obviously I am wrong about how defining "Groups" affect the Permissions scenario. May I ask somebody to help clarify the issue here and … -
How can I return multiple values from hidden input when I click the button with jquery?
When I click the button, I want to get the value of the hidden input, but when I write it like this, it only takes the first value. <div> <input type="hidden" name="producecode" class="pdcode" value="{{per.produceCode}}" /> <input type="hidden" name="useremail" class="uponequantity" value=" {{user.username}}" /> <button class="btn btn-sm btn- primary" onclick="upoq()"><i class="fa fa-plus"></i></button> $(".up").click(function(){ $(".prdtd").find("input:first- child").attr("value"); $(".pcode").val()} -
Stop CSS loader spinning if form validation error, django, javascript
How do I stop the loader spinner showing if the forum submit fails and the user has to complete a missing form field. The spinner keeps spinning forever while the user enters the missing information. My submit button in the form: ... <div class="control"> <button type="submit" class="button" onclick="showDiv()">Submit </button> </div> </form> My spinning loader below the form: <span class="loader" id="loadingdisplay" style="display:none;"></span> My javascript on click event to display spinning loader: <script type="text/javascript"> function showDiv() { document.getElementById('loadingdisplay').style.display = "block"; } </script> -
Affect total sum with start date and end date
My views: class CentreRevenue(ListAPIView): permission_classes = [IsAuthenticated, ] pagination_class = CustomPagination serializer_class = serializers.CentreRevenueSerializer def get_queryset(self): self.pagination_class.page_size = page_size id = self.request.query_params.get("id") start_date = self.request.query_params.get("start_date") end_date = self.request.query_params.get("end_date") data = center_models.Centers.objects.filter(center_type__in=['collection_center', 'direct_client'], id__isnull=False) if id: data = data.filter(id=id) # if start_date and end_date: # data = data.filter(created_at__date__range=[start_date, end_date]) return data #Serializer class CentreRevenueSerializer(serializers.BaseSerializer): class Meta: model = package_models.CollectionCenterLedger def to_representation(self, instance): tbc = booking_models.Booking.objects.filter(center=instance, center__isnull=False).values_list('id').count() amount = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, center=instance, ledger_type='debit' if instance.type == 'prepaid' else 'credit' ).values_list('amount', flat=True) ) remove_test_billing_client_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='credit' if instance.type == 'prepaid' else 'debit', center=instance, ).values_list('amount', flat=True) ) add_test_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='debit' if instance.type == 'prepaid' else 'credit',center=instance ).values_list('rcl_share', flat=True) ) remove_test_billing = sum( package_models.CollectionCenterLedger.objects.filter( package__isnull=False, ledger_type='credit' if instance.type == 'prepaid' else 'debit', center=instance ).values_list('rcl_share', flat=True) ) rcl_amount = add_test_billing - remove_test_billing amount = amount - remove_test_billing_client_billing return{ 'ccdc_name':instance.name, 'sales_person':instance.sales_manager.user.username if instance.sales_manager else None, 'centre_type':instance.center_type, 'total_booking_count':tbc, # 'total_revenue':sum([i for i in total_rev if i is not None]), 'total_revenue':amount, 'rcl_share':rcl_amount } Here i am calculating total_booking_count, total_revenue and rcl_share. I want to filter these data with start_date and end_date and accordingly these calculation will affect. Suppose if i selected date range 5 days then it will only show calculation of … -
HOW TO UPDATE DJANGO FORM WITH FILES AND TEXT INPUTS?
I have an update form in django and the code below is working particulary the instance: def edit_project(request, project_id): detail = projectDB.objects.get(pk=project_id) form = projectForm(request.POST or None, instance = detail) if form.is_valid(): form.save() return redirect ('/manage') return render(request, 'edit_project.html', {'detail': detail, 'form':form }) But when I inserted request.FILES as well to save the updated file from the form like this, def edit_project(request, project_id): detail = projectDB.objects.get(pk=project_id) form = projectForm(request.POST or None, request.FILES instance = detail) if form.is_valid(): form.save() return redirect ('/manage') return render(request, 'edit_project.html', {'detail': detail, 'form':form }) the instance seems not working anymore. Im new to django and I want to update a form that contains files and text inputs from users and I dont know how to save both at the same time. Hope you help me, thank you -
Github Actions CI/CD without docker on an -Django-Gunicorn-Nginx
I have a digital ocean server setup with Django-Gunicorn-Nginx. Everything is working as I want but sadly everytime I make a code change I have to manually login to my server pull my changes from github and restart gunicorn. Is it possible to setup a CI/CD workflow by just using Github-Actions? P.S - Docker is not an option right now. -
Why my django send_mail is not working with Occasion models?
I am working on project, in this project a user can make a group(occasion) where he saves the message, members(Many-to-many), occasional_date(date of the occasion) and when the occasional date appears the webapp should send the message by email to all members of the occasional group. But It is not sending emails. here is my occasions/models.py from django.db import models from django.dispatch import receiver from members.models import Member from django.contrib.auth import get_user_model import uuid import datetime from django.core.mail import send_mail class Occasion(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="occasions") description = models.TextField(max_length=500, null=True, blank=True) members = models.ManyToManyField(Member) occasional_date = models.DateField(help_text="Enter the date on what you want to send the notifications to members.", default="2022-03-01") message = models.TextField(max_length=500, default="hello") is_email_sent = models.BooleanField(default=False) def __str__(self): return self.name def send_email(self): if self.is_email_sent == False and self.occasional_date == datetime.date.today(): for member in self.members: receiver = [] receiver.append(member.email_address) send_mail("Smart Alert", self.message, "officialsmartalert@gmail.com", receiver, fail_silently=False,) self.is_email_sent = True self.save() return True And in a template I call this method to work. {% for occasion in user.occasions.all %} {% if ocassion.send_email %} <li>{{ ocassion.name }}</li> {% endif %} {% endfor %} Please tell me how it will work because I am tired of … -
How to escape out of django tags?
I am currently working on a small project where I am using HTMX with Django. {% render_field form.email class="form-control my-3" placeholder="Email" hx-post="{% url 'accounts:verify-email' %}" hx-trigger="keyup" hx-target="#email-verif" hx-swap="outerHTML" %} {{ form.email.errors|striptags }} However, the code breaks because it thinks the %} portion of the url snippet is close bracket of the whole line. Is there any solution for this? -
Unable to declare javascript variable with a django variable
I am using django and when I assign a django variable to a javascript variable I get the following error. Uncaught SyntaxError: Unexpected token '&' What Im doing is I passed a variable which is a list of strings to the template html through the view function Im calling here is the view function: def index(request): class_obj = AllClasses() return render(request, 'index.html', { 'classNames': class_obj.classList }) Then I declared a global JavaScript variable inside index.html like this: <script> var names = {{classNames}}; </script> This results in the following error that Uncaught SyntaxError: Unexpected token '&' Any idea on how to solve this ? -
How to make an api completely independent from the main Django Project?
I have a django project that is hosted internally, and this project feeds the database. I need an API that serves the data of that database to a public domain (that api does not do any DML only selects), but this API needs be hosted in a diferent machine and even if the project that is hosted internally explodes that api needs to keep working. I am using DRF for the api I did an api project that has its own apps, views, serializers and models(those models connect to the db existing table like this) and only have the fields that I need represented. Is this the right way to do this or am I missing something? The thing that I am worried is if one of the columns of a model changes name i will have to change the model in the api, but that is a very rare modification. -
Multiple add to cart buttons on the same page in django
i am trying to add multiple add to cart buttons of products on the same page. i had the code of one add to cart button for one produc in one page but now i am trying to do it for multiple products (a grid) def product(request, category_slug, product_slug): cart = Cart(request) product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug) imagesstring = '{"thumbnail": "%s", "image": "%s", "id": "mainimage"},' % (product.get_thumbnail(), product.image.url) for image in product.images.all(): imagesstring += ('{"thumbnail": "%s", "image": "%s", "id": "%s"},' % (image.get_thumbnail(), image.image.url, image.id)) print(imagesstring) if request.method == 'POST': form = AddToCartForm(request.POST) if form.is_valid(): quantity = 1 #form.cleaned_data['quantity'] cart.add(product_id=product.id, quantity=quantity, update_quantity=False) messages.success(request, 'The product was added to the cart') return redirect('product', category_slug=category_slug, product_slug=product_slug) else: form = AddToCartForm() similar_products = list(product.category.products.exclude(id=product.id)) if len(similar_products) >= 4: similar_products = random.sample(similar_products, 4) context = { 'form': form, 'product': product, 'similar_products': similar_products, 'imagesstring': "[" + imagesstring.rstrip(',') + "]" } return render(request, 'product/product.html', context) here is the view function for one product page. -
Routing does not work in Django: page not found (GET)
I've tried multiple methods of writing views but I don't think it is a problem here. App is installed in settings.py It displays error every time. project structure: structure url.py in apps folder from django.urls import path from . import views urlpatterns = [ path('home_view/', views.home_view) ] apps.py in app folder from django.apps import AppConfig class AppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'app' urls.py in store folder from django.contrib import admin from django.urls import path, include from app import views urlpatterns = [ path('app/home_view/', include('app.url')), path('admin/', admin.site.urls), ] error message: error -
Fetching data using eact native
I am trying to fetch my user infomations from django database. But I only get the following message {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "ee5e4317-5bb7-4b5f-8e19-7a787cdee766", "offset": 0, "size": 94}}, "bodyUsed": false, "headers": {"map": {"allow": "GET, POST, HEAD, OPTIONS", "content-length": "94", "content-type": "application/json", "date": "Sat, 19 Mar 2022 22:02:40 GMT", "referrer-policy": "same-origin", "server": "WSGIServer/0.2 CPython/3.6.8", "vary": "Accept, Origin, Cookie", "x-content-type-options": "nosniff", "x-frame-options": "DENY"}}, "ok": true, "status": 200, "statusText": "", "type": "default" I can use it to determine if the status is OK to long in, but I would like to be able to gather the user information and send them to the next page. Any help? -
Update global variable in an asychrounouus way in Django
I have a tacky problem. On my website, you can find current price tracker for crypto coins as a purely content filler element. I get my data from coin API, you are allowed 100 request's per day. def crypto_api_prices(request): api_base_url = 'https://rest.coinapi.io/v1/exchangerate/' api_key = '===============' headers = { 'X-CoinAPI-Key': api_key, } crypto_tickers = ["BTC","ETH","ETC","RVN"] crypto_api_links = [api_base_url+x+"/"+"USD" for x in crypto_tickers ] crypto_api_prices = [requests.get(x, headers=headers).json()['rate'] for x in crypto_api_links] context = { "cryptoPrices":crypto_api_prices } return context I'm calling this function in my home view. Unfortunately, if I have couple of visitors daily this generates 100 requests pretty fast and my element isn't working anymore. What I want to achieve is set crypto_api_prices as a global variable and update it every hour, so no matter how many users will be on my page I will generate only 24 requests. Is this a good idea? Are there alternatives? Of course I can buy more requests but this website is a "passion" project so I want to keep costs down -
DRF IsAuthenticated seems to be not working properly in remote server
I started a migration of a personal project between two servers and I get a very weird behavior. My APP uses TokenAuthentication from DRF and is working perfectly in a local environment and in the previous server but in the new one I get the following error: "Authentication credentials were not provided.". At the first time I thought that it was because Nginx was not sending the right headers to the backend but after doing some debugging I found that the headers were ok. Im totally lost at this point, hope I can get some help. Thanks to everyone. My REST_FRAMEWORK config: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", #"rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, "DEFAULT_FILTER_BACKENDS": [ "django_filters.rest_framework.DjangoFilterBackend" ], } Current view: class UserInfoView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user = self.request.user return Response({"type": user.user_type, "username": user.username}) Request made by CURL: % curl 'http://myapp.com:8000/api/user-info/' \ -H 'Connection: keep-alive' \ -H 'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"' \ -H 'Accept: application/json, text/plain, */*' \ -H 'Authorization: Token 144e22bc66c9b145596690c8673ef9aaefbaad1d' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36' \ -H 'sec-ch-ua-platform: "macOS"' \ -H 'Sec-Fetch-Site: cross-site' \ -H 'Sec-Fetch-Mode: … -
Django 3.2 makemigrations ProgrammingError: table doesn't exist for abstract model
I'm currently updating my website to use Django 3.2, but I use the zinnia blog which is no longer receiving updates. I'm making the necessary changes to bring it up to compatibility with 3.2 but I'm now getting the error that the AbstractEntry table doesn't exist. This is, however, an abstract table so I'm confused why it would try to find the table at all. Full traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.8/dist-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.8/dist-packages/zinnia/models/__init__.py", line 4, in <module> from zinnia.models.entry import Entry File "/usr/local/lib/python3.8/dist-packages/zinnia/models/entry.py", line 6, in <module> class Entry(load_model_class(ENTRY_BASE_MODEL)): File "/usr/local/lib/python3.8/dist-packages/zinnia/models_bases/__init__.py", line 18, in load_model_class _class … -
How do I fix: Your branch is ahead of 'heroku/main' by 1 commit. (Heroku/Django)
I am trying to drill down a major problem I have created syncing my Heroku and local PostgreSQL databases. I believe I may have found the source of the problem: I am new to web development and this is my first deployed application so I have made some clumsy mistakes along the way. My current flow for pushing is this: Local migration: python3 manage.py makemigrations Commit: git add and git commit -a Deploy: git push heroku main Migrate to server: heroku run python3 manage.py migrate I currently get this message: On branch main Your branch is ahead of 'heroku/main' by 1 commit. It looks like my Heroku DB may be out of sync by 1 commit with my local db - hence I am getting a whole host of errors in my deployed application. I would like to know how to rectify this and hope to have some advice prior to doing anything to make sure I don't mess it up. Below is the terminal log for the push that led to the above message. I am not sure if the WARNINGS are linked to the current issue, because they reference STATICFILES I assume not. Terminal Log (venv) xx % … -
How to get IntergrityError data Django
I have an IntegrityError data as follow : ERROR: Duplicate key value breaks unique constraint "CampaignNamingTool_year_month_advertiser_na_aedc5c8c_uniq" DETAIL: The key “(year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. I would like to get the key: (year, month, advertiser, name, kpi, type_of_format, device)=(2022, 03, FR - Python, Paris, CPV, Multi-device, IAB)” already exists. How can I do that? Any help is appreciated try: CampaignNamingTool.objects.bulk_create(list_of_campaign_naming_tool) except IntegrityError as e: messages.error(request, e) return redirect('bulk_create_campaign_naming_tool') else: msg = "Campaigns successfully uploaded" messages.success(request, msg) return redirect('bulk_create_campaign_naming_tool') -
When to use OAuth in Django? What is it's exact role on Django login framework?
I am trying to be sure that I understand it correctly: Is OAuth a bridge for only third party authenticator those so common like Facebook, Google? And using it improves user experience in secure way but not adding extra secure layer to Django login framework? Can I take it like this? Thanks in advance!