Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reciprocation Of Django Model ForeignKey
I want to reciprocate the existence of my ForeignKey in the Client app. Client App Structure: Project Client model.py Client model.py Code: class Client(models.Model): primary_key = models.AutoField(primary_key=True) unique_num = models.TextField(max_length=30) name = models.TextField(max_length=30, default='Name Not Found') number = models.TextField(max_length=30) email = models.EmailField() Email App Structure: Project Email model.py Client model.py Code: class ScheduledEmail(models.Model): primary_key = models.AutoField(primary_key=True) recipient_name = models.TextField() subject = models.TextField() message = models.TextField() datetime_sent = models.TextField(max_length=20, default='Not Yet Sent') datetime_created = models.TextField(max_length=20) recipient_email = models.EmailField(max_length=50, default='Email Not Found') sent = models.BooleanField(default=False) recipient = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='scheduled_emails_sent') -
can you explain this python django makemigrations error?
i deleted my database and when i tried to migrate with a new database i am getting this error. traceback File "D:\work\Student Management\student_management_system\student_management_app\urls.py", line 3, in <module> from . import views, AdminViews, StaffViews, StudentViews File "D:\work\Student Management\student_management_system\student_management_app\views.py", line 7, in <module> from .AdminViews import * File "D:\work\Student Management\student_management_system\student_management_app\AdminViews.py", line 4, in <module> from .forms import * File "D:\work\Student Management\student_management_system\student_management_app\forms.py", line 8, in <module> class AddStudentForm(forms.Form): File "D:\work\Student Management\student_management_system\student_management_app\forms.py", line 19, in AddStudentForm for course in courses: File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 280, in __iter__ self._fetch_all() File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\work\Student Management\myvenv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\work\Student Management\myvenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "student_management_app_courses" does not exist LINE 1: ...student_management_app_courses"."updated_at" FROM "student_m... i dont understand what the error is can somebody please … -
How link Noscript tag in Django python
I try to linked CSS in my html , but not working what is issue? others working <link rel="stylesheet" href="{% static "/player/css/appf6eb.css" %}"> <link rel="preload" href="{% static "/player/themes/qartulad/assets/css/fonts.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/css/fonts.css" %}"></noscript> <link rel="preload" href="{% static "/player/themes/qartulad/assets/plugins/fontawesome-free-5.6.3-web/css/all.min.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/plugins/fontawesome-free-5.6.3-web/css/all.min.css" %}"></noscript> <link rel="stylesheet" href="{% static "/player/themes/qartulad/assets/css/style-mixed434d.css" %}"> -
how do i filter from variant that is many_to_many relationship with category
Here is my code: # VIEW.PY def retrieve(self, request, pk=None): variant_id = request.get('variant_id') queryset = Category.objects.filter(category_id=pk) querysetSerializer = CategoryServiceListSerializer(queryset, many=True) i want to filter variant_id from Variant so that it display only that particular variuant. Not sure where changes need to be made in views or serialzier. im assuming this could be solution queryset = Category.objects.filter(category_id=pk,variant__in = variant_id) but getting error TypeError: 'int' object is not iterable # MODELS.PY class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) category_icon = models.CharField(max_length=500, null=True, blank=True) category_image = models.CharField(max_length=500, null=True, blank=True) category_description = models.CharField(max_length=1000, null=True, blank=True) active_status = models.BooleanField(default=True) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) # SERIALIZER.PY class CategoryServiceListSerializer(serializers.ModelSerializer): variant = VariantServiceSerializer(many=True, source="variant_set") class Meta: fields = "__all__" model = Category class VariantServiceSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = "__all__" -
interagtion of scrapper.py to flask
i made a web scrapper which loads the data in dataframe as df everytime i run the program. is there a possible way in which i can integrate this data frame i.e df in flask or web app and to save he data in a database (sql) ?? regards -
com_error when trying to get COM object with win32com.client from Django view
I am trying to connect a SAP GUI session to my Django project so I can interact with it, by using win32com.client to work with COM objects. When working from the shell I have no problem at all to get this working by running the following code: sap_gui = win32com.client.GetObject("SAPGUI") application = sap_gui.GetScriptingEngine connection = application.Children(0) session = connection.Children(0) If I start the server with this code in the views.py Django module this also works, and I can get the session info displayed in my Django view. However, I want to be able to connect and disconnect such session by hand, since different users will need to connect to different sessions, and by running the code at start I can only stick to the first session. I have been trying to get this working by defining the following view in views.py: def dashboard(request): if request.method == 'POST' and 'SAP_button' in request.POST: # Get the COM object (SAP session in this case) sap_gui = win32com.client.GetObject("SAPGUI") # ERROR HERE application = sap_gui.GetScriptingEngine connection = application.Children(0) session = connection.Children(0) # This is just a test to see if I get the desired output from the COM object test = session.info.User return render(request, 'Users/dashboard.html', … -
Reverse for '' with arguments '('',)' not found
I am trying to implement a way to change some saved settings on my app , the user should be able to view and change these settings accordingly. However , the above error is received when trying to load the "SettingsHome" page. Please see the below code and full error message: Error: NoReverseMatch at /settings Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Request Method: GET Request URL: http://localhost:8000/settings Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\KylePOG\Documents\GMA Programming\accConnect', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Tue, 14 Sep 2021 08:30:03 +0000 Error during template rendering In template C:\Users\KylePOG\Documents\GMA Programming\accConnect\main\templates\main\base.html, error at line 7 Reverse for 'viewSettings' with arguments '('',)' not found. 1 pattern(s) tried: ['accConnect/setting/(?P<settings_pk>[0-9]+)$'] 1 2 3 4 5 /* The sidebar menu / 6 .sidenav { 7 height: 100%; / Full-height: remove this if you want "auto" height / 8 width: 160px; / Set the width of the sidebar / 9 position: fixed; / Fixed Sidebar (stay in place on scroll) / 10 z-index: 1; / … -
NoReverseMatch at /polls/3/vote/
So I've tried to check for an answer to similar questions asked but I haven't found one that solves my problem. I could be wrong but from my understanding, my code isn't reading my question.id, which means nothing is being passed to my vote view. Here's the code snippet: My views: My URLs: And the form where question.id is being passed to polls:vote from: Here is the error I'm encountering: Again, my bad if the question has been answered before but I had to be sure. Can anyone point out what I'm missing? -
Django how to create a filled update object form?
I want to create an update form. When a user enters this page the form should be filled with information so that the user can edit what they want to fix. I try to use instance in views but didn't work. The fields are still empty. How can I do it? views.py def setup_settings(request): user = request.user data = get_object_or_404(DashboardData, user=user) # print(data) --> DashboardData object (45) form = SetupForm(request.POST or None, instance=data) if request.method == 'POST': if form.is_valid(): form.save() else: form = SetupForm() context = { 'form': form, } return render(request, 'update_setup.html', context) -
Associating a post with a user in react and django using JTW tokens
I would like to associate a post with a logged-in user, a react, and Django app. I have tried this, and am getting an unauthorized error, settings.py REST_FRAMEWORK = { # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated' # ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_TOKEN_CLASSES': ( 'rest_framework_simplejwt.tokens.AccessToken', ) } my serializers.py class PoultryCreateSerializer(serializers.ModelSerializer): class Meta: model = Poultry fields = ('title', 'price', 'category', 'description', 'image', 'county', 'subcounty', 'location', 'contact') read_only_fields = ['seller'] views.py @api_view(["POST"]) @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAuthenticated]) def poultrycreate(request): print(request.user) parser_classes = (MultiPartParser, FormParser) serializer = PoultryCreateSerializer(data=request.data) if serializer.is_valid(): serializer.save(seller=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) # print('error', serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
I want to show each games title in its specific platform in the navbar
I want to show each games title in its specific platform in the navbar by creating a GameManager with a function called 'show_pc_game' which will only show games whose platform is PC. This is my models.py: class GameManager(models.Manager): def show_pc_game(self): return self.filter(platform='PC') class Platform(models.Model): PLATFORM_CHOICES = ( ('PC', 'PC'), ('PS', 'playstation'), ('XBOX', 'Xbox'), ('Nintendo Switch', 'nintendo switch'), ) title = models.CharField(max_length=15, choices=PLATFORM_CHOICES, verbose_name= "platform") slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name = "platform" verbose_name_plural = "platforms" def __str__(self): return self.title class Game(models.Model): title = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to="images") platform = models.ManyToManyField(Platform) class Meta: verbose_name = "game" verbose_name_plural = "games" def __str__(self): return self.title objects = GameManager() my views.py: def home(request): return render(request, 'blog/base.html') class GameList(ListView): template_name = "blog/game.html" model = Game class GameDetail(DetailView): template_name = "blog/game_detail.html" class PlatformList(ListView): template_name = "blog/platform.html" model = Platform I have used 'extends' in secondary html files so I have to apply changes only in 'base.html' And this is my context_processors.py for apply contextes: from .models import Platform, Game def add_variable_to_context(request): return { 'platforms': Platform.objects.all(), 'games': Game.objects.all(), 'PC_games': Game.objects.show_pc_game(), } And my base.html: <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown">Platform</a> <ul class="dropdown-menu"> {% for platform in platforms … -
why am I getting a CSRF token missing or incorrect error?
why am I getting a CSRF token missing or incorrect error? I did put the {% csrf_token %} in my html, and the rest of my pages works well, only the delete not working. I am trying to delete a user from my database when the admin click on the delete button. allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> <th>Staff Name</th> <th>Staff Username</th> <th>Email</th> <th>Date Joined</th> <th>Action</th> </tr> {% for user in allusername %} {% csrf_token %} <tr> <td>{{user.first_name}} {{user.last_name}}</td> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{user.date_joined}}</td> <td><a class="btn btn-sm btn-info" href="{}">Update</a></td> <td> <form action="{% url 'delete' user.id %}" method="post"> <button type="submit" class="btn btn-sm btn-danger">Delete</button> </form> </td> </tr> {% endfor %} </table> <br> <h6>*Note: You are 8 hours ahead of the server time.</h6> </div> </div> {% endblock %} urls.py urlpatterns = [ #path('', views.index, name='index'), #path('login/', views.login_view, name='login_view'), path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', … -
IntegrityError, NOT NULL constraint failed: contest_contestant.contest_id while updating record
I Have two models Contest and Contestant, users can start a contest, and other users can register as a contestant under any contest… models.py class Contest(models.Model): contest_title = models.CharField(max_length=30) contest_post = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Contestant(models.Model): contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='participating_contest') contestant_name = models.CharField(max_length=10, blank=True, null=True) votes = models.IntegerField(default=0) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) Fans of any contestant can cast an unlimited amount of vote for their favourite contestant, anytime a fan votes i want to increment the Contestant.votes with the amount of votes being casted, i have tried using FBV but it is too complicated for my level of django, i am now using CBV, but i am getting an IntegrityError saying IntegrityError at /contests/contestant/2/ NOT NULL constraint failed: contest_contestant.contest_id this error doesn’t make sense to me because contest_id has already being assigned to contestant upon creation, and i can even confirm it from the database view.py class ContestantCreateView(CreateView): model = Contestant fields = ['contestant_name'] def form_valid(self, form): form.instance.contest_id = self.kwargs.get('pk') return super().form_valid(form) the voting logic is in side contestant detailView, which is being triggered by a POST request from a form views.py class ContestantDetail(DetailView, FormMixin): model = Contestant context_object_name = 'contestants' template_name = … -
django-rest-framework ignores fields from model mixin
I have the following configuration of django models with base classes and a mixin for additional fields, but django-rest-framework is ignoring the fields from the mixin class. Models from django.db import models class Base(models.Model): a = CharField() class Meta: abstract = True class Mixin(object): b = CharField() class Concrete(Base, Mixin): c = CharField() class Meta(Base.Meta): abstract = False Serializers from rest_framework import serializers class BaseSerializer(serializers.Serializer): class Meta: fields = ('a',) abstract = True class ConcreteSerializer(BaseSerializer): class Meta(BaseSerializer.Meta): model = Concrete fields = ('b', 'c',) View sets from rest_framework import viewsets class BaseViewSet(viewsets.ModelViewSet): # Some common @actions here. class Meta: abstract = True class ConcreteViewSet(BaseViewSet): serializer_class = ConcreteSerializer class Meta(EquipmentItemEditProposalViewSet.Meta): abstract = False URLS from rest_framework import routers router = routers.DefaultRouter() router.register(r'concrete', ConcreteViewSet, basename='concrete') However, when I browese to http://localhost/api/concrete/ I get the django-rest-framework form with the a and c fields, but not the b field from the mixin. NOTE: if I make the Mixin class inherig from django.db.models.Model instead of object, then I do get the field, but I that won't work because applying a django migration results in a diamond inheritance problem: TypeError: Cannot create a consistent method resolution order (MRO) for bases Model, Mixin Is there a solution … -
How to set for image in VersatileImageField
I am using VersatileImageField for my image field in Django models. I want to set a default image like we do normally in an ImageField. I have tried using default='' in VersatileImageField but it doesn't work. Following is my models.py from django.db import models from django.contrib.auth.models import User from versatileimagefield.fields import VersatileImageField, PPOIField class Image(models.Model): image = VersatileImageField( 'Image', upload_to='images/', default='default.jpg', ppoi_field='image_ppoi' ) image_ppoi = PPOIField() class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = ( ('published', 'Published'), ('draft', 'Draft') ) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=100) excerpt = models.TextField(null=True) content = models.TextField() published = models.DateField(auto_now_add=True, editable=False) modified_on = models.DateField(auto_now_add=True) image = models.ManyToManyField(Image, related_name='products') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts', default=1) status = models.CharField( max_length=10, choices=options, default='published') objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-published',) def __str__(self): return self.title -
Return nested/related models with manyToMany relationship through model
I have a ManyToMany relationship between Recipe and Product. If I request Recipes, I am able to query also the relating products, but when I request Product, there is no related model data. I think this is because the relationship is defined on the Recipe model. How can I query the Recipes related to Product (with the through model info!)? models.py class Recipe(models.Model): ... products_input = models.ManyToManyField(Product, through='RecipeInput', related_name='products_input') ... class Product(models.Model): ... class RecipeInput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField() ... serializers.py class RecipeInputSerializer(serializers.HyperlinkedModelSerializer): product_key = serializers.ReadOnlyField(source='product.key') product_name = serializers.ReadOnlyField(source='product.name') class Meta: model = RecipeInput fields = ("product_name", 'amount', 'product_key', ) class RecipeSerializer(serializers.ModelSerializer): products_in = RecipeInputSerializer(source='recipeinput_set', many=True) class Meta: model = Recipe fields = "__all__" depth = 3 class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" depth = 3 -
I have this error delete() missing 1 required positional argument: 'id' when I click on the delete button
when I click on the delete button, I am supposed to make it delete from my database, but instead I got this error: delete() missing 1 required positional argument: 'id' as shown in the picture below: urls.py urlpatterns = [ path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), #path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), path('delete', views.delete, name='delete'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] views.py def delete(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.delete(id) return HttpResponseRedirect("/home") return render(request, 'delete.html', context) allstaff.py {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> <th>Staff Name</th> <th>Staff Username</th> <th>Email</th> <th>Date Joined</th> <th>Action</th> </tr> {% for user in allusername %} <tr> <td>{{user.first_name}} {{user.last_name}}</td><td>{{user.username}}</td><td>{{user.email}}</td><td>{{user.date_joined}}</td><td><a class="btn btn-sm btn-info" href="{}">Update</a></td><td><a class="btn btn-sm btn-danger" href="/delete">Delete</a></td> </tr> {% endfor %} </table> <br> </div> </div> {% endblock %} What did I miss out? How do I get it to work so that when I click on the delete button, it will auto delete from my database? -
Disabling an duplicate database entries || Django
I currently have a settings form that enters their entries into the Django SQLite database. I obviously don't want the user to enter 2 settings with the same name. I have tried to use a for loop to check if the data exist, but just can't get it right. Here is my current code for this form: Views.py: def newSetting(request): form = SettingsForm() if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): form.save() return render(request , 'main/newSetting.html' , {'form':form}) newSetting.html: {% extends "main/base.html"%} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> <style > .row_container{ line-height: 500%; } </style> {% block content %} <form class="form-group mt-4" action="" method="post"> {% csrf_token %} {{ form.Complex }} <br> <br> <div class="row_container" name='TRB-YTD'> <div class="row mb-.1"> <div class="col" style="left-align"> {{ form.Trial_balance_Year_to_date }} </div> <div class="col-11"> <p> Trial balance YTD</p> </div> </div> </div> <div class="row_container" name="TRB-MONTH"> <div class="row "> <div class="col" style="left-align"> {{ form.Trial_balance_Monthly }} </div> <div class="col-11"> <p> Trial balance Monthly</p> </div> </div> </div> <div class="row_container" name="IS-YTD"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Year_to_date }} </div> <div class="col-11"> <p> Income Statement YTD</p> </div> </div> </div> <div class="row_container" name="IS-MONTHLY"> <div class="row "> <div class="col" style="left-align"> {{ form.Income_Statement_Monthly }} </div> <div class="col-11"> <p> Income Statement Monthly</p> </div> </div> </div> … -
Can Django select_for_update be used to acquire a read lock?
I'm working on a project similar to ecommerce in which I have models that represent a product with a certain amount in the storage, and users can buy some quantity of the product as long as it doesn't exceed the stored amount. I want to avoid a race condition taking place when the server receives multiple requests to buy the same product. class Product(models.Model): amount_in_storage = models.PositiveIntegerField() # for design reasons, this amount is unchangeable, it must be only evaluated once during initialization like constants in C++ @property def amount_available_for_purchase(self): return self.amount_in_storage - Purchase.objects.filter(product=self.id).aggregate(models.Sum('amount'))["sum__amount"] class Purchase(models.Model): product = models.ForeignKey(Product, ...) amount = models.PositiveIntegerField() payment_method = ... Let's assume that this is the block of code that's responsible for creating a purchase. @atomic_transaction def func(product_id, amount_to_purchase): product = Product.objects.get(...) if product.amount_available_for_purchase > amount_to_purchase: # do payment related stuff Purchase.objects.create(product=product, amount=amount_to_purchase) # do more stuff I would like to restrict concurrent access to this block of code, Ideally I would like to obtain a read lock access at the if condition, so that if multiple threads try to see if the amount available is greater than the amount to purchase, one of the threads will have to wait until the transaction is … -
Django Running Slow while working with Mediafiles and Pytesseract
I am working on Django where I am preprocessing some data and images, having pytesseract, opencv and some other libraries. For some reason sometimes after uploading images for extracting data. The program loads up quickly but sometimes it's taking way too long and I have to manually restart the server. After restarting the server, module loads quickly again. I am unsure if it's because of pytesseract or because of the Media files. One of the part of the code: adhar.py: from django.conf import settings import pytesseract import cv2 import re import cv2 import ftfy from PIL import Image from scipy.ndimage import rotate import numpy as np face_classifier = cv2.CascadeClassifier("/home/arijitsen/Downloads/haarcascade_frontalface_default.xml") def adhar(filename): """ This function will handle the core OCR processing of images. """ i = cv2.imread(filename) newdata=pytesseract.image_to_osd(i) angle = re.search('(?<=Rotate: )\d+', newdata).group(0) angle = int(angle) i = Image.open(filename) if angle != 0: #with Image.open("ro2.jpg") as i: rot_angle = 360 - angle i = i.rotate(rot_angle, expand="True") i.save(filename) i = cv2.imread(filename) # Convert to gray i = cv2.cvtColor(i, cv2.COLOR_BGR2GRAY) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) i = cv2.dilate(i, kernel, iterations=1) i = cv2.erode(i, kernel, iterations=1) text = pytesseract.image_to_string(i) #return text # Arijit Code Added … -
Need to removed url when printing the value of href in django
I am attempting to print the href value but its occuring along with the url HTML <style> a.printable:link:after, a.printable:visited:after { content:" [" attr(href) "] "; } </style> <table> <tr> <td height="40" valign="right" style="width:150px; font-size: 4.2mm; padding:4pt 0pt 0.5pt 0pt; text-align:center; background:#006400;"><a href="{{ request.scheme|safe|escape }}://{{ request.get_host }}/crm/orders/accepting/{{client.id}}/{{invoice.id}}/" class="printable" style="color:#fff; text-decoration:none;">Accept this Order</a></td> </tr> </table> Here what actually i need is Accept this order But i am getting Accept this order[http:http://127.0.0.1:8000/crm/orders/accepting/13/647/] -
Django: 3-level base class and Meta class ignored?
I'm having the following setup in a Django 2 app: class Base1(models.Model): # ... some fields here... class Meta: abstract = True unique_together = [ 'brand', 'name' ] class Base2(Base1): # ... some more fields here... class Meta: abstract = True class Concrete(Base2): pass The Concrete class doesn't seem to have the unique_together requirement that's present in Base1. Is this expected? If it is, how can I make sure that Concrete has the constraint while keeping things DRY? Thanks! -
Filtering data for multiple conditions in DRF
Django newbie here and having a hard time implementing a simple filter operation. I have an Order model which has two fields - order_id and zipcode. The users are going to pass the above two parameters in the request body and I have to return an order that matches the combination. API endpoint: POST https://myapi.com/orders/ { "order_id": "A123", "zipcode": 10001 } My solution: # views.py from rest_framework.response import Response from django.shortcuts import get_object_or_404 from rest_framework.viewsets import ViewSet from ..models import Order from ..serializers import OrderSerializer class OrderViewSet(ViewSet): def create(self, request): queryset = Order.objects.all() order = get_object_or_404( queryset.filter(order_id=request.data["order_id"]).filter( zipcode=request.data["zipcode"] ) ) serializer = OrderSerializer(order) return Response(serializer.data) Questions Is ViewSet the right way to go here or should I use generics? Not sure which one to use when. Is there a better way to apply multiple filters than chaining them like I have done above? -
ImportError: cannot import name 'MealSerializer' from partially initialized module 'delivery_api.main.serializers'
When I insert this line cart = CartSerializer() into my serializer to get detailed information, I get an error ImportError: cannot import name 'MealSerializer' from partially initialized module 'delivery_api.main.serializers' (most likely due to a circular import). What is the reason for this and how to solve it? cart/serializers.py class CartMealSerializer(serializers.ModelSerializer): meal = MealSerializer() class Meta: model = CartMeal fields = ['id', 'meal', 'qty', 'final_price'] class CartSerializer(serializers.ModelSerializer): meals = CartMealSerializer(many=True) owner = CustomerSerializer() class Meta: model = Cart fields = '__all__' main/serializers.py class OrderSerializer(serializers.ModelSerializer): cart = CartSerializer() *<--- This line causes an error* class Meta: model = Order fields = ['first_name', 'last_name', 'cart', 'phone', 'address', 'status', 'created_at'] Please help me solve this problem -
Best Web Framework [closed]
I wanted to ask that which web framework takes the least time and builds the best web apps , django vs mean vs others.