Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the implementation of Django code into HTML possible?
HTML File: <script> from django.contrib import messages messages.error('Sign-In First') </script> This doesn't work but is there a way where I can do this? Because my layout of an error message is not appealing as compared to Django's. -
How protect Login and Register endpoints (views) of an API created with DRF which use JWT as authentication?
I have been searching and reading other questions and blogs, but I didn't find anything concrete about my doubt. A little of context: I am developing a SPA which works with a REST API in Django by means of Django Rest Framework (DRF) and the authentication is made it through Bearer token: JWT (package 'Simple JWT'). So, I was reading whether it needs protection against CSRF: • Do I need CSRF token if I'm using Bearer JWT? • Should I use CSRF protection on Rest API endpoints? • The Web API Authentication guide, Bearer tokens Basically if the browser does not make an automatically authentication (with sessions or some kind of cookie), the odds of a CSRF vulnerability are slim. This approach is achieved with the Bearer Tokens using the JWT. The problem: There are some public endpoints, that don't need authentication, so I used this permission in DRF settings 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAuthenticatedOrReadOnly'], This way, unauthorized users only can make safe requests -methods: GET, HEAD and OPTIONS-. The users, with a JWT, can perform any kind of request. Login and register views works through POST requests due to modify the state of the application. The issue is the above permission avoids … -
django-background-tasks process_tasks not working
I've set up a django project with the instructions from the docs, and have a simple task: @background def test_task(): print("wtf") I then ran the test_task() function within the manage.py shell, and the task was successfully added to the DB (SQLite3). However, when I ran python manage.py process_tasks nothing happened. This module isn't very popular to say the least, so I couldn't find any answers to my problem until 5 minutes ago on a closed issue on the module's repository on github. And I am deciding to post this below. PS: I am running Django 2.2 for this project -
Django - Dividing a modelform into sections
I am making a property management app where the user can fill out a rental application. I'm looking for a way to divide my form into sections like Personal Information: item item item item Rental History: item item item item Employment item item item My form class ApplicantForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ApplicantForm, self).__init__(*args, **kwargs) self.fields['property'].queryset = Properties.objects.filter(is_active=True) class Meta: model = Applicant fields = '__all__' exclude = ['application_date'] widgets = { 'requested_move_in_date': DateInput(), 'dob': DateInput(), 'job_length': DateInput(), } labels = { 'requested_move_in_date': 'Requested Move in Date', 'dob': 'Date of Birth', 'ssn': "Social Security Number", 'job_length': "Job Start Date" } My template {% load crispy_forms_tags %} {% block content %} <div class="jumbotron text-center"> Application page </div> <form class="post-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-primary">Submit</button> </form> {% endblock %} -
Django - Detecting Value of Field in Model - Views
I need to loop through all field objects of a model in Django. Once I look through I need to detect if in any of the entries of data this specific field(type) is equal to "Date1". If it is I need it to send a variable(val) that is a string equal to "True" to the Django templates. I have everything set and it seems simple and it seems like it should work. On its own, the val can send a value to the template when it is not in an if statement and the for loop also properly works. Even when "Date1" exists as a value in the type field of an entry in the model "Field_Repo1" the val isn't sent and the if statement is never iterated through(I know this by using prints). No matter what the if statement is never run through. Code Below. Thanks in advance. context = {} context['Field_Repo1'] = Field_Repo1.objects.filter(user=response.user) for type1 in Field_Repo1.objects.values_list('type'): if type1 == "Date1": val = "True" context['val'] = val print(val) print(AHHHHHHHHHHHH) if response.method == 'POST': form = Field_Repo1_Form(response.POST, response.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = response.user instance.save() response.user.Field_Repo1.add(instance) return redirect('repo1') else: form = Field_Repo1_Form() context['form'] = form return render(response, … -
How to change input method of Django default form ? from text input to choices
I have below create view, class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title','name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and in Post create template I just put it as a form tag <form method="POST" > {% csrf_token %} {{ form|crispy }} </form> I want name field to be dropdown choice in frontend HTML, What shall I do ? It is possible by adding choice field in models.py but I can not do that and I have another idea to implement, -
DJango Composite priamary key with instance field values
hi im having troubles in django 3.2 with a work arround for composite key's. as my customer request he needs a composite key as primary key not just on unique_together constraint so im wonder if there any way or place to intercept the instance be fore validation and populate the composite key with values from the other fields and save it to the db ej: class MyModel(models.Model): foo = models.UUIDField(default=uuid.uuid4, auto_created=True, editable=False, max_length=36) bar = models-charfield() taz = models.charfield() composite_key = models.charfield(primary_key=True, default = 'foo' + 'taz' + 'foo') somthing among these lines i cant get pass from the form field validator on django admin site so i really cant test signals or save() method any help wil be apreciated. -
how can i map manual with django-elastcisearch-dsl
So as Stack does not want i ask for clarification on it (#Near duplicate), where i have to put fields declaration under Index class or under Django class. class MyDocument(Document): class Index: # here class Django: # here Near duplicate : How to map keyword field in Django Elasticsearch? -
User has no customer
In a Django project, i have two apps; ecommerce and users. Ecommerce app has situation where logged in users are expected to be customers and they can add to cart. Non logged in users can as well add to cart. In the users app, new users are to register, logged in and be redirected to the store page(store.html). The new registered users does not have this customer instance I guess, reason I'm getting the User has no customer RelatedObjectDoesNotExist. How can I integrate this new registered users to have this customer instance so they can be redirected to the store page? or give a condition where not all users must have a customer instance. (ecommerce app) models.py: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): """String for representing a model object""" return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False,null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): """String for representing a model object""" return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = … -
Blog matching query does not exist
I am using slug to to show my blog details page. here is models.py class Blog(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='post_author') blog_title=models.CharField(max_length=264,verbose_name='Put a Title') slug= models.SlugField(max_length=264,unique=True) blog_content=models.TextField(verbose_name='what is on your mind?') blog_image=models.ImageField(upload_to='blog_images',verbose_name='Image') publish_date=models.DateTimeField(auto_now_add=True) update_date=models.DateTimeField(auto_now=True) class Meta: ordering = ('-publish_date',) def __str__(self): return self.blog_title+' From :'+str(self.author) blog list views.py def Creating_blog(request): form=BlogForm() if User.is_authenticated: if request.method=='POST': form=BlogForm(request.POST,request.FILES) blog_obj=form.save(commit=False) blog_obj.author=request.user title=blog_obj.blog_title blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4()) blog_obj.save() return redirect('bloglist') return render(request,'blogs/createblog.html',{'form':form}) urls.py from django.urls import path from .import views urlpatterns = [ path('write/',views.Creating_blog,name='creatingblogs'), path('bloglist/',views.BlogList.as_view(),name='bloglist'), path('details/<slug:slug>/',views.blog_details,name="blog_details") ] blog_list page html anchor tag code <div class="col-sm-8"> <p>{{blog.blog_content|capfirst|truncatewords:100}}<a href="{% url 'blog_details' slug=blog.slug|slugify %}">Read More</a></p> </div> I can see the blog list page but when it try to see blog details it shows me this error DoesNotExist at /details/big-time-space-rarity-9a3d63b4-634a-11ec-9db9-9c7bef6a0e62/ Blog matching query does not exist. I have tried adding some new blog but it shows me the same. please help me out this and kindly ask me if any description needed. Thanks in advance. -
How to reference a index field from fk model in admin
I want to made a thumbnail in admin model. For now i have: models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) admin.py class AdminProductModel(admin.ModelAdmin): model = Product def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( '<img src="%s" style="width:30px;height:30px;">' % (ProductImages.image_file.url)"""here is my doubt, i need only 1 image""" ) list_display = ['product_thumb','user','slug','created_at'] ... Well, the ProductImages model store all images related with Product model, and i need get 1 image related to made thumbinail in admin -
Access denied to css file that is public on S3 AWS bucket
So I have a Django application running on a docker container, on AWS EC2. The static content is hosted on an S3 bucket (css, javascript, etc.). This all works fine. I did implement a PDF output for some files using weasy print. Locally, it produces the expected PDF fine. However on the server, I get a 500 error. Upon closer inspection, the following error popped in the django logs that I have added to my decorator (that is responsible for generating the PDF). The decorator decorates some handle that is called, and the produced PDF shows up in the download folder. A decorated handler: @generate_pdf_httpresponse def handler_warehouse_packingslip(request, **kwargs): id = kwargs.get("pk") context = { .... details to provide to print.... } filename = "foo.pdf" infos = {"context":context, "template_path":'projectlibs/pdf_outputs/pdf_base.html', "extra_css_files":[], "filename":filename,"request":request} return infos The decorator: def generate_pdf_httpresponse(func): @functools.wraps(func) def wrapper_generate_pdf_httpresponse(*args, **kwargs): try: logger.info(f"Wrapper for pdf response") value = func(*args, **kwargs) html_string = render_to_string(value.get("template_path"), context=value["context"]) html = HTML(string=html_string, base_url=value["request"].build_absolute_uri()) css_files = [] pdf = html.write_pdf(stylesheets=css_files) logger.info(f"Creating tmp file for pdf response") with tempfile.NamedTemporaryFile() as file: file.write(pdf) file.seek(0) stream = file.read() httpresponse = HttpResponse(content_type='application/pdf;', content=stream) httpresponse['Content-Disposition'] = f'attachment; filename={value["filename"]}' httpresponse['Content-Transfer-Encoding'] = 'binary' return httpresponse except Exception as ex: logger.error(f"PDF wrapper failed: {ex}") return … -
Django: Filtering the fields of the m2m model from the models associated with the m2m model will take time
There are quite a few lines of code and logs that may be complicated and difficult to understand. I apologize for that. The following is OR full-text search for Video.title and Tag.name using pgroonga, an extension for full-text search. But the query takes about 2000-4000 ms to execute. The number of hits is about 130,000, but we have a LIMIT 20 limit. The index for full-text search is being used successfully. Video: 300K rows Tag: 5K rows video_tag_through: 1.3M rows # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) ... class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) updated_at = models.DateTimeField(auto_now=True) ... class History(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Favorite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_wl = models.BooleanField(default=False, editable=False) ... class Track(models.Model): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... # migration file ... operations = [ migrations.RunSQL( "CREATE EXTENSION pgroonga", "DROP EXTENSION pgroonga", ), migrations.RunSQL( "CREATE INDEX pgroonga_video_index ON videos_video USING pgroonga (title pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_video_index", ), migrations.RunSQL( "CREATE INDEX pgroonga_tag_index ON videos_tag USING pgroonga (name pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_tag_index", ), ] # lookups.py class Groonga(Lookup): lookup_name = … -
Create list of Approvers Django
I am trying to create an application where you can create project-based expenses, and each project should have a list of approvers who will approve the expense once uploaded to the project, how do I replicate this in Django. What I tried to do. I got the approvers into the form as a ModelMultipleChoiceField self.fields['approvers'] = forms.ModelMultipleChoiceField(queryset=Profile.objects.all()) and saved it as a list into the database def getApprovers(approvers): id = [] for profile in approvers: id.append(profile.id) return id in project create function project.approvers = getApprovers(form.cleaned_data['approvers']) I created a templatetag to display the list of approvers as the Profile Queryset objects. I tried to iterate over the saved list of approvers, but I keep getting errors def approvers_list(approvers): for profile in list(approvers): return profile How better can I represent this. here is the project and expense models class Project(MiscClass): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True, unique=True) slug = models.SlugField(max_length=500, null=True, blank=True, unique=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) approvers = models.CharField(max_length=100, null=True, blank=True, validators=[int_list_validator]) class Meta: ordering = ['-created'] def __str__(self): return str(self.title) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) class Expense(MiscClass): PROCESSING … -
ModuleNotFoundError: No module named 'PIL' , after installing in new PC
I have cloned a Git repo which have Pillow==5.2.0,but even after installing it results in above error during execution. Currently the models.py have, from PIL import Image Tried, import Image from Pillow import Image import Image // after installing Image library but no success, However the same Git repo works perfectly on Win 7 machine but after cloning and installing in new Win 10 , the error happens Project link https://github.com/Anoop-George/farmproject.git -
Name is not defined (Django queryset.filter) [closed]
What i want to do is i want to only show article comments that belongs to article that author has a public profile attribute. Here is the problem ,i get "name is not defined" on filters which points to here: Filters #this works totally fine class FollowedUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__followers__author=request.user ) #this is the one with issue class PublicUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__public_profile = true ) But the interesting thing is that i have another filter which works pretty fine (as i pointed above). Views.py class PublicUserServiceCommentViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = UserServiceComment.objects.all() serializer_class = UserServiceCommentSerializer filter_backends = [PublicUserServiceCommentFilterBackend] Models class UserServiceComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='userservicecomments_set') userservice = models.ForeignKey(UserService, on_delete=models.CASCADE, related_name='userservicecomments') content = models.CharField(max_length=100) class UserService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='userservices') userservice = models.CharField(unique=False,max_length=100,null=True,blank=True) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) public_profile = models.BooleanField(default=True) I get "name not defined" but i can't point out which name it is. When i try directly from browser it is fine but it gives error when trying from Curl or Json. Syntax looks fine, I checked it multiple times. What is the issue?Did I … -
127.0.0.1:8000/admin/ won't load up
Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: C:\Users\User\PycharmProjects\pythonProject2\venv\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\User\PycharmProjects\pythonProject2\mywebsite', 'C:\Users\User\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python310', 'C:\Users\User\PycharmProjects\pythonProject2\venv', 'C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages'] Server time: Mon, 27 Dec 2021 18:46:36 +0000 -
Django Admin panel refuses Content Security Policy
I am struggling to use django-csp in my admin panel, I can see my frontend with vue3 and vite, you can see my demo site on here. When I try to log in admin I get a black screen and in the console, I see the error below: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' fonts.googleapis.com ajax.cloudflare.com static.cloudflareinsights.com www.google-analytics.com ssl.google-analytics.com cdn.ampproject.org www.googletagservices.com pagead2.googlesyndication.com". Either the 'unsafe-inline' keyword, a hash ('sha256-Tq5HCCxkFfCSF4NPeTUcXBhJqVIuv2SvsJXpa2ACR2Y='), or a nonce ('nonce-...') is required to enable inline execution. I configured my django-csp in my settings: # default source as self CSP_DEFAULT_SRC = ("'none'",) CSP_INCLUDE_NONCE_IN = ["default-src"] CSP_STYLE_SRC = ("'self'", 'fonts.googleapis.com', "'unsafe-inline'", "'unsafe-eval'", "https") # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'", 'fonts.googleapis.com', "ajax.cloudflare.com", "static.cloudflareinsights.com", "www.google-analytics.com", "ssl.google-analytics.com", "cdn.ampproject.org", "www.googletagservices.com", "pagead2.googlesyndication.com") # images from our domain and other domains CSP_IMG_SRC = ("'self'", "www.google-analytics.com", "raw.githubusercontent.com", "googleads.g.doubleclick.net", "mdbootstrap.com") # loading manifest, workers, frames, etc CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'fonts.googleapis.com') Can you help me to fix this? Thanks -
Django - how to validate data from post that is not in a django form?
I am receiving post data from my template but it's being created with js, it is not a django form. I know that if I am posting a field using a django form I can use form.is_valid() or x = form.cleaned_data['field'] but I don't know how to validate/clean my data when not using a django form. The reason that I'm using js for this form/template is to get a specific look that I couldn't do with a standard django template/form. models.py class AssessComment(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) comment = models.TextField(blank=True) js snippet // this js is appended to the grade-form element in the template document.getElementById('grade-form').appendChild(table); comment = document.createElement('td'); commentName = "row-" + n + "-comment"; commentText = document.createElement("textarea"); commentText.setAttribute("name", commentName); rowName[n].appendChild(comment); comment.appendChild(commentText); The above js is putting a textarea in a table and giving it the name commentName. The template sends this as a post to my view. I iterate through several rows of n. template div class="form-group"> <form action="" method="post">{% csrf_token %} <div id="grade-form"></div> <!-- js is inserted here --> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> views.py while s < len(cs): comment = "row-" + str(s) + "-comment" form_comment = request.POST[comment] # … -
Django This backend doesn't support absolute paths after integrating aws S3 bucket
I found similar question on stackoverflow on this topic but still now my problems didn't solved. I am facing following problems after integrating aws S3 bucket: problem 1: Image resizing not working after integrating aws S3 bucket. problem 2: getting this error page after image upload NotImplementedError at /blog/edit/hello/ This backend doesn't support absolute paths. here error details of my terminal "C:\Users\Fdg\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\files\storage.py", line 123, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. [27/Dec/2021 23:49:44] "POST /blog/edit/hello/ HTTP/1.1" 500 118419 my settings.py AWS_ACCESS_KEY_ID = "my acess key" AWS_SECRET_ACCESS_KEY = "my secret key" AWS_STORAGE_BUCKET_NAME = "my bucket name" AWS_S3_CUSTOM_DOMAIN = 'my aws domain name' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA = '/media/' AWS_STATIC = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' here is my models.py for upload images: class BlogHeaderImage(models.Model): image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )]) blog = models.ForeignKey(Blog,on_delete=models.CASCADE,related_name="blog_header_image") def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.image.path) def __str__(self): return str(self.blog) Though I am getting this error but image is uploading on aws … -
Django get count of total quantity in cart
I 'm trying to get the total quantity of the items I have added to cart. e.g. Item id 1 quantity 1 pc Item id 2 quantity 1 pc Item id 3 quantity 4 pcs There are 6 pcs in total in cart. In cart detail page, I could get correct count using this line {{cart.get_total_qty}} This is my cart.py page: class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] item['quantity'] = int(item['quantity']) yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def get_total_qty(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True Now I … -
Getting errors after installing Django AllAuth and migrating
Help! I'm getting errors after installing Django AllAuth and migrating! Errors: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/apps/registry.py", line 93, in populate raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth``` -
Какие поля нужны для хранения счета? [closed]
Нужна модель матча по пинг понгу. Требуется модель, из которой можно будет взять следующие данные: Время | Игрок1 | Игрок2 | Выигранные сеты игрока1 | сеты игрока2 | счет по сетам например 16.01.01 | олег | данил | 3 | 0 | 11:3, 11: 6, 11: 9 пока что модель выглядит так class Game(models.Model): date = models.DateTimeField(auto_now_add=True) player1 = models.CharField() player2 = models.CharField() sets1 = models.IntegerField() sets2 = models.IntegerField() А какие поля нужны для хранения счета? Еще важно, что количество сетов может быть разным, и соответственно количество счетов по сетам тоже. -
How can I limit access to certain urls depending on the logged in user?
first of all I want to clarify that I am new to this, so if I fail in some concepts I apologize in advance. I have configured the django administration panel, with an administrator user and two other users that I need to have different permissions to access certain urls of the web environment. In the home page there are three titles with links to three different sections of the page: SECTION A, SECTION B AND SECTION C. I want to have a user that has access to all the sections of the page and the other user that has access only to two sections. How can I manage that? Another thing I would need is the following: in my configuration, by default, when you launch the web server, the first thing that opens is the django administration portal, but I need that when you log in with a user, access directly to the url that has permissions. Thanks in advance -
Understand the responsibility of each part of django architecture
Im a little confuse about Django responsibility architecture. In my project, i chose work with CBV and built-in urls. In my studies, i understood that the responsibilities are divided into: Model, View, Template where: Model takes care data and DataBase, from docs : "definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing" View takes care about request and response Template is a hight level layer app to show data correct me if not that. Most of my questions are where to put the codes, eg: In my models i use something like: class Product(models.Model): ..."""other fields""" user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_title_seo = models.CharField(max_length=255, default='product_title_seo') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = slugify(self.product_goal + " " + self.product_type + " " + self.product_district) self.product_title = slugify(self.product_title) if not self.slug: self.slug = self.product_title_seo return super().save(*args, **kwargs) So as we can see i have 3 methods inside my model class, but i need some treatment for the majority of fields which would represent a considerable increase in methods. This approach is correct, a lot of …