Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django one model for two model form
i am newbie on Django. I have one model.Two forms where different url. I have two different table on my database when i fill forms. I want to one table on the database. What can i do? Here is my forms; class customerForm(forms.ModelForm): class Meta: model = customerInfoModel fields = ( "customerName", ) class addCustomerForm(forms.ModelForm): class Meta: model = customerInfoModel fields = ( "user", "passwd", ) And here is my model; class customerInfoModel(models.Model): customerName = models.CharField(max_length = 100) user = models.CharField(max_length = 50) passwd = models.CharField(max_length = 20) -
How to upload form data with image file to django model using ajax
I want to upload image file with some other data to django database using ajax. But every time i am doing this by using formData.But formData is always empty when debugging.And my serializer not validating.Please help me to resolve this problem.is there any other way to send image file to server. function add_bike_model(btn){ debugger; var data=new FormData() data.append('image',$("#bike_model_name")[0].files[0]) // BikeModels = document.getElementById('bike_model_name').value; // var e = document.getElementById("city_drop"); // var strUser = e.options[e.selectedIndex].value; // image = document.getElementById('img_file').value; // e.preventDefault(); // var data = new FormData($('#form').closest('form')[0]); console.log('hello') data = {"CityForCars":strUser, "BikeModels": BikeModels, 'Image':image} $.ajax({ type: 'POST', enctype: 'multipart/form-data', processData: false, contentType: false, cache: false, url: baseUrl + "/bike_model/", data:new FormData($("#moment-pane-upload-form")[0]), success: function(data) { console.log('sucessfully done') console.log(data) window.location.href = baseUrl + "/bike_model/"; } }); } <form name="add_model_form" id="add_model_form" enctype="multipart/form-data" class="comon-form" method="post"> <h3>ADD BIKE MODELS</h3> <div class="col-md-6"> <div class="avatar-upload"> <div class="avatar-preview"> <div id="imagePreview" style="background-image: url(/static/Chatbot_Dashboard/img/logo/logo.png);"></div> <img id="bike_image" src=""> </div> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>Bike Model Name <em>*</em></label> <input class="form-control" placeholder="" type="name" id="bike_model_name" required=""> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>City <em>*</em></label> <select style="width: 100%; background: #fff; padding: 7px;" id="city_drop"> <option value="" selected="selected">Select City</option> {% for city in city.car_city %} <option value="{{city.id}}">{{city.CityForCars}}</option> {% endfor %} </select> </div> </div> <div class="col-md-6"> <div class="form-group-inner"> <label>Bike … -
Django background task - schedule integrity error
I am trying to use the schedule decorator to schedule a background task using django-background-tasks module. However, when i run this particular piece of code, it shows the following error. Code: @background(schedule=1) def function(s,id): return some_return_value Error: IntegrityError at url null value in column "repeat" violates not-null constraint DETAIL: Failing row contains (169, function, [["s", 57], {}], a24y78123j1b23j1321232aebc9762c0fa2, null, 0, 2018-11-21 07:29:28.99142+00, null, null, null, 0, null, , null, null, null, null). The error is in the background_task table(repeat column) but I am not sure why this pops up. Yes, I understand that it tries to insert a null value in a not null column, but I have never got such an error while using background task before. -
Django send context data from template to view (request.post)
I have a page with forms which is filled out by the user. In this page there is a check box, if the checkbox is valid, I need to execute a method and to display result of action, but after that in this page a post the inquiry is cleaned as it is possible to add data from a template to a post inquiry template -> view -> if checkbox true -> show new page with result -> then save all data from 1st page template (request.POST is empty) how i can add template data (context) to request.POST def add_data(request): # takes data from template if request.method == "POST": #checkbox checking interpolation_method = request.POST.get("interpolation_method",default=None) if interpolation_method: # this method work with data from template forms data = Interpolation(data, interpolation_method) context = { 'd' :data, } return render(request,'data/interpolation.html',context) than i show our next page with the processed data def int_data(request): # Our next view to get user desicion from second template page if request.method == "POST": #request.POST is empty return JsonResponse(request.POST) how i can add context data (from view 1) to request.POST -
Set specific group of Django user as celery worker
I need to make a specific group of Django user(group : delivery person) as celery worker. Whenever any registered django user from that specific group logs in, they can pick task from the celery queue and complete. As soon as one user completes a task, it must be dequeued from the queue and asynchronously it should not be visible to the next logged in user from that group. -
How to make form with checkbox in Django to select the list of items?
I am trying to make a form which consists list of foods with name, price and quantity. From which I can select the multiple items using check box and can submit after selecting. And also how can I display the selected items on the admin page along with name that has been submitted previously in loginform. Please give the full explanation. -
Django login with custom form template
I'm using the Django authentication with my login form in my template, after i pressed the login button on the form the page refresh but doesn't log me in and doesn't show the {{context}} error in the template. My view: > def login_view(request): > if request.method == 'POST': > all_categories = Categories.objects.all() > all_websites = Website.objects.all() > all_discounts = Discount.objects.order_by('-id') > username = request.POST.get('username') > password = request.POST.get('password') > user = authenticate(request, username=username, password=password) > if user is not None: > login(request, user) > return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts) > else: > context = 'wrong username or password' > all_categories = Categories.objects.all() > all_websites = Website.objects.all() > all_discounts = Discount.objects.order_by('-id') > return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts,context=context) My form (header.html) <div class="col-md-3 top-info-cart text-right mt-lg-4"> {% if user.is_authenticated %} <p>Welcome, {{ user.username }}.</p> <p><a href="{% url 'frontend:logout' %}">logout</a></p> {% else %} <ul class="cart-inner-info"> <li class="button-log"> <a class="btn-open" href="#"> <span class="fa fa-user" aria-hidden="true"></span> </a> </li> </ul> <p>{{context}}</p> {% endif %} <!----> <div class="overlay-login text-left"> <button type="button" class="overlay-close1"> <i class="fa fa-times" aria-hidden="true"></i> </button> <div class="wrap"> <h5 class="text-center mb-4">Login Now</h5> <div class="login p-5 bg-dark mx-auto mw-100"> <form action="{% url 'frontend:login' %}" method="post"> {% csrf_token %} <div class="form-group"> <label class="mb-2">User name</label> <input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll … -
Celery connecting to rabbitmq-server instead of redis-server
I have a Django application which I want to configure it celery to run background tasks. Packages: celery==4.2.1 Django==2.1.3 Python==3.5 Configuration of celery in settings.py file is: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'app.tasks.task_number_one', 'schedule': crontab(minute='*/1'), }, } And celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.prod') app = Celery('niftytrader_temp') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When I run : celery -A niftytrader_temp worker -l info -B -E It points to rabmmitmq server, instead it should point to redis-server, shown below: -------------- celery@user-desktop v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-39-generic-x86_64-with-Ubuntu-18.04-bionic 2018-11-21 12:04:51 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: project:0x7f8b80f78d30 - ** ---------- .> … -
What is the proper way to process the user-trigger events in Django?
For example, I have a blog based on Django and I already have several functions for users: login、edit_profile、share. But now I need to implement a mission system. User logins, reward 10 score per day User completes his profile, reward 20 score User shares my blogs, reward 30 score I don't want to mix reward code with normal functions code. So I decide to use message queue. Pseudo code may look like: @login_required def edit_profile(request): user = request.user nickname = ... desc = ... user.save(...) action.send(sender='edit_profile', payload={'user_id': user.id}) return Response(...) And the reward can subscribe this action @receiver('edit_profile') def edit_profile_reward(payload): user_id = payload['user_id'] user = User.objects.get(id=user_id) mission, created = Mission.objects.get_or_create(user=user, type='complete_profile') if created: user.score += 20 user.save() But I don't know if this is the right way. If so, what message queue should I use? django-channel / django-q or something else? If not, what is the best practice? -
How Count() woks?
In the book that I am, reading so as to count the number of tags in common between multiple posts the Count from django.db.models is used. For tags the taggit is used. But I am quite confused how this functionality is working post_tags_ids = post.tags.values_list('id', flat=True) similar_posts =Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4] In my case, I have several posts and each has two tags. Each post shares only one tag with other posts. I am getting the list of the ids of the tags that the post that I am interested in contains. Then according to that list, I am filtering out other posts. Then I am adding same_tags parameter for all the posts, counting the tags they have. My confusion is here, as I said I have two tags in each post but magicaly here same_tag is counting one which is the number of tags that post shares with the post of my interest. How this is happening? Here is my test in the shell >>> posts [<Post: This is the other one >, <Post: Some content >, <Post: Other Post>,<Post: Temurs learning curv>] >>> post = Post.objects.get(pk=1) >>> post_tags_ids = post.tags.values_list('id', flat=True) >>> post_tags_ids [2, 3] similar_posts = … -
how to stop routers from creating unwanted urls in Django RestFrameWork
I am using DefaultRouters in my project for creating urls. my question is how can i prevent routers from creating some urls for certain urls. eg: i have a url 127.0.0.1:8000/api/users/ which returns a list view, but at the same time router is also creating urls like 127.0.0.1:8000/api/users\.(?P<format>[a-z0-9]+)/?$ which i do not want to be there. here is my files views.py class UserAuthAPIView(ModelViewSet): queryset = UserModel.objects.all() serializer_class = ListViewSerializer urls.py from rest_framework_mongoengine import routers as merouters from UserAPI.api.views import UserAuthAPIView #UpdatePasswordSerializer merouter = merouters.DefaultRouter() merouter.register(r'users', UserAuthAPIView, base_name='user') urlpatterns = [] urlpatterns += merouter.urls -
django docker-compose deleting data from mongo database when i am doing "docker-compose down" and again"up"
DockerFile: FROM python:3.6 WORKDIR /usr/src/jobsterapi COPY ./ ./ RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose.yml version: "3" services: jobster_api: container_name: jobster build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: "bash -c 'python src/manage.py makemigrations --no-input && python src/manage.py migrate --no-input && python src/manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/jobster_api environment: REDIS_URI: redis://redis:6379 MONGO_URI: mongodb://jobster:27017 ports: - "8000:8000" volumes: - ./:/usr/src/jobster_api links: - redis - elasticsearch - mongo #redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.5.0 ports: - "9200:9200" - "9300:9300" mongo: image: mongo ports: - "27017:27017" I have done setup django with mongodb inside docker using following docker-compose command. it is working fine every thing. but when i am adding any records using "docker exec -it 'img id' /bin/bash" it is inserting data(i tried creating superuser for django admin panel). but, when i am again making it "docker-compose up" after "docker-compose down" it is deleting all data from database showing empty records. so i am not able to access admin panel also for next timeself. Please have a look......... -
How can I use aggregate sum with division?
I want to get average of the total within the past 3 months. I have an object called 'Book' and attribute 'total'. I need to sum up the total and divide by 3 to get the avg for one month. Here is my code: past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')) I have tried: past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3) It return error: File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate 360. arg.default_alias During handling of the above exception ('CombinedExpression' object has no attribute 'default_alias'), another exception occurred: File "C:\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\customers\views.py" in Summary 222. past_3_month_avg = Book..objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3) File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate 362. raise TypeError("Complex aggregates require an alias") Exception Type: TypeError at /summary/ Exception Value: Complex aggregates require an alias -
which more on security; MySQL or PostgreSQL [on hold]
Hi I'm new to web programming, and I'm working on a website with Django web framework. But now I want to switch my SQLite database out and replace with either MySQL or PostgreSQL, I been googling on both database management language and seems to work well on Django but, the important is security; which language less secure??? -
If-statement too nested?
I use the following code to check if the ticket should contain a discount or not. There are now three if-statements and I wonder if there is a better way to not make it less nested? ticket_price = current_ticket.display_price discount_code_session = request.session.get(request.event.discount_code_cookie(), None) if discount_code_session: discount_code = Discount.objects.filter( code=discount_code_session, event=request.event.pk ).first() # Make sure discount_code exists if discount_code: discounted_tickets = discount_code.tickets.all() # Why not discounted_tickets: If discounted_tickets empty, then the # discount code is valid for all tickets. if not discounted_tickets or current_ticket in discounted_tickets: discounted_price, original_price = ( discount_code.calculate_discounted_value(ticket_price) ) ticket_price_dict = { 'original_price': original_price, 'discounted_price': discounted_price, } return ticket_price_dict return ticket_price -
Django Resize image in Forms
I'm using python 3.6 and Django 2.0. I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload. avatar = models.ImageField(path_and_rename, max_length=255, blank=True I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error. 'Image' object has no attribute '_committed' How can I resize my square image to meet the new dimensions that I need. My code (leaving out validation to make it simpler): forms.py def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: print(len(avatar)) w, h = get_image_dimensions(avatar) max_width = max_height = 750 image = Image.open(avatar) resized_image = image.resize((max_width,max_height), Image.ANTIALIAS) print(type(avatar)) print(type(image)) print(type(resized_image)) return resized_image except ... the output of the above is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> <class 'PIL.JpegImagePlugin.JpegImageFile'> <class 'PIL.Image.Image'> if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar? Full error message: File "C:\myapp\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 126. … -
Creating another virtualenv for a new Django project
I'm learning Django and Python. If it is right that I understood, I need to create a new virtualenv per Django project. python django: create a new virtualenv for each django project? I installed virtualenv when I was following a Django tutorial before. I want to create an application to practice. so I'm trying to install a new virtualenv. However powershell shows me this. virtualenv installation error? How can I install another virtualenv in this case? could you please give me an advice or link to solve this problem. Thank you. -
How to attach graph-tool to Django using Docker
I need to use some graph-tool calculations in my Django project. So I started with docker pull tiagopeixoto/graph-tool and then added it to my Docker-compose file: services: version: '3' services: db: image: postgres graph-tool: build: . image: dcagatay/graph-tool web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - graph-tool When I up my docker-compose I got a line: project_graph-tool_1_87e2d144b651 exited with code 0 And finally when my Django projects starts I can not import modules from graph-tool, like: from graph_tool.all import * If I try work directly in this docker image using: docker run -it -u user -w /home/user tiagopeixoto/graph-tool ipython everything goes fine. What am I doing wrong and how can I fix it and finally attach graph-tool to Django? Thanks! -
Paypal sandbox ipn subscription bug
I am implementing subscription with Paypal IPN and Django. The transaction process was fine till 11/16/2018 around 3PM. After that, the transaction history on Paypal customer account went buggy. I tried to pay $1 to subscribe twice but no records is shown on the following page. enter image description here However, if I go to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_manage-paylist, I can see those records. And the facilitator account also has the similar issue, no records show up on the history on the main page but those records can be seen on the subscription management page. I used two accounts to test it. Same issue. Any idea what is going on? -
Django: required field even with true=blank on form submision
I've a form that has a field 'instrucciones' that should be optional to complete. I've tried to modified it in the model and put it as a blank field, null true, and even use a default (''). instrucciones = models.CharField(max_length=200, blank=True, null=True, default='') However, in submition I'm ask to complete this field. Why? class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = (('50', '50',), ('100', '100',), ('150', '150',)) # usuario = models.ForeignKey(User, on_delete=models.DO_NOTHING) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) imagenes = models.FileField(upload_to='imagenes/', null=True) instrucciones = models.CharField(max_length=200, blank=True, null=True, default='') # uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tamanios forms.py # Declare Forms class StepOneForm(forms.Form): tamanios = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño') cantidades = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') class StepThreeForm(forms.ModelForm): instrucciones = forms.CharField(widget=forms.Textarea) class Meta: model = TamaniosCantidades fields = ('imagenes', 'instrucciones') html: {% csrf_token %} <div class="form-group"> {{ form.imagenes|as_crispy_field }} <div id="instrucciones-adicionales" style="display: none"> <p class="bold-font"> Instrucciones adicionales (opcional):</p> {{ form.instrucciones|as_crispy_field }} </div> </div> </br> </br> <p>O, sáltate este paso y envía tu arte por correo electrónico</p> <button type="submit" class="btn btn-naranja text-white btn-block">Continuar </button> </form> -
Access to the camera from the system the application is running on
I am building a web application with django and opencv for computer vision. In the web application there exists a button which when pressed starts the web cam of my computer. The problem is when i host the web application using my IP and access the application with a different computer and press the button, The webcam in my computer start. I knew the problem lied in this line of code cam = cv2.VideoCapture(0) I looked online and found this post , which asks me to use javascript to access the webcam. Is that the best option available or can I somehow change that line of opencv code to access the camera in the system the application is running on? If there is no better way to do it than javascript, then I would also like to know once I access the webcam and display the feed onto the screen, how do I link the rest of the python code like the face detectors and classifiers to the javascript code? I have just started getting my hands dirty with python and i still have a lot to learn. Thanks in advance -
PLC to Server to Web
First, thank you for reading this second, I'm a new to all this as i'm fresh out colleges and I'm tasked with developing this project that allows, a plc to read the input (analogue data) at the factory and send its data to the server(A PC) by wireless, at the factory. The Server will then upload the data onto a webpage; where it can be view anywhere, mobile or computer. Now questions how do I let server read plc data and upload to the webpage in real time? I'm using MITSUBISHI PLC FX3G-14MR/ES-A and The website I'm doing is a Django framework/python The Server Database I'm considering between this three: PostgreSQL MySQL MongoDB But which more scalable and had strong security Are there tips, any recommendations? or website where I can start? -
Filtering Django Queryset Based on Presence of String
I have a model which renders a json file in views.py: def bill_sum(request): data = Summary.objects.values('title','summary','summary_text') return render(request,'billsummary.html',context={'data':data}) Is it possible to filter the summary_text object query by looking up a specific string which I would pass in from urls.py? Something like using from django.db.models import Q Summary.objects.values('title;'summary',Q('summary_text'__contains=someword),...) -
How to send email with django "Rest Framwork"?
I'm using small Rest api project and it works fantastic. But somehow i have to make send email function in there. so i added email config in settings.py like that // settings.py # SMTP Mail service with decouple EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = config('EM_ACCOUNT') EMAIL_HOST_PASSWORD = config('EM_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER //views.py from rest_framework import viewsets from consult.models import Consult from consult.serializers import ConsultSerializer from django.core.mail import EmailMessage class ConsultViewSet(viewsets.ModelViewSet): queryset = Consult.objects.all() serializer_class = ConsultSerializer def send_email(request): email = EmailMessage( 'Title', (ConsultSerializer.name, ConsultSerializer.email, ConsultSerializer.phone), 'my-email', ['my-receive-email'] ) email.attach_file(ConsultSerializer.file) email.send() // models.py from django.db import models # Create your models here. class Consult(models.Model): name = models.CharField(max_length=16) position = models.CharField(max_length=16, null=True) group = models.CharField(max_length=50) email = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=14) describe = models.TextField(blank=True, null=True) file = models.FileField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Consult' // serializers.py from rest_framework import serializers from .models import Consult class ConsultSerializer(serializers.ModelSerializer): class Meta: model = Consult fields = ('id', 'name', 'position', 'group', 'email', 'phone', 'describe', 'file', 'create_date') Yup. that is all of my codes. And i setted send_mail function in views. Honestly I want automatic send mail function when the consult data … -
Changing a form field's 'required' property with save_model in Django admin
I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can get this to work properly. So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required. It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help! admin.py class UserAdmin(admin.ModelAdmin): model = Order form = UserForm def save_model(self, request, obj, form, change): if obj.pickup_only == 1: form.fields['address'].required = False form.fields['city'].required = False form.fields['state'].required = False form.fields['zipcode'].required = False return super(UserAdmin, self).save_model(request, obj, form, change)