Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to remove default string " Currently: avatar/default.png " from template
I'm using Django to upload user avatar,my question is ,how to remove the default string " urrently: avatar/default.png Clear " from template Model: class User(AbstractUser): nickname1 = models.CharField(max_length=30, blank=True, null=True, verbose_name='昵称') url = models.URLField('个人网址', blank=True, help_text='提示:网址必须填写以http开头的完整形式') avatar = ProcessedImageField(upload_to='avatar', default='avatar/default.png', verbose_name='头像', processors=[ResizeToFill(100, 100)], # 处理后的图像大小 format='JPEG', # 处理后的图片格式 options={'quality': 95} # 处理后的图片质量 , blank=True ) identifier = models.CharField(max_length=40, unique=True,blank=True, null=True) ... USERNAME_FIELD = 'identifier' def save(self, *args, **kwargs): if len(self.avatar.name.split('/')) == 1: self.avatar.name = self.username + '/' + self.avatar.name super(User, self).save() class Meta: verbose_name = '用户信息' verbose_name_plural = verbose_name ordering = ['-id'] def __str__(self): return self.username url: path('<str:username>/', views.account_profile,name = 'process'), view.py: @login_required def account_profile(request, username): profile_user = get_object_or_404(User, username=username) messages = [] if request.method == 'POST': form = UserDetailForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() messages.append('资料修改成功!') form = UserDetailForm(instance=request.user) return render(request, 'user/user_detail.html', context={'form': form, 'messages': messages, 'profile_user': profile_user,}) form: class UserDetailForm(ModelForm): class Meta: model = User fields = ['avatar',] template: <form class="profile" method="post" enctype="multipart/form-data" action="/<str:username>/"> {% csrf_token %} {{ form|crispy }} <div class="avatar"> <img class="img-rounded" src="{{ request.user.avatar.url }}"> </div> <button class="primaryAction" type="submit">更新资料</button> </form> In the form I only set filed avatar there,but there is always a string " Currently: avatar/default.png Clear " Any friend know how to remove this string? -
Django submitting multiple forms in one page
I have a store with the models: Items, Cart. I created a loop to display the Items in the html file but only if they are in stock (if quantity > 0). However, the user can only add 1 item at a time and the page has to refresh. I'm trying to do it so that the user can enter the quantity for each item and then have one submit button for them all, but I can't seem to figure it out. I tried modelformset and formset, but the examples are confusing. Django's documentation shows it in console mode and it doesn't match when I'm trying to do. Here are the models: #model: Items class Items(models.Model): STORAGE_TYPE = { ('Dry', 'Dry'), ('Frozen','Frozen'), ('Refrigerated','Refrigerated'), ('Other','Other'), } ITEM_TYPE = { ('Produce', 'Produce'), ('Grains', 'Grains'), ('Protein/Dairy', 'Protein/Dairy'), ('Extra Items', 'Extra Items'), } item_name = models.CharField(blank=False, null=False, max_length=255, unique=True) weight = models.FloatField(blank=False, null=False, default=0) quantity = models.IntegerField(blank=False, null=False, default=0) description = models.TextField(max_length=1279, blank=True, null=True) image = models.ImageField(upload_to='fp/', null=True, blank=True) price = models.IntegerField(default=1, blank=False, null=False) storage_type = models.CharField(max_length=255, null=True, choices=STORAGE_TYPE, default="Dry") item_category = models.CharField(max_length=255, null=True, choices=ITEM_TYPE, default="Produce") limit = models.IntegerField(default=999, blank=False) show = models.BooleanField(default=True, blank=False, null=False) date_created = models.DateTimeField(auto_now_add=True, null=True) modified_timestamp = models.DateTimeField(auto_now=True, null=True) #model: … -
Creating a Simple form using django. Stuck between two error, Attribute Error and Key error
This is my form code and I am getting error an Keyerror on line 7 i.e name and also email.I am also getting attribute error on line with ValidationError. from django import forms from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class StudentRegistration(forms.Form): name= forms.CharField() email= forms.EmailField() def clean(self): cleaned_data = super().clean() valname= self.cleaned_data ['name'] valemail=self.cleaned_data [ 'email'] if len(valname) < 8: raise forms.ValidatonError('Name should be more than or equal to 4') if len(valemail) < 10: raise forms.ValidatonError('Abe dhang se daal') -
Django models.OneToOneField(User) not able to access data by user.profile in profile.html
I am trying to display the fields qualification and name that I defined in my Profiles>>models.py file to show on the web page itself. I am trying to call the info with user.profile.name and user.profile.qualification.all but it doesnt find it models.py: from django.db import models from django.contrib.auth.models import User class UserQualifications(models.Model): name = models.CharField(max_length=64, unique=True) normalizedName = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=200) def __str__(self): return self.name class Profiles(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") qualification = models.ManyToManyField(UserQualifications, blank=True) name = models.CharField(max_length=50, blank=True, null=True) isHighSchoolGraduate = models.BooleanField(default=False) isUndergraduate = models.BooleanField(default=False) isCollegeGraduate = models.BooleanField(default=False) isDoctor = models.BooleanField(default=False) isExpert = models.BooleanField(default=False) def __str__(self): return f'{self.user.username} Profiles' profile.html {% extends 'base.html' %} {% block content %} <h1> {{ user.get_full_name }} (@{{ user.username }}) </h1> {% with profile=user.profile %} {% if profiles %} <h2> {{ profile.name|default:"" }} </h2> <br/> <div> Qualifications: {% for qualifacation in profile.qualification.all %} <span> {{ qualifacation.name }}{% if not forloop.last %}, {% endif %} </span> {% endfor %} </div> {% endif %} {% endwith %} {% endblock %} -
Django: ModelFormSet.is_valid() throws django.core.exceptions.ValidationError: ManagementForm data is missing or has been tampered with
I know this error has been asked about before plenty of times on SO, but none of the other threads that I read seem to have the same situation as me, in that I am not trying to render the formset AT ALL. I simply want it for posted data validation purposes alone. Is this not a supported way of using ModelFormSets? The Django docs suggest that I can do this: from django.forms import modelformset_factory from django.shortcuts import render from myapp.models import Author def manage_authors(request): AuthorFormSet = modelformset_factory(Author, fields=('name', 'title')) if request.method == 'POST': formset = AuthorFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() # do something. else: formset = AuthorFormSet() return render(request, 'manage_authors.html', {'formset': formset}) So I can't for the life of me understand why the below code is apparently so illegal: def add_player_to_teams(request): AddPlayerToTeamsFormSet = modelformset_factory( Team, fields=['players']) team_ids = post_data.getlist('team_ids') # Tried adding this, but the stupid thing **still** refuses to work! teams_init_data = { 'teams-TOTAL_FORMS': len(team_ids), 'teams-INITIAL_FORMS': '0' } post_data = post_data.copy() post_data.update(teams_init_data) teams_form_set = AddPlayerToTeamsFormSet(post_data, queryset=Team.objects.filter(unique_id__in=team_ids)) status_dict = { 'status': True, 'errors': None } user = request.user if not teams_form_set.is_valid(): # Here's where it breaks status_dict['status'] = False status_dict['errors'] = teams_form_set.errors else: user.registration_step += 1 user.save() for team … -
Is there way to add paypal to website for buying courses
Is there a way to add paypal to the website to buy the courses in my website .. I have a section for the courses and I want to make it paid, I want the user to choose a specific course and pay by paypal and when the user pays it will be opened for him forever What should I do this .. I mean, what are the right steps to do this ? -
Django rest framework - Nested queries, Passing queryset to response
I am using the Django rest framework and trying to fetch a response for a logistics use case that is based on two models. Model 1 is basically a model that stores the data on which users are assigned which lanes(routes). class BuyerFreightLaneMatrix(models.Model): buyer_email_id = models.ForeignKey(BuyerDetail, on_delete=models.CASCADE, related_name='buyer_Freight_Lane_matrix_buyer_detail_email_id_set') user_email_id = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="user_mapped_lanes") assigned_freight_lanes = models.ManyToManyField(MasterTableLane, related_name='user_mapped_lanes') and model 2 is where we store the data on the freight rates for each lane. class FreightRate(models.Model): lane_name = models.ForeignKey(MasterTableLane, on_delete=models.DO_NOTHING, related_name='Freight_rates_by_lane_name') lane_rate_per_ton = models.DecimalField(max_digits=12, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) created_by_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='freight_rates_created_by_User') updated_at = models.DateTimeField(auto_now=True) updated_by_user = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='freight_rates_updated_by_User') class Meta: ordering = ['-updated_at'] get_latest_by = ['-updated_at'] def __str__(self): return str(self.lane_name)+str('-Rs ')+str(self.lane_rate_per_ton)+ str('per MT') My serializer is class BuyerMappingWiseFreightRateSerializer(serializers.ModelSerializer): user_mapped_lanes = BuyerFreightLaneMatrixSerializer(many=True,read_only =True) class Meta: model = BuyerFreightLaneMatrix fields = ['user_mapped_lanes'] depth = 2 what I am trying to achieve is, for a given user_email_id in model 1, fetch the assigned_freight_lanes that are mapped to him, and then for each of those lanes, get the latest lane_rate_per_ton based on updated_at timestamp from model 2. I have attempted to do this using Viewsets and generics in the Django rest framework and here are my views class BuyerFreightRateView(generics.ListAPIView): serializer_class = BuyerMappingWiseFreightRateSerializer … -
How long it will take you to complete this project?
My daily job is fixing code and implementing small features, so I never actually start any project from scratch, just wondering, on average how long will took for any developer to build this project? There's few part of the project that will connect to each other, the main goals is to create a simple GUI to extends functionality of existing SPA. Selenium: Login to the SPA Submit form thru the SPA Scrape the data from the SPA Get the status of the submitted form Django Get the data from Selenium Sent command to Selenium Keep the data in database Provide API to view (React) React Render new application for displaying data, submit data I know everyone got their own pace on building something, just I want to get a benchmark, if you are building this project, how many hours you will take? and How many hours you think is average. Please give your opinion. Sorry if the project requirement seem vague. Thanks! -
Django - How add a user to a group with Class Based View
I'm having some issues trying to add a user to specific group with generic CreateView. The trouble is that i want that only one user creates the user's accounts and assign him to a group The form is rendering correctly and it seems select the correct group without issue, but when i check the user doesn't have any group assigned. I tried many ways that i sow but any seems work for me. I dont know if i should do it in (Post method), or form_valid() Im using the CreateView but I'm not so good modifying the class it self, Please any help Im using the default user and this is my create class Views.py class CreateUserView(LoginRequiredMixin, CreateView): model = User form_class = CustomUserForm template_name = 'accounts/create_user.html' queryset = User.objects.all() def get_success_url(self): return reverse_lazy('accounts:list_user') def post(self, request, *args, **kwargs): if self.request.method == 'POST': form = self.form_class(self.request.POST) if form.is_valid(): self.object = form.save(commit=False) # form_class = self.get_form_class() # form = self.get_form(form_class) # position = int(request.POST['groups'])-1 # self.object.groups.add(position) my_group = Group.objects.get(name="Usuario Avanzado") my_group.user_set.add(self.object) self.object.save() return HttpResponseRedirect(self.get_success_url()) return HttpResponseRedirect(self.get_success_url()) Please any help I'll be so grateful -
Django get_or_create how to use it on foriegnkey?
How do i use get_or_create in foriegnkey? i have this code, that if the Student_Users(foriegnkey) doesnt exist the data will inserted and if not the data will update, but in my case even though the Student_Users exist the record inserted. insert_data, created = studentsRecord.objects.get_or_create( Student_Users=student, School_Year = schoolyear Education_Levels = educationlevel ) if not created: insert_data.Student_Users = student insert_data.School_Year = schoolyear insert_data.Education_Levels = educationlevel insert_data.save() -
How to implement password change in Django Rest Framework without repeating code (DRY principle)
I have a Django app that already has a web interface for changing passwords. It uses django.contrib.auth functions and django.views.generic.UpdateView. Here is the code: class PasswordChangeView(LoginRequiredMixin, generic.UpdateView): form_class = PasswordChangeForm template_name = 'form.html' input_value = 'update password' def post(self, request, *args, **kwargs): form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! try: request.user.auth_token.delete() # Important! except (AttributeError, ObjectDoesNotExist): pass messages.success(request, 'Your password was successfully updated!') return redirect('/') else: messages.error(request, 'Please correct the error below.') def get(self, request, **kwargs): form = PasswordChangeForm(request.user) return render(request, self.template_name, {'form': form, 'input_value': self.input_value}) The above code works fine in the web interface. Now I want to implement REST API for changing passwords. I know that I can create APIView/viewset and serializer to do that (like the answers for this question), but it will violate DRY principle. What is the best way to implement the REST API interface for that given that there is already a fully-functional web interface? -
Stripe API error when running Django server
I am trying to run a django server under my localhost and I need help with an error. Everytime I try to run my django server with python manage.py runserver, I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/john/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/john/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 408, in check for pattern in self.url_patterns: File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/john/django-stripe-tutorial/myvenv1/lib/python3.7/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/home/john/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, … -
Trouble Setting Up React and running npm run dev
I am getting the error Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation. If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing. when I go to run npm run dev. I am very new to React and have limited knowledge; I am currently following a tutorial and got lost setting up the React. In my 'presets' section, I already have @babel/preset-react in there, so I don't know why the error is occurring or how to fix it. Here is my babel.config.JSON: { "presets": [ [ "@babel/preset-env", { "targets": { "node": "10" } } ], "@babel/preset-react" ], "plugins": ["@babel/plugin-proposal-class-properties"] } -
Voice chat integration with Django Channels
I'm developing django + angular app, that's use django channels and need voice chat functional. I found simple realization of the voice chat with socket, threading and pyaudio packages. Server example: class Server: PORT = 6655 def __init__(self): self.ip = socket.gethostbyname(socket.gethostname()) while True: try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.ip, self.PORT)) break except socket.error: print("Couldn't bind to that port") self.connections = [] self.accept_connections() def accept_connections(self): self.socket.listen(100) print('Running on IP: ' + self.ip) print('Running on port: ' + str(self.PORT)) while True: connection, addr = self.socket.accept() self.connections.append(connection) threading.Thread(target=self.handle_client, args=(connection, addr)).start() def broadcast(self, sock, data): for client in self.connections: if client != self.socket and client != sock: try: client.send(data) except: pass def handle_client(self, connection, addr): while True: try: data = connection.recv(1024) self.broadcast(connection, data) except socket.error: connection.close() And have some questions about it: Can I realize this solution on django channels? Can I use such threads in django channels, is thread safe? -
Is PyCharm Community Edition doesn't have Database Tool?
I'm using pycharm 2020.3 community edition. but id doesn't showing database tool. it means this edition comes without that option? or any action we have to do for this? *Note: some people saying add plugin data base browser. but that is not built in. I want database tool. -
Django : 'collections.OrderedDict' object is not callable
I am trying to make a post request to module User which inherits AbstractUser using serializer UserSerializer, but I'm getting the error 'collections.OrderedDict' object is not callable on-field "PhoneNumber". Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model= User fields="__all__" def save(self, **kwargs): user = User( username = self.validated_data.get('username'), first_name =self.validated_data.get('first_name'), last_name = self.validated_data.get('last_name'), email=self.validated_data.get('email'), Address=self.validated_data.get('Address'), PhoneNumber=self.validated_data('PhoneNumber')) user.save() User Model: class User(AbstractUser): Address=models.TextField(blank=True,null=True) PhoneNumber = models.CharField(max_length=15, blank=True,verbose_name='PhoneNumber') cdNumber = models.CharField(max_length=16, blank=True,verbose_name='cdNumber') cdDate=models.DateField(blank=True,null=True,verbose_name='cdDate') cdName = models.CharField(max_length=16, blank=True,verbose_name='cdName') def __str__(self): return self.first_name+" "+self.last_name -
Cant pinpoint the cause of a Module Not Found error
Here is the traceback for a project called zealplaza. (venv) mike@system76-pc:~/projects/zealplaza$ python3 manage.py migrate Traceback (most recent call last): File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/mike/projects/zealplaza/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) 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 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'zealmarkets' … -
What is the best way to get parent model data in serializer?
I have two models: Company(DateTimeModel): title = models.CharField(max_length=100) ... Contract(DataTimeModel): ... company = models.ForeignKey(Company, on_delete=models.CASCADE) When I want to create a contract I want to send only company id For example my input: { "some_fields": "foo", ..., "company": 1 } But in output I want to get id and title { "id": 1, ..., "company": { "id": 1, "title": "company title", } } This is my serializer: class ContractSerializer(serializers.ModelSerializer): company_id = serializers.IntegerField(write_only=True) company = CompanyRelatedSerializer(read_only=True) But I should create validation for company_id manualy and it is two different fields. I guess there is a better implementation than mine. How do it better? -
DJANGO Error: UnboundLocalError at local variable 'cart_obj' referenced before assignment
I have limited experience in coding, but I like django and python and I am trying to learn by completing a udemy course called "Build a DJANGO ecommerce web application. It appears the course has some issues, but I have already invested several hours and want to get to the end! Please help !!! I am having problems with the cart build. When I navigate to localhost/cart/cart I receive the above error. I have not posted the settings.py as I think thhe error is limited to the views and models configuration. The relevant information is below: traceback Internal Server Error: /cart/cart/ Traceback (most recent call last): File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\nia\Desktop\Pharma-mart\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\views.py", line 14, in cart_home cart_obj, new_obj = cart.objects.new_or_get(request) File "C:\Users\nia\Desktop\Pharma-mart\pharmamart\cart\models.py", line 22, in new_or_get return cart_obj, new_obj UnboundLocalError: local variable 'cart_obj' referenced before assignment [28/Mar/2021 10:38:40] "GET /cart/cart/ HTTP/1.1" 500 72446 cart/models.py from django.db import models from django.conf import settings from store.models import product, customer from django.contrib.auth.models import User from django.db.models.signals import pre_save, post_save, m2m_changed # Create your models here. User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", default= … -
I need help integrating stripe payments with raspberry pi
I am currently working on a program from a raspberry pi using stripe to send payments after a customer has scanned their card. The card will be read by the raspberry pi using NFC, so I need some way to send the debit/credit card data to the stripe API which can charge the card. I am getting my code from https://github.com/justdjango/django-stripe-tutorial. -
Django: The best / canonical way to preserve / access form fields' 'old' values (before they are updated)
Use cases: I want to programmatically access the value of a form field prior to the update, for one of the following scenarios (just 2 examples, to illustrate the case) a) I want to detect if the original value of a field has been changed in the form, before it's saved in the database b) I want to detect / prevent changing the field value in a very specific way, e.g. if a field value is set to "Approved", it should never change back to "Pending approval", etc. Constraint: Ideally, I would prefer not to do another trip to the database (to check for the old value), for performance reasons. -
Filtro en django
estoy haciendo mi función para filtrar con django_filters este es mi código: class Redaccion(models.Model): titulo = models.CharField(max_length=100) texto = models.TextField() fecha = models.DateField(default=timezone.now) categoria = models.CharField(max_length=255, default='coding') autor = models.ForeignKey(User, on_delete=models.CASCADE) nombre = models.CharField(max_length=255) en filters.py import django_filters from .models import Redaccion class RedaccionFiltro(django_filters.filterset): class Meta: model = Redaccion fields = [ 'categoria', 'fecha', ] y en views es def FiltroViews(request): context = {} filtro_redaccion = RedaccionFiltro( request.GET, queryset = Redaccion.objects.all() ) context['filtro_redaccion'] = filtro_redaccion return render(request ,'categorias/listar_noticias.html', context=context) el problema es que cuando quiero hacer una makemigrations me sale este error File "C:\Users\Rosmari\Desktop\Proyectoparaelmartes\TrabajoFinal\apps\categorias\filters.py", line 5, in class RedacionFiltro(django_filters.filterset): TypeError: module() takes at most 2 arguments (3 given) no estoy entendiendo, estoy siguiendo un tutorial y en este sale bien el código sin problemas gracias desde ya. -
Django how to hide ID from URL
I'm using Django. I want to hide Id from URL. url: path('<int:news_pk>/', views.newsDetailView, name='detail'), View: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) return render(request, "news/pages/index-inner.html", { 'news': news, }) Model: class News(models.Model): title = models.CharField(max_length=100, verbose_name='title') verbose_name='snippet') content = RichTextUploadingField(blank=True, null=True, verbose_name='content') class Meta: verbose_name = "news" verbose_name_plural = verbose_name def __str__(self): return self.title Any friend can help? -
Create a One to One Queryset In Django
I am having trouble creating a queryset by joining two one to one fields. Does anyone know how to solve this problem? I am trying this example here but not getting it to work. Django one to one relation queryset class Category_Driving (models.Model): ACCEPTABLE_UNACCEPTABLE = ( ('acceptable', 'ACCEPTABLE'), ('unacceptable', 'UNACCEPTABLE'), ) bbso_record_id = models.OneToOneField(BBSO_Records, on_delete=models.CASCADE, primary_key=True) vehicle_condition = models.CharField(max_length=12, blank=True, choices=ACCEPTABLE_UNACCEPTABLE, verbose_name="Vehicle in Safe Condition") seat_belt_secured = models.CharField(max_length=12, blank=True, choices=ACCEPTABLE_UNACCEPTABLE) def __str__(self): return self.vehicle_condition class Meta: verbose_name_plural = "CategoryDriving" class BBSO_Records(models.Model): severityLevel = ( ('Level 1', 'Level 1'), ('Level 2', 'Level 2'), ('Level 3', 'Level 3'), ) severity_level = models.CharField(max_length=7, default= "Level 3" , choices=severityLevel) date_recorded = models.DateField() location_details = models.CharField(max_length=50, help_text='e.g. In the kitchen on the 4th floor.', blank=True) # I am trying this code in my view but it is not working. queryset = Category_Driving.objects.filter(id=id).values('vehicle_condition').\ annotate(record_count=Count('vehicle_condition')).order_by('vehicle_condition') This is the error message I am getting: Cannot resolve keyword 'id' into field. Choices are: bbso_record_id, bbso_record_id_id, distracted, inspection, seat_belt_secured, speed, spotter, vehicle_condition Any help will be greatly appreciated. note: I did not show all the fields in my model in the example given. I cut them down not to show all the code. -
Field 'id' expected a number but got 'search'
I got stuck for a couple of hours already, I'm not able to find what could be the mistake. When I click search btn on the form I'm getting the following error. (ValueError at /vehicles/search Field 'id' expected a number but got 'search'.) Why this field is expecting a number when should redirect to 'search'. Any suggestions or help is appreciated! Thank you! view:: def vehicle_detail(request, pk): ad_vehicle = AdVehicle.objects.get(pk=pk) comment_form = CommentVehicleForm() if request.method == 'POST': comment_form = CommentVehicleForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.user = request.user comment.ad_vehicle = ad_vehicle comment.save() return HttpResponseRedirect(reverse('detail_view_ad_vehicle', kwargs={'pk':pk})) return render(request, 'vehicles/single-vehicle.html', context={'ad_vehicle':ad_vehicle, 'comment_form':comment_form}) def search(request): vehicles = AdVehicle.objects.order_by('-publish_date') model_search = AdVehicle.objects.values_list('model', flat = True).distinct() brand_search = AdVehicle.objects.values_list('brand', flat = True).distinct() year_search = AdVehicle.objects.values_list('year', flat = True).distinct() price_search = AdVehicle.objects.values_list('price', flat=True).distinct() # keywords if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: vehicles = vehicles.filter(description__icontains=keywords) if 'model' in request.GET: model = request.GET['model'] if model: vehicles = vehicles.filter(model__iexact=model) if 'transmission' in request.GET: transmission = request.GET['transmission'] if transmission: vehicles = vehicles.filter(transmission__iexact = transmission) if 'year' in request.GET: year = request.GET['year'] if year: vehicles = vehicles.filter(year__iexact=year) if 'price' in request.GET: price = request.GET['price'] if price: vehicles = vehicles.filter(price__lte = price) context = { 'vehicles':vehicles, 'model_search' : model_search, …