Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to implement Pyrebase on my Django Project but somehow I get an error when I try to login the user
Here is the complete Traceback [16/Jan/2018 11:43:13] "GET /login/ HTTP/1.1" 200 2019 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\edit.py", line 182, in post if form.is_valid(): File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 183, in is_valid return self.is_bound and not self.errors File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 385, in full_clean self._clean_form() File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 412, in _clean_form cleaned_data = self.clean() File "C:\Users\CLAIRE\Desktop\Thesis\finalThesis\well\now\accounts\forms.py", line 130, in clean login(request, user) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\contrib\auth__init__.py", line 154, in login request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'dict' object has no attribute '_meta' [16/Jan/2018 11:43:26] "POST /login/ HTTP/1.1" 500 105312 forms.py from django import forms from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from profileacc.models import DocProfile import pyrebase User = get_user_model() config = { 'apiKey': "AIzaSyB0bEes5zKUjJqiOL7YWtJ0RdtFbhqqDBM", 'authDomain': "chartsdjango.firebaseapp.com", 'databaseURL': "https://chartsdjango.firebaseio.com", 'projectId': "chartsdjango", 'storageBucket': "chartsdjango.appspot.com", 'messagingSenderId': "176923102759" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all … -
Django rest framework integrate 2 different django project API
I have 2 different django project. Django 1 is a social medical app which is for user with their medical information. Django 2 is a doctor app which is for the doctor and staff who will prescription details to patient who visited them. So i have these task. Integration of django 1 api and django 2 api, on django api method on django 1 api, code to POST BookAppt Integration of django 1 api and django 2 api, on django api method on django 2 apiI, code to GET BookAppt Integration of django 1 api and django 2 api, on django api method, connect to another API From my understanding, django 1 will post to django 2 BookAppt API. But how do i integrate these 2 app together so that i can post from django project 1 into django project 2 ? Is it possible to give an example ? As i cant find any link which helps me for these situation. -
Django: Server Error (500) when Debug is False
I'm trying to configure my Django app for production. When I set Debug to False I get "Server Error(500)" When I set debug to true, I get this error instead TemplateSyntaxError at /beginners/ Invalid block tag on line 11: ''style.css''. Did you forget to register or load this tag? Things I've tried: manage.py collectstatic && y Relevant code snippets: STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = ( os.path.join('static'), ) SECRET_KEY = os.environ.get('SECRET_KEY', "default_value") BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['*'] [installed_apps] 'django.contrib.staticfiles', I think it's because it cannot locate my static folder, since that is the error I get when debug is true -
Automatic retrying after deadlock in django and mysql setup causes duplicate entry
I'm using solution from Hook available for automatic retry after deadlock in django and mysql setup to handle deadlocks, I thought in case of deadlock exception, the corresponding SQL operation should fail, not changing the status of data in the database. But it seems I was wrong. When I insert some data into a table with unique restrictions, the first try failed because of deadlock, And then execute_wrapper retried automatically, which failed with IntegrityError (1062, "Duplicate entry '96-1160' for key 'xxxxxxxxxxxxx_id_4714853c_uniq'") exception. Can anybody tell me why the first try still changed the data in case of deadlock exception? And any suggestions on how to handle it? Thanks! The execcute_wrapper code listed as below: original = django.db.backends.utils.CursorWrapper.execute def execute_wrapper(*args, **kwargs): attempts = 0 while True: try: return original(*args, **kwargs) except OperationalError as e: code = e.args[0] if attempts == 10 or code != 1213: raise e attempts += 1 time.sleep(0.3) django.db.backends.utils.CursorWrapper.execute = execute_wrapper Thanks! -
Distributed or Central Authorisation in Django Microservices
I'm building a Django rest framework based service which has some complicated permissions. So far, my microservices stack looks like this: /auth/ JWT authentication service /users/ - adding users, adding them to different services /new-service/ - needs authorization Users database is shared by auth and users read-only, and read/write respectively. new-service has no access to this database but the challenges consist of: user can be in multiple groups specific to that service user could have read-only access to one item in one of the groups user could be allowed to create new users with access to one of the groups users have different roles in the service, but we still need to allow for access like the read-only one listed Groups are used not to manage users, but to provide access to things. Like GitLab groups provide access to GitLab projects. If I put all the permissions in the users service, my new service has to talk to that one and it will get chatty. It seems like there has to be a data divide, but I'm not sure exactly where to put it. Conversely, should the django-rest-framework service even have a shadow entry of the user account in it's … -
Django Form Not Posting to SQL
I have a page where an item from a list nested within my form can be favorited, it redirects back to the same page following what should be an update to the database, then it shows a star next to the item. While this should work fine my form doesn't change the DB at all. I am confident it is not the html rendering since when I manually change the field in the admin panel it renders fine. What is causing this to not post? view.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import Album, Song # Create your views here. def index(request): all_albums = Album.objects.all() template = loader.get_template('music/index.html') context = {'all_albums' : all_albums,} return render(request, 'music/index.html', context) def detail(request, album_id): album = get_object_or_404(Album, pk=album_id) return render(request, 'music/detail.html', {'album' : album}) def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) print("favorite stuff happens here") try: selected_song = album.song_set.get(pk=int(request.POST['song'])) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album' : album, 'error_message': 'Did not select a valid song' }) else: selected_song.favorite = True selected_song.save() return render(request, 'music/detail.html', {'album' : album}) <img src="{{album.album_logo}}"> <h1>{{album.album_title}} </h1> <h2>{{album.artist}} </h2> {% if error_message %} <p><strong> {{error_message}} </strong></p> {% endif %} <form … -
Dropdown Menu Not Working When Implementing with Django
I'm new to working with Django and am running into a problem implementing it into the static site that I've made. Could you please advise as to why the dropdown menu is not working (not dropping down)? It was working fine when it was just the html/css files before django implementation. Attached image shows the file/folder layout - please let me know if you need to see any of the additional files and I can post them. Am thinking I have some css in the wrong directory (?) Image: IMAGE {% load staticfiles %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Test Site"> <meta content="width=device-width, initial-scale=1, user-scalable=no" name="viewport"> <title>Test Site</title> <meta name="description" content="Test Site Web Application"/> <link rel="shortcut icon" href="{% static 'themes/images/favicon.ico' %}"> <!-- Google icon --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Bootstrap css --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}"> <!-- Propeller css --> <!-- build:[href] assets/css/ --> <link rel="stylesheet" href="{% static 'assets/css/propeller.min.css' %}"> <!-- /build --> <!--Propeller date time picker css --> <link rel="stylesheet" href="{% static 'components/datetimepicker/css/bootstrap-datetimepicker.css' %}" /> <link rel="stylesheet" href="{% static 'components/datetimepicker/css/pmd-datetimepicker.css' %}" /> <!-- Propeller theme css--> <link rel="stylesheet" href="{% static 'themes/css/propeller-theme.css' %}" /> <!-- Propeller admin theme css--> <link rel="stylesheet" href="{% static 'themes/css/propeller-admin.css' … -
Use 'pass' return value in another function in python
I am using python 3.5. Function1 is : def boolean_key_validation(dictionary, key): data = {} try: dictionary_value = dictionary[key] except KeyError: pass else: if dictionary_value == 'TRUE': data[key] = True elif dictionary_value == 'FALSE': data[key] = False else: raise ValueError("{} value should be either blank or 'TRUE'/'FALSE' only".format(key)) return data[key] # not able to get the 'do_nothing' value here Function 2 is : def read_file(start_date, end_date, dictionary): read_data = {} files = File.objects.all() # ... # read_data['downloaded'] = boolean_key_validation(dictionary, 'downloaded') read_data['integrity'] = boolean_key_validation(dictionary, 'integrity') read_data['validation'] = boolean_key_validation(dictionary, 'validation') return files.filter(**read_data) I want to filter my model 'File' based on the boolean values of 'downloaded', etc. In function1 what I want is that if key is not present in dictionary this function1 should do nothing and my read_data dictionary in function2 should have no value for that key. I have searched for similar problem but those are using 'pass' in conditional statements within some function. -
Select Element in a Django Form
I am learning the Django framework, and I would like to build all of my forms the "Django way" instead of the old fashioned HTML way. Could someone please show me a simple example of how to build a simple select element within a form.py file? -
NOT NULL constraint failed: with my create function
I'm trying to have one view that produces 2 forms and saves them both with one button. I have a good idea on how to accomplish this in an update view so I'm trying to apply the same logic with a create view. Everything seems to be working ok but I'm getting a NOT NUlL constraint failed error. I realize that this error has something to do with my second form probably not being able to find the "carrier" to attach itself too, I just don't know how to go about solving it. Here's my code: MODELS.PY class Carrier(models.Model): carrier_name = models.CharField(max_length=255, unique=True) mc_number = models.CharField(max_length=10, unique=True, blank=True) dot_number = models.CharField(max_length=15, unique=True, blank=True) carrier_ein = models.CharField(max_length=9, unique=True) carrier_phone = models.CharField(max_length=10) carrier_phone_two = models.CharField(max_length=10, blank=True) carrier_phone_three = models.CharField(max_length=10, blank=True) carrier_fax = models.CharField(max_length=10, blank=True) carrier_email = models.CharField(max_length=50, blank=True) US_STATES_OR_CAN_PROVINCES = ( ('AK', 'Alaska'), ('AL', 'Alabama'), ('AR', 'Arkansas'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DC', 'District of Columbia'), ('DE', 'Delaware'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('IA', 'Iowa'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('MA', 'Massachusetts'), ('MD', 'Maryland'), ('ME', 'Maine'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MO', 'Missouri'), ('MP', 'Northern Mariana Islands'), … -
Edit image in Django not working
I have created a application form with photo. I have used imagefield for photo. The photo is saved properly in create form and displayed back in the template. The image is not seen in the edit form application. profile=get_object_or_404(Profile, id=pk) form=ProfileForm(request.POST or None, request.FILES or None, instance=profile) form2=EducationForm(request.POST or None, instance=profile.education) form3 = FamilyForm(request.POST or None, instance=profile.family) form4 = OtherForm(request.POST or None, instance=profile.other) if request.method == "POST": if form.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid(): profile = form.save(commit=False) for language in request.POST.getlist('languages'): profile.languages.add(language) profile.save() education = form2.save(commit=False) education.profile = profile education.save() family = form3.save(commit=False) family.profile = profile family.save() other = form4.save(commit=False) other.profile = profile other.save() messages.add_message(request, messages.SUCCESS, 'Sucessfully Updated Profile') return HttpResponseRedirect(reverse('vived:index')) -
Using instance attributes conditionally determine ModelAdmin inlines? (Django 2.0)
Context: I am writing an app for distributing company policies to users, for them to read and take a test if the policy mandates they do so. The Policy model includes a 'quiz_required' boolean which I would like to use to determine whether the QuizInLine should be included in the inlines of the PolicyAdmin instance. Similar feeds on this issue advise overriding the get_inline_instances and get_form_sets however this produces a Validation Error: ManagementForm data missing error while formset validation. If anyone knows an optimum way of achieving this aim I would be very grateful for the help. Thanks you. models.py class Policy(models.Model): title = models.CharField(max_length = 100)`enter code here` policy = RichTextField() requires_quiz = models.BooleanField('Quiz', default=False) admin.py class QuizInLine(admin.StackedInline): model = Quiz class PolicyAdmin(admin.ModelAdmin): model = Policy fieldsets = [ ('Policy', {'fields': ['title','policy','requires_quiz',]}), ] inlines = [] quiz_inlines = [QuizInLine,] def get_inline_instances(self, request, obj=None): inline_instances = [] if obj.requires_quiz: inlines = self.quiz_inlines else: inlines = self.inlines for inline_class in inlines: inline = inline_class(self.model, self.admin_site) if request: if not (inline.has_add_permission(request) or inline.has_change_permission(request) or inline.has_delete_permission(request)): continue if not inline.has_add_permission(request): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_formsets(self, request, obj=None): for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj) -
django-admin: change column font to red when if condition is true
I have a vlog that I can preload vlog entries into the db, so that when the date of vlog-published-date is less than the models field of now, the vlog entry will be automatically displayed / published. How can I make the django-admin column of Vlog Date Published font red when the date of the vlog_published_date is greater than now (not yet published)? Here is a visual example of what I mean where the now date is January 16, 2018: Here is my vlog models.py code: class VlogDetails(models.Model): .... vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.') .... class Meta: .... There is this similar thread, but the thread is 7+ years old and I was hoping there was information more current to django 1.10 and python 3.5. -
Django, GDAL and CircleCI 2
I have a Django app configured with GeoDjango that is failing on CircleCI 2.0 builds with the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library. Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. However, when I remove 'django.contrib.gis' from DJANGO_APPS in settings.py the build runs successfully. Are there additional steps for configuring GDAL in CircleCI outside of the postgres and GDAL docker images? I (perhaps incorrectly) assumed that GDAL would be found after the docker image was installed. Below is my config.yml: version: 2 jobs: build: docker: - image: circleci/python:3.6.3 - image: circleci/postgres:10.1-postgis environment: - POSTGRES_USER=ubuntu - POSTGRES_DB=myapp_test - image: geodata/gdal working_directory: ~/repo steps: - checkout # Download and cache dependencies - restore_cache: keys: - v1-dependencies-{{ checksum "requirements.txt" }} # fallback to using the latest cache if no exact match is found - v1-dependencies- - run: name: install dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: paths: - ./venv key: v1-dependencies-{{ checksum "requirements.txt" }} - run: name: run tests command: | . venv/bin/activate python manage.py test environment: DATABASE_URL: "postgres://ubuntu@localhost:5432/myapp_test" - store_artifacts: path: test-reports destination: test-reports -
Using Django Model form with ManyToMany relationship fields
I'm new to development. I have three tables. Table A and Table B have a OneToMany relationship. Where A can have many B's but a B can only have one A. The data from Table A and Table B are already synced. Their relationship table has all the data it needs. Table A and Table B both have a ManyToMany relationship with Table C. I need a form that will link the information in Table C to Tables A and B. I need a form that includes all three tables in a scroll down format. The user would pick an option on table A, depending on their choice on Table A they will get choices on Table B and then all the options in Table C would show up independent of choices A and B. Once the users pick what they want from each scroll down I want the users to be able to submit the form. Once submitted, I need the form to POST relationships, so that it fills the TableA_TableC and TableB_TableC tables in the database. Later on I'll be able to query all the items that Table A has related to Table C, and the items that … -
How to Iterate over four arrays one by one and printing them in django template?
I am going to print four array values simultaneously in django template . like this the four arrays are of equal length ,they are header_list , domain_list , domain_data , dom for i in range(10): print headerlist[i] print domain_list[i] print domain_data[i] print dom[i] how to acheive these in django template . -
Different field values for each user
I have this model: class Product(models.Model): art_name = models.CharField(max_length=100) plu_num = models.IntegerField(default=0, unique=True) sales_price_brutto = models.FloatField(null=True) sales_price_netto = models.FloatField(null=True) last_price = models.FloatField(null=True) purchase_price_brutto = models.FloatField(null=True) purchase_price_netto = models.FloatField(null=True) entry_date = models.DateField() margin = models.FloatField(null=True) stock = models.IntegerField(default=0) I created for example two user groups. Then I want to each group of users have different values in stock and sales_price_brutto (save method of model calculate rest of the fields values depending on sales_price_brutto and purchase_price_brutto). I tried adding one more field: owner = models.ForeignKey(Group, editable=False) But it seems to not work as I want. I don't really know if there is a way to do that. -
How can I escape underscores in Django's field lookups?
By default, Django cannot support trailing underscores in field names because it messes up field lookups. Unfortunately, I've found myself in a situation where the Postgres table was created without using Django and now I have to do the following: queryset = queryset.filter(**{field + '__icontains': value}) This field could have an underscore. How do I tell Django to ignore the first of the triple underscores and find the field? It clearly knows about the field because it shows it as an option in the error: django.core.exceptions.FieldError: Cannot resolve keyword 'ccc' into field. Choices are: _bbb, aa_a, ccc_ But I have not found any way to force filter to do what I want. Is there a syntax that let's me explicitly specify field name and lookup? -
Django queryset filter max values for list
I'm wondering if there is any way to pass a list to a django queryset and limit to the max/min/latest/oldest value for each item in the list. Basically something like this: serial_list = [2231, 2232, 2233] data_queryset = Data.objects.filter(serial__in=serial_list).latest() I'm fully aware that the above code doesn't work. I'm just trying to illustrate a queryset that would return the .latest() value for each object where the serial is in serial_list. -
Stacked in django2.0 tutorial / why "from . " is needed to import views?
I just start learning Python3.x from scratch. in the tutorial of django 2.0, I stacked with this question. please help me to solve the problem. as a module, following code is work [directory] mydir | +-test.py +-test2.py ====================== [test.py] import test2 test2.say() ====================== [test2.py] def say(): print("hey") but in django tutorial_01, (https://docs.djangoproject.com/en/2.0/intro/tutorial01/) [directry] polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py ====================== [poll/urls.py] from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] import command does not work without "from .", even views.py exist in the same directory. Error message says "ModuleNotFoundError: No module named 'views'" could you explain why this kind Error is occurred ? Thank you in advance! -
Custom Django login form middleware
I'm looking at a solution of implementing a modal pop-up login form to be used site wide in the navigation bar. I'm working with Django 1.11. Now, I'm defining a LoginFormMiddleware class as follows: middleware.py from django.http import HttpResponseRedirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm class LoginFormMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): from django.contrib.auth.forms import AuthenticationForm if request.method == 'POST' and request.POST.has_key('base-account') and request.POST['base-account'] == 'Login': form = AuthenticationForm(data=request.POST, prefix="login") if form.is_valid(): from django.contrib.auth import login login(request, form.get_user()) request.method = 'GET' else: form = AuthenticationForm(request, prefix="login") request.login_form = form This is all included in the standard way in settings.py in MIDDLEWARE = []. I also have 'django.template.context_processors.request' defined in TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ *** ] } ] as I should. Using {{ request.login_form }} in my templates as follows: <div class="container"> {{ request.login_form }} </div> Yet nothing is being rendered - where it should? From browser inspector tools: Can anyone advise me on what I am missing please? -
TypeError: url() got an unexpected keyword argument 'name_space'
I know it looks like a simple problem but I'm still too new for sorting it out myself, so : learing_log/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', 'learning_logs.urls',name_space='learning_logs'), ] Previously I had the following error so I've removed the include function ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. learing_logs/urls.py """Defines URL patterns for learning_logs.""" from django.conf.urls import url from . import views urlpatterns=[ #Homepage url(r'^$',views.index,name='index'), ] views.py from django.shortcuts import render #Create your views here. def index(request): """The home page for Learning Log""" return render(request,'learning_logs/index.html') Im using Django 2.0 and Python 3.6.1 Could you please advice why I'm getting TypeError with name_space arg, is that related to Django version, many thanks in advance. -
django The form does not show on the page
The form does not show on the page what is the problem I tried a lot but there was difficulty comment.html: <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> views.py : def post_detail_view(request,year, month, day, post): post = get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) context ={ 'post':post } return render(request,'post/comment.html',context) comments = post.comments.filter(active=True) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = post new_comment.save() else: form = CommentForm() return render(request,'post/comment.html',{'post':post, 'comments': comments, 'form':form}) The form does not show on the page what is the problem I tried a lot but there was difficulty forms.py : from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name','email','body','website',) models.py : class Comment(models.Model): post= models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) name = models.CharField(max_length=80) website = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering =('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name,self.post) The form does not show on the page what is the problem I tried a lot but there was difficulty urls: from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$',PostListView.as_view(),name='blog'), url(r'^$',views.post_list_view,name='post_list_view'), #url(r'^(?P<pk>\d+)/$',PostDetailView.as_view(),name='post_detail'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',views.post_detail_view,name="post_detail_view"), ] The … -
Django: automatically assigning foreign key in CBV form
This builds on: Django automatically set foreign key in form (with class based views). The answer there seems like it would work but Django throws a ValueError I have (2) models: Product and Procedure that are related by a foreign key. I want to have a link from the Product page to add the Procedure, and have the product FK (via its pk) automatically passed to the form. There are several thousand products, so selecting the FK manually from a dropdown isn't feasible. class ProductBase(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) name = models.CharField(max_length=128,null=False) class ProcedureText(models.Model): id_procedure = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False) text_procedure = models.TextField() parent_product = models.ForeignKey(ProductBase,on_delete=models.CASCADE') I have a link from the Product details page to call a CreateView: <a class='btn btn-success' href="{% url 'products:addprocedure' pk=product_details.pk %}">Add Procedure</a> which is mapped through urls.py: path('addprocedure <pk>',views.AddProcedureView.as_view(),name='addprocedure'), class AddProcedureView(CreateView): form_class = AddProcedureForm template_name = 'addprocedure.html' model = ProcedureText #fields = ('__all__') def form_valid(self, form): form.instance.parent_recipe = self.kwargs.get('pk') return super(AddProcedureView, self).form_valid(form) calling in forms.py class AddProcedureForm(forms.ModelForm): class Meta: model = ProcedureText fields = ('__all__') and templating out to a standard form: <form class="form-horizontal" action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </form> Whenever the form is submitted, Django returns a ValueError of … -
django return edited form validation data from 'clean'
Python 3.x Django 2.x Hi, I have an address form. I am aware of the clean_<field> methods and the clean method. I am doing some per-field validation and that is all working. I want to validate/normalize the address information and am doing that in clean. I am in the US and my use case fits in the USPS address API (I think). In any case, I can build the USPS XML query structure from the cleaned_data dict. I can make the API call and receive the possibly reformatted XML API result. I can harvest the possibly reformatted data from the result XML and I can put it into cleaned_data or self.cleaned_data. I then try returning either cleaned_data or self.cleaned_data but the modified vales do not show up in the model. def clean(self): # # get the form data cleaned_data = super().clean() # # build a USPS xml object address_wrapper = xmlET.Element("AddressValidateRequest", attrib=dict( USERID=config_parser['USPS']['username'] )) ... # # build the request quoted_xml = urllib.request.quote(xmlET.tostring(address_wrapper)) with urllib.request.urlopen(config_parser['USPS']['url'] + "?API=Verify&XML=" + quoted_xml) as response: ... # # get the result of the request xml_result = response.read().decode('utf-8') my_xml = xmlET.fromstring(xml_result) # # cannonacalize the US address info self.cleaned_data["address1"] = "" if my_xml.find("Address1"): self.cleaned_data["address1"] = …