Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save custom added field in an extended user creation form in django
I am pretty new to Django and i made a custom signup form by extending the UserCreationForms in Django. class SignUpForm(UserCreationForm): #This class will be used in views of account to make sigupform user_type = forms.CharField(required=True,widget=forms.Select(choices=usertypes)) email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'user_type','email','password1','password2'] def save(self,commit=True): user = super(SignUpForm, self).save(commit=False) user.user_type = self.cleaned_data['user_type'] print('Flag3') if commit: user.save() return user It is working fine with the view : def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) print('Flag0') if form.is_valid(): user = form.save() if user.user_type == 'Seller' or user.user_type=='seller': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Seller') print(group.name) print('Flag3') user.groups.add(group) return redirect('get_seller') if user.user_type == 'Customer' or user.user_type=='customer': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Customer') print(group.name) print('Flag3') user.groups.add(group) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I added flags because is was checking the progress of the form. The problem that i am facing is that i want to save the custom field that made user_type . I don't know how to save the custom field or if it is being saved how to get the value. -
I need to do a form that changes on-the-fly depending of a choice
The form that I need to do is for the user to select a payment type.The problem is that depending on the choice if the user wants to pay monthly or annually a different date-picker field has to appear. if he selects monthly, he has to choose a day of the month. And if he chooses annually a date-picker that allows him to pick the month has to appear. I've been searching online for an answer but all I can find is dynamic form in the sense that it can generate a field type multiples times and that is not what I need. All help is appreciated. -
problem with modelchoicefield show objet 1 and object 2without names?
hi friends i have model structure with code and names (structure_desig) i want show list of choices in modelchoicefield and it shows like this structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that from django.db import models # Create your models here. class Structure(models.Model): structure_code=models.CharField(max_length=1) structure_desig=models.CharField(max_length=350) def __str__(self): return self.structure_desig class Service(models.Model): structure_id= models.ForeignKey(Structure,on_delete=models.CASCADE,null=True) service_desig=models.CharField(max_length=350) class Immob(models.Model): immo_code=models.CharField(max_length=7) immo_desig=models.CharField(max_length=150) immo_qte=models.FloatField(default=1) immo_datemes=models.DateTimeField() immo_cptimmob=models.CharField(max_length=10) immo_dureevie=models.IntegerField(default=7) immo_numaut=models.CharField(max_length=4) immo_origine=models.CharField(max_length=1) immo_fournisseur=models.CharField(max_length=150) immo_nufact=models.CharField(max_length=20) immo_datefact=models.DateTimeField() immo_valht=models.DecimalField(max_digits=18,decimal_places=2) immo_monaie=models.CharField(max_length=3) immo_tauxcvt=models.DecimalField(max_digits=18,decimal_places=2) immo_tauxctrval=models.DecimalField(max_digits=18,decimal_places=2) immo_frais=models.DecimalField(max_digits=18,decimal_places=2) immo_coutacq=models.DecimalField(max_digits=18,decimal_places=2) immo_refcmde=models.CharField(max_length=35) immo_datecmde=models.DateField() immo_journee=models.CharField(max_length=10) immo_cptanal=models.CharField(max_length=9) immo_local=models.CharField(max_length=45) immo_mode_amort=models.CharField(max_length=1) immo_code_r=models.CharField(max_length=2) immo_val_amort=models.DecimalField(max_digits=18,decimal_places=2) immo_status=models.CharField(max_length=1) immo_code_bar=models.CharField(max_length=25) service_id= models.ForeignKey(Service,on_delete=models.CASCADE,null=True) #this is the forms.py from django.contrib.auth.forms import AuthenticationForm from immob.models import Structure from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs= {'class':'form-control'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'class':'form-control'})) class UserRegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) structure = forms.ModelChoiceField(Structure.objects.all(), to_field_name="structure_desig") the result it shows like that without names of structure structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that -
Django how to handle urls.py with a login form in a navbar
I have a login form in a navbar accesible via context processors, I want it to be shown in every page where there's no active user. core/context_processors.py def login_form(request): form = AuthenticationForm() return { 'auth_form': form } The urls.py is stated as normal core/urls.py path('accounts/', include('django.contrib.auth.urls')), And the form in the navbar is called this way: <h2>Login</h2> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ auth_form | crispy }} <input type="submit" class="btn btn-primary" value="Login"/> <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </form> Now I don't want a custom login view, since it's available in all templates. But when I hit login I got redirected to a 404 or the login template if a create one. How can I bypass the template part, login the user and redirect somewhere else? -
Django, psycopg2: permission denied on Heroku server
I have a Django project running on Heroku, every time an action is carried out, I get a looong series of errors like this, all pointing back to the same cause: ERROR:django.request:Internal Server Error: /event/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: permission denied for relation django_session The URL /event/ does not exist on my project, nor is it referenced anywhere in it, and as far as I know there isn't a database associated with this slackbot (so if someone could also direct me as to how to list all existing databases I would be grateful). How can I fix this through Heroku? I tried the online console with some basic psql command, but all I got was this response psql: could not connect to server: No such file or directory -
django multiple annotate sum advanced
I Have the following queryset, and I want to multiple sum using django annotating but i have some error, Could you please have your suggestions on this??, any help will be appreciated. i already try this but not same what i want myqueryset= BuildingCell.objects.filter(absent__publish='2019-07-22', absent__building_name='f2', absent__bagian='CUT', inputcutsew__publish='2019-07-22', inputcutsew__days='normal', inputcutsew__user=factory_user_cutting)\ .exclude(inputcutsew__cell_name__isnull=True).exclude(inputcutsew__cell_name__exact='').order_by('inputcutsew__cell').values('inputcutsew__cell', 'inputcutsew__model', 'absent__normal_mp', 'absent__ot0_mp', 'absent__ot1_mp', 'absent__ot2_mp', 'absent__ot3_mp').exclude(occult_cell='yes')\ .annotate(total_output_jam=Coalesce(Sum(Case(When(inputcutsew__dummy_days='normal', then='inputcutsew__output'))), 0), total_output_ot=Coalesce(Sum(Case(When(inputcutsew__dummy_days='overtime', then='inputcutsew__output'))),0), total_time=Coalesce(Sum('inputcutsew__time'),0), total_time_ot=Coalesce(Sum('inputcutsew__time_ot'),0), total_time_ot1=Coalesce(Sum('inputcutsew__time_ot1'),0), total_time_ot2=Coalesce(Sum('inputcutsew__time_ot2'),0), total_time_ot3=Coalesce(Sum('inputcutsew__time_ot3'),0))\ .annotate( normal_wmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), normal_swmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), overtime_wmh=(Coalesce(F('absent__ot0_mp'),0)*Coalesce(F('total_time_ot'),0))+(Coalesce(F('absent__ot1_mp'),0)*Coalesce(F('total_time_ot1'),0))+(Coalesce(F('absent__ot2_mp'),0)*Coalesce(F('total_time_ot2'),0))+(Coalesce(F('absent__ot3_mp'),0)*Coalesce(F('total_time_ot3'),0)), overtime_swmh=(1.5*Coalesce(F('absent__ot0_mp'), 0) * Coalesce(F('total_time_ot'), 0)) + (2*Coalesce(F('absent__ot1_mp'), 0) * Coalesce(F('total_time_ot1'), 0)) + (2*Coalesce(F('absent__ot2_mp'), 0) * Coalesce(F('total_time_ot2'), 0)) + (2*Coalesce(F('absent__ot3_mp'), 0) * Coalesce(F('total_time_ot3'), 0)))\ .annotate( sum_total_output_jam=Sum(F('total_output_jam')), sum_total_output_ot=Sum(F('total_output_ot')), sum_overtime_wmh=Sum(F('overtime_wmh')), sum_overtime_swmh=Sum(F('overtime_swmh')) ) FieldError at /superuser/inputtime/2/3/f2/CUT/2019-07-22 Cannot compute Sum('total_output_jam'): 'total_output_jam' is an aggregate -
How to fix: "Unknow command: manage.py" in a Django project in PyCharm (newbie)
I'm totally new to Django, just learned a bit Python for science analysis. I use PyCharm as IDE wanted to made the django "tutorial" from the PyCharm website (https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-django-project.html). I struggle quite early at the point "Launching Django Server". So, I can open the new command line with Ctrl+Alt+R, but when I enter "manage.py" as described in the tutorial I get the error "Unknown command: manage.py Type'manage.py help' for usage". If I type 'manage.py help' the same error occurs. Since PyCharm creates the files, the code itself should be functional since I didn't changed a single line. The versions are: PyCharm 2019.1.3 (Professional); Python: 3.7; Django: 2.2.3 I tried to run PyCharm as administrator. Since I'm totally new to Django I also have no idea what else I should try. A google search showed just findings not comparable to mine. -
How to display and hstore field in forms as separate fields in django
I trying to create a form that separates the hstore field address into fields street, city, state, and zipcode in form.py. But when the form is submitted, it will be added to the database as Hstorefield with {'street':street,'city':city,'state':state,'zipcode':zipcode}. Any help is appreciated! model.py from django.contrib.postgres.fields import HStoreField class Student(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True,) fullname=models.CharField(max_length=100,null=False,blank=False,default="fullname") address=HStoreField(null=True) form.py class StudentProfileForm(forms.ModelForm): street=forms.CharField(max_length=80, required=True, strip=True) city=forms.CharField(max_length=50, required=True, strip=True) state=forms.CharField(max_length=20, required=True, strip=True) zipcode=forms.IntegerField(required=True) class Meta: model = Student exclude = ['user'] # I've tried adding this, but that does nothing to the database. def clean(self): self.cleaned_data['address'] = {"street":self.cleaned_data.get('street'),"city": self.cleaned_data.get('city'), "state": self.cleaned_data.get('state'),"zipcode":self.cleaned_data.get('zipcode'),}, self.save() -
Get data related to manytomany field
I have two model, first one is Industries, second one is experts. My models looks like this. name = models.CharField(max_length=255, verbose_name="Industry name") slug = models.SlugField(unique=True, blank=True, max_length=150) class Expert(models.Model): name = models.CharField(max_length=255, blank=True, verbose_name="Expert Name") industry = models.ManyToManyField(Industries, blank=True, verbose_name="Industries") on the all experts page I made an industries field clickable, when user clicked any industry, My goal is show the experts which is in this industry. My urls.py looks like this: path('e/country/<slug:slug>', ExpertCountryView.as_view(), name="expert_country") Now I am confused with my views.py how can I create my view (ExpertCountryView) to shows me experts with this industry. example: www.mysite.com/p/country/trade trade is my industry. I hope all is understandable. -
How to display specific output for specific username in django?
I have made a simple django app. In my models.py I have defined a table- class events(models.Model): id_campaign = models.CharField(default='newevent',max_length=100) status = models.CharField(default='100',max_length=100) name = models.CharField(default='100',max_length=100) This is my views.py - from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView from django.shortcuts import render from website.models import * from website.models import events from django.views.generic import ListView class HomePageView(TemplateView): template_name = 'base.html' class AboutPageView(TemplateView): template_name = 'about.html' class ContactPageView(TemplateView): template_name = 'contact.html' class Success(TemplateView): template_name = 'success.html' def get_context_data(self, **kwargs): context = super(Success, self).get_context_data(**kwargs) query_results = events.objects.all() context.update({'query_results': query_results}) return context And this is the success.html - {% if user.is_authenticated %} <header> <a href=" {% url 'logout'%}">Logout</a> </header> {% block content %} <h2>you are logged in successfully. this is your personal space.</h2> <table> <tr> <th>id_campaign</th> <th>status</th> <th>name</th> </tr> {% for item in query_results %} <tr> <td>{{ item.id_campaign }}</td> <td>{{ item.status }}</td> <td>{{ item.name }}</td> </tr> {% endfor %} </table> {% endblock %} {% else %} <h2>you are not logged in.</h2> {%endif %} I need to check the username in success.html and based on the user I need to show results, how do I do that? if request.user.is_authenticated(): username = request.user.username if username is 'xyz' then I want … -
How do I get a param inside an URL in django admin?
I use django admin and want to access the object id in an URL like this: http://localhost:8000/polls/platform/837/change class PlatformAdmin(admin.ModelAdmin): def get_queryset(self, request): print(request.??) So what should be returned is the 837 -
How to validate Stripe in django-form-tools?
I've a 5 form wizard, with the last step taking credit card details using Stripe. I need to validate the Stripe details and return the user to the form should they generate payment card error. I am doing something like this def done(self, form_list, form_dict, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY .... try: card_token = Card.create_token ( number=self.request.POST['checkout-cardNumber'], exp_month = int(self.request.POST['checkout-expiryDate'].split('/')[0]), exp_year = int(self.request.POST['checkout-expiryDate'].split('/')[1]), cvc = self.request.POST['checkout-cvv'], ) except Exception as e: return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) ... I know this isn't returning an error message but the bigger problem is because I'm in the done method form-tools has cleared the form wizard and it returns me to a blank form at the start of the process. With that in mind I started adding to the clean method of the form. stripe.api_key = settings.STRIPE_SECRET_KEY try: card_token = Card.create_token ( number=cleaned_data['cardNumber'], exp_month = int(cleaned_data['expiryDate'].split('/')[0]), exp_year = int(cleaned_data['expiryDate'].split('/')[1]), cvc = cleaned_data['cvv'], ) except Exception as e: if "Your card number is incorrect." in str(e): self.add_error('cardNumber', "Your card number is incorrect.") else: self.add_error('cardNumber', e) This works great for this example but the next step is to process the card using something like: try: djstripe_customer = Customer.objects.get(subscriber=self.request.user) customer = stripe.Customer.retrieve(djstripe_customer.id) customer.sources.create(source=card_token) except: #deal with exception pass The problem here … -
for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable
I got this error when i try to run python manage.py runserver or any other python manage.py * commands in command line. but when i tried python manage.py shell it connected without error and gets data from database. error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fa03b7386a8> Traceback (most recent call last): File "/home/tornike/apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/tornike/apps/env/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/tornike/apps/env/lib/python3.6/site-packages/debug_toolbar/apps.py", line 25, in check_middleware for i, middleware in enumerate(settings.MIDDLEWARE): TypeError: 'NoneType' object is not iterable MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware' ) -
Django ORM get instance with unique ManyToMany [duplicate]
This question already has an answer here: Django queryset get exact manytomany lookup [duplicate] 1 answer Here is my issue: I want to grab the model instance that has a unique set of ManyToMany instances. For example, I have 3 models (one is a joint table): class Itinerary(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class FlightLeg(models.Model): flight = models.ForeignKey('flights.Flight', on_delete=models.CASCADE, related_name='flight_legs') itinerary = models.ForeignKey('itineraries.Itinerary', on_delete=models.CASCADE, related_name='flight_legs') class Flight(models.Model): itineraries = models.ManyToManyField( 'itineraries.Itinerary', through='itineraries.FlightLeg', related_name='flights' ) I'd like to query the Itinerary instance that has a particular list of flights. For example, let's say I have an Itinerary that has 3 flights with id 1,2,3 respectively. Let's say I have another Itinerary with ids 2,3. In both these cases, I'd like to query the itinerary that has a unique set of flights. So if I query an itinerary with flight id 1 and 2 it should not return the one with flight ids 1,2,3. Right now I've tried this but it obviously doesn't work: flights = [<Flight: B6 987>, <Flight: AM 401>, <Flight: AM 19>] query = reduce(and_, (Q(flight_legs__flight=flight) for flight in flights)) itinerary = Itinerary.objects.filter(query) I only want to return the Itinerary that has these 3 flights and nothing else. … -
How to modify a many-to-many collection using django rest framework
I am trying to create an endpoint where, having a User entity, I can add / remove existing Group entities to user.groups many-to-many field. But when I try to do it, django-rest-framework tries to create new group objects instead of finding existing ones. I have defined two serializers where UserSerializer has a nested GroupSerializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['id', 'name'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'groups'] groups = GroupSerializer(many=True) def update(self, instance, validated_data): data = validated_data.copy() groups = data.pop('groups', []) for key, val in data.items(): setattr(instance, key, val) instance.groups.clear() for group in groups: instance.groups.add(group) return instance def create(self, validated_data): data = validated_data.copy() groups = data.pop('groups', []) instance = self.Meta.model.objects.create(**data) for group in groups: instance.groups.add(group) return instance When I send a JSON: { "id": 6, "username": "user5@example.com", "email": "user5@example.com", "groups": [ { "id": 1, "name": "AAA" } ] } I expect serializer to find the Group with given id and add it to User. But instead, it tries to create a new user group and fails with duplicate key error: { "groups": [ { "name": [ "group with this name already exists." ] } ] } I searched over … -
reverse for app_list error while customizing my admin
while customizing admin page in django facing this error " Reverse for 'app_list' not found. 'app_list' is not a valid view function or pattern name. " but i dont created a view named app_list i have created a directory named admin and created base_site.html file in it admin/urls.py from django.urls import path from .views import InvoiceList, MerchantUserList, SupportStatusUpdate from django.contrib import admin admin.autodiscover() urlpatterns=[ path( 'home/', admin.site.admin_view(InvoiceList.as_view()), name='home' ), path( 'user/list/', admin.site.admin_view(MerchantUserList.as_view()), name='user_list' ), path( 'support/update/<int:pk>/', admin.site.admin_view(SupportStatusUpdate.as_view()), name='support_update' ) ] -
How can I display category in http bar?
Working on eccomerce shop. I have created catogories fucntion which displays the items with particular category. All works fine, but I would like also to display the category name after /category/. I tried GET method but I get error. Any adivse? Value in the button is the Category. form in templates: <form method='post' action='/category/' class="form-inline"> {% csrf_token %} </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="S" style="background-color: grey;">Shirts</button> </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="O" style="background-color: grey;">Outwear</button> </li> <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="S" value="SW" style="background-color: grey;">Sportwear</button> </li> </form> views: def category(request): if request.method=="POST": if request.POST.get('S', False): s = request.POST['S'] objects_display = Item.objects.filter(category=s) if objects_display.exists(): context ={ "objects": objects_display } return render(request, "shop/categories.html", context) else: messages.warning(request, 'no items found') return redirect('item-list') urls: path('category/', category, name='category'), -
I need help to make application with API server(Ubuntu)
I want to make application that have information from Ubuntu server. I don't know what to do in android studio. Do you have example or project for starter? I want to show data from Ubuntu server(Django) and make application. Please, help me.... -
Am I in the right track to become a web developer? [on hold]
long time ago I started learning web development by myself. First in HTML, CSS, JavaScript/JQuery and then Django I am also doing some Android. However, I am a computer science major so I do have a background on coding which made learning much easier. Still, I wonder if I am doing things the right way and where do I place myself in such a competitive field. I have no confidence in what I am doing and I think I might be wasting time because when looking at the jobs description in Glassdoor, all I see is companies looking for people who have minimum two to three years of experience. I have to to say that I do not have professional experience but only side projects that I do in my spare time. Now, my online resume is going to be the first serious project that "push" so I would like you to tell me what do you think about it. Of course, it looks ugly but it is uncompleted and is something that I am working on the side and it is just the beginning so give it a year and it will be completed. Please tell, am I in … -
Create models from database run time
In my Project we create new Databases dynamically. After the creat (which works fine) we need to create our models schema with inspectdb. I call de following python code. def trigger_after_extract(request): # inspectdb name = request.GET.get('project') command = 'python manage.py inspectdb --database ' + name + ' > api_manager/schemas/' + name + '.py' os.system(command) Now this code doesnt work. I already searched the Internet for some solution but couldnt find one. All I need to do is following: Durring run-time I need to create a model for a new Database with tables which are already created. I know that Inspectdb does exactly what I need but not durring run time is there a solution for the it? -
Model instances without primary key value are unhashable
I need to instantiate several model objects without actually creating them. They need to be added to a set but apparently: TypeError: Model instances without primary key value are unhashable What are my options here? -
How to route subdirectory based on country using Django
I want my Django application to work as a Subdirectory structure for my Subdomains. For example www.example.com/in www.example.com/ae Based on the country code we get, we will change currency & lang. -
How to display the contents of a table as a table in django?
I have made a simple django app. In my models.py I have defined a table- class events(models.Model): id_campaign = models.CharField(default='newevent',max_length=100) status = models.CharField(default='100',max_length=100) name = models.CharField(default='100',max_length=100) This is my views.py - from django.shortcuts import render # Create your views here. from django.views.generic import TemplateView from django.shortcuts import render from website.models import * from website.models import events from django.views.generic import ListView class HomePageView(TemplateView): template_name = 'base.html' class AboutPageView(TemplateView): template_name = 'about.html' class ContactPageView(TemplateView): template_name = 'contact.html' class Success(TemplateView): template_name = 'success.html' def MyView(self, request): query_results = events.objects.all() return render(request, self.template_name) And this is the success.html - {% if user.is_authenticated %} <header> <a href=" {% url 'logout'%}">Logout</a> </header> {% block content %} <h2>you are logged in successfully. this is your personal space.</h2> <table> <tr> <th>id_campaign</th> <th>status</th> <th>name</th> </tr> {% for item in query_results %} <tr> <td>{{ item.id_campaign }}</td> <td>{{ item.status }}</td> <td>{{ item.name }}</td> </tr> {% endfor %} </table> {% endblock %} {% else %} <h2>you are not logged in.</h2> {%endif %} My issue is that once the user logs in he is only able to see the hardcoded column names but the column values are not visible. It is as if the {% for item in query_results %}. part is not … -
How it is possible to create a billing record for a customer with woocommerce api
I can not post my information concerning a particular customer from my django app to my woocommerce site. The procedure that i am following is taking the information about billing from a form and then calling a function doing the post through the api to my site. I noticed that the billing information did not stored at all. Do you know if this behavior has to do with the syntax of the api? Do you know if I have to define the id of the customer in the posting command? my code: def create_woocommerce_client_billing_individually(wcapi,wholesale_client_id,first_name,last_name,company,address_1,address_2,city,state,postcode,country,email,phone): print(wholesale_client_id) fetched_billing=Woo_Customer_Billing.objects.get(client_id=wholesale_client_id,email=email) data = { "first_name": fetched_billing.first_name, "last_name": fetched_billing.last_name, "company": fetched_billing.company, "address_1": fetched_billing.address_1, "address_2": fetched_billing.address_2, "city": fetched_billing.city, "state": fetched_billing.state, "postcode": fetched_billing.postcode, "country": fetched_billing.country, "email": fetched_billing.email, "phone": fetched_billing.phone, } wcapi.post("customers", data).json() -
Best Way to Perform Addition and Multiplication on Django Fields
I have a model 'Manifests' and a form 'CreateManifestForm'. The user enters multiple lines of data in the CreateManifestForm and these are saved to the Manifest model (on a line by line basis, not using ajax or anything). There are 3 fields of concern in the model and form - 'Cases', 'FOB', 'CNF'. Both FOB and CNF are dollar amounts, so I'll use one as an example. How could I take the user entered FOB price, multiply it by cases and then store that number? Additionally, when the user enters another line, how could I do the same and then add that to the original number so I can get a total value. MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() product_name = models.ForeignKey(Products, default=None, blank=True, null=True) count = models.IntegerField() CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) def __str__(self): return self.description VIEWS.PY def add_manifest(request, reference_id): form = CreateManifestForm(request.POST or None) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) instance.reference = order except Orders.DoesNotExist: pass instance.save() form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return …