Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a dynamic model-form?
I'm new to Django and I'm trying to write a project where employers can post job vacancies. I want to be able to save the job description as a model using a model-form but I also want to allow the user to specify how many requirements there are for a job. So one job might specify 4 job requirements while another might specify 6. So saved models will vary depending on how much requirements were specified. Is there anyway to create a dynamic model-form where the user can specify how many fields there are in the form and model? I've been researching this for a while but yet to find a simple explanation. -
django model saving the data temporary
I am using postgresql as database and it is just saving the data permanently into the database. So, given below is my views.py file @login_required def add_comment(request): if request.method == 'POST': comment = request.POST.get('comment') floor_id = request.POST.get('floor_id') question_id = request.POST.get('question_id') floor_detail = get_object_or_404(FloorDetail, id=floor_id) question = get_object_or_404(Question, id=question_id) answer, created = Answer.objects.get_or_create(floor_no=floor_detail, question=question) comment_obj = Comment.objects.create(answer=answer, comment=comment) print(answer, comment_obj) data = render(request,'mobile/include/single_comment.html', {'comment':comment_obj}) if data: html=data else: html=None return HttpResponse(html) else: question_id = request.GET.get('question_id') floor_id = request.GET.get('floor_id') question = get_object_or_404(Question, id=question_id) floor_detail = get_object_or_404(FloorDetail, id=floor_id) answer = Answer.objects.filter(floor_no=floor_detail, question=question).first() comments = Comment.objects.filter(answer=answer) data = render(request,'mobile/include/comment.html', {'comments':comments}) if data: html=data else: html=None return HttpResponse(html) when i use print (answer, comment_obj) statement it is printing out both the objects on the terminal, however when check the database through django-admin interface the answer & comment_obj instance isn't shown, means data is not reflected there. Please tell me how to fix it. -
django - view for redirecting to another page with query recieved
I have two search inputs, first on home page another on search results itself. what i m try to do is receive query form home and redirect it to search results page according to this : Like I search - html-5 redirect page should be - 127.0.0.1/html-5/find/?q=html-5 I have tried but unfortunately not getting the right way to it, please suggest me the correct way to do it. -
Combining ModelAdmin and InlineModelAdmin
Given two models Group and Member, where Member has a foreign key to Group: class Group(models.Model): # some fields class Member(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) # some other fields how can I have both a custom ModelAdmin for Member as well as an InlineModelAdmin (of members) in Group? class MemberAdmin(admin.ModelAdmin): # some logic, restricting fields, changing change form initial data.... admin.site.register(Member, MemberAdmin) class GroupAdmin(admin.ModelAdmin): # some logic, restricting fields, changing change form initial data.... inlines = [<MemberInline>] admin.site.register(Group, GroupAdmin) Adding a new inline admin for Member ignores the custom logic in its admin class class MemberInline(admin.TabularInline): model = Member extra = 3 # Does not respect the custom logic in MemberAdmin -
Error in Virtualenv(Python3.5/pip3/Django2.0/psycopg2) when run python3 manage.py migrate
I can run manage.py migrate at Virtualenv(Python3.5/pip3/Django2.0/psycopg2). (miWeb) xxxx@yyyy:~/myproject/miWeb$ python3 manage.py migrate /home/xxxx/mipagina/lib/python3.5/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/xxxx/miWeb/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/xxxx/miWeb/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File … -
django checkbox unchecked despite initial=True
I have a Django form containing a boolean field, "reduction." The field has an initial value of True (i.e. I want the corresponding checkbox to render as checked). My problem is that this doesn't happen. When the form first renders, the checkbox is unchecked. Searching for this topic yields a ton of issues related to the value of the checkbox on submit, and how it doesn't send anything if unchecked, etc. But I can't figure out why Django isn't initially checking this box. I've verified that the value of the field in the form is indeed true when the form is passed to the template from the view. Any ideas? The Form: class RunParamsForm(Form): fluid_present = BooleanField(widget=HiddenInput, required=False) solid_init_present = BooleanField(widget=HiddenInput, required=False) solid_sim_present = BooleanField(widget=HiddenInput, required=False) solid_present = BooleanField(widget=HiddenInput, required=False) load_map_present = BooleanField(widget=HiddenInput, required=False) scallop_map_present = BooleanField(widget=HiddenInput, required=False) fluid_endtim_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) solid_init_drterm_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) solid_sim_endtim_units = CharField(widget=TextInput(attrs={'class': 'units', 'readonly': 'readonly'})) steps = CharField(widget=HiddenInput) reduction = BooleanField(initial=True, required=False) The relevant html: <!-- REDUCTION BLOCK --> <div class="block1"> <div class="queueRunHeading"> Other </div> <div class="fieldWrapper"> <label for="{{ form.reduction.id_for_label }}"> 1-Dimensional Reduction </label> {{ form.reduction }} <span class="errorlist"> {{ form.reduction.errors.as_text }} </span> </div> </div> -
LookupError: No installed app with label 'app' (Django 1.11 / Python 2.7 / xadmin)
Can't for the life of me figure out what the issue is. Help please! I'm trying to extend the admin view (using the xadmin app), by including a chart The issue started appearing with the addition of: admin from xadmin import views from .models import DGISummary ... @xadmin.sites.register(views.website.IndexView) class MainDashboard(object): widgets = [ [ { "type": "chart", "model": "dgisummary", "chart": "reg_members", "params": { "_p_date__gte": "2017-01-01", "p": 1, "_p_date__lt": "2017-12-01" } }, ], ] model @python_2_unicode_compatible class DGISummary(models.Model): quarter = models.CharField(max_length=2,) reg_members = models.IntegerField() sub_received = models.IntegerField() ... class Meta: verbose_name = u"Summary" verbose_name_plural = verbose_name def __str__(self): return self.quarter And the traceback System check identified no issues (0 silenced). February 20, 2018 - 15:38:35 Django version 1.11.10, using settings 'csa_portal.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ERROR:root:No installed app with label 'app'. Traceback (most recent call last): File "C:/../apps\xadmin\views\dashboard.py", line 563, in get_widgets ws.append(self.get_widget(widget)) File "C:/../apps\xadmin\views\base.py", line 78, in method return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs) File "C:/../apps\xadmin\views\base.py", line 47, in filter_chain return func() File "C:/../apps\xadmin\views\base.py", line 72, in _inner_method return func(self, *args, **kwargs) File "C:/../apps\xadmin\views\dashboard.py", line 517, in get_widget wid_instance = widget_with_perm(self, data or widget.get_value()) File "C:/../apps\xadmin\views\dashboard.py", line 325, in __init__ super(ModelBaseWidget, self).__init__(dashboard, … -
Optimise Django query with large subquery
I have a database containing Profile and Relationship models. I haven't explicitly linked them in the models (because they are third party IDs and they may not yet exist in both tables), but the source and target fields map to one or more Profile objects via the id field: class Profile(models.Model): id = models.BigIntegerField(primary_key=True) handle = models.CharField(max_length=100) class Relationship(models.Model): id = models.AutoField(primary_key=True) source = models.BigIntegerField(db_index=True) target = models.BigIntegerField(db_index=True) My query needs to get a list of 100 values from the Relationship.source column which don't yet exist as a Profile.id. This list will then be used to collect the necessary data from the third party. The query below works, but as the table grows (10m+), the SubQuery is getting very large and slow. Any recommendations for how to optimise this? Backend is PostgreSQL but I'd like to use native Django ORM if possible. user = Profile.objects.get(handle="philsheard") qs_existing_profiles = Profiles.objects.all() rels = TwitterRelationship.objects.filter( target=user.id, ).exclude( source__in=Subquery(qs_existing_profiles.values("id")) ).values_list( "source", flat=True ) Thanks in advance for any advice! -
Relative URL replace part of old url instead of add to old one in django
i have a problem with relative url in django application. i have structure of objects which look like this Competitions/ games/ players/ costs/ and urls to point to it competitions/ list of all competitions {% for comp in competitions%} <li onclick=window.location.href='{{comp.pk}}'> comp.name </li> {% endfor %} when i clik on one of this links im redirect to page competitions/ competitions/ detail view of a competition competitions/games/ list of all game in picked competition {% for game in games%} <li onclick=window.location.href='{{game.pk}}'> game.name </li> {% endfor %} so when im on url: competitions/games/1 which list all games in competition with id = 1 <li onclick=window.location.href='1'> game1</li> <li onclick=window.location.href='2'> game2</li> <li onclick=window.location.href='3'> game3</li> <li onclick=window.location.href='4'> game4</li> and i click for example on game4 my url address is competitions/games/4 insted of competitions/games/1/4 can someone explain me why. -
Django Deploy to Heroku "Six" / "django-appconf" issue
I am a complete beginner, but I have created a small website using Python / Django with the help of django-cookiecutter, including the deploy to Heroku instructions. I am in the process of deploying it for the first time to Heroku, however, the build is failing at the point in which it is running setup.py install for django-appconf, suggesting that it is due to the fact that Heroku already has the "Six" package. The error message I am receiving is as follows: Running setup.py install for django-appconf: finished with status 'error' Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-tzjhtkga/django-appconf/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y2i8uuc4-record/install-record.txt --single-version-externally-managed --compile --without-c-extensions: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: option --without-c-extensions not recognized ---------------------------------------- Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-tzjhtkga/django-appconf/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-y2i8uuc4-record/install-record.txt --single-version-externally-managed --compile --without-c-extensions" failed with error code 1 in /tmp/pip-build-tzjhtkga/django-appconf/ ! Hello! Your requirements.txt file contains the six package. ! This library is automatically installed by Heroku and shouldn't be in ! Your requirements.txt file. This can cause unexpected behavior. ! -- Much Love, Heroku. ! … -
django queryset to json list to js array
I am fairly new to json and javascript and I've been trying to pass django queryset to a js array. I've managed to pass the .values queryset to javascript through json. Django to JSON code def getPorts(request): ports = Port.objects.all() data = serializers.serialize('json', ports, fields=('name')) return JsonResponse(data, safe=False) JS where I am currently stuck at $.ajax({ url: 'getPorts, dataType: 'json', success: function(result){ var ports = JSON.parse(result) console.log(ports[0]); } }); ports[0] gives me something like {model: "Coordinator.port", pk: 1, fields: {…}} fields: {name: "Fa0/1"} model:"Coordinator.port" pk:1 proto:Object Is there a way to extract only the 'name' attribute? I've been trying to treat it like a 2d array but I haven't really been successful -
How do I add headers to a python-oauth2 request?
I'm using the python-oauth2 library to send requests to the Twitter API. I want to do a GET users/show request which needs a parameter to specify the user_id, but the small wiki on the official GitHub page doesn't really explain how to add non-oauth HTTP headers to it's requests. By trying to read the code and understand what the right approach was I tried this: get_info_url = 'https://api.twitter.com/1.1/users/show.json' #user is a Django model with the authorization info for the user access_token = oauth.Token(user.oauth_token, user.oauth_token_secret) client = oauth.Client(consumer, access_token) headers = { 'user_id' : user.twitter_id } resp, content = client.request(url=get_info_url, method="GET", headers=headers) print('Content: ' + str(content)) but it prints Content: b'{"errors":[{"code":50,"message":"User not found."}]}'. How should I do it? -
Django SetPasswordForm will not display bootstap class "form-control"
I am trying to make a "change password"-page by using the SetPasswortForm. The problem is that it does not implement the 'class': 'form-control'-attrribute. Maybe I am missing something, but it should work normally. Here it is: class PasswordChangeForm(SetPasswordForm): old_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', 'autofocus': 'autofocus' } ) ) new_password1 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) new_password2 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) class Meta: model = User fields = ( 'old_password', 'new_password1', 'new_password2', ) I did it the same way in my UserCreationForm and it worked. change_password.html: {% load widget_tweaks %} <form method="post"> {% csrf_token %} {{ form.non_field_errors }} <table style="margin-bottom: 1.5em;"> <tr><td><label for="{{ form.old_password.id_for_label }}">Altes Passwort*</label></tr></td> <tr><td><field>{{ form.old_password }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password1.id_for_label }}">Neues Passwort*</label></tr></td> <tr><td><field>{{ form.new_password1 }}</field></tr></td> <tr><td><label style="margin-top: 1.5em;" for="{{ form.new_password2.id_for_label }}">Neues Passwort bestätigen*</label></tr></td> <tr><td><field>{{ form.new_password2 }}</field></tr></td> </table> Views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('accounts:password_change_done')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) Maybe the code on the views.py is not correct. If you have any idea, let … -
'ValidationError' object has no attribute 'get'
I am making a form using python 3.5 and DJANGO 1.8 and I am getting this error--> I tried reading this Post but I already have returned clean_data so no use AttributeError at /login My forms.py file class UserLoginForm(forms.Form): username=forms.CharField(max_length=40) password=forms.CharField(max_length=40,widget=forms.PasswordInput) def clean(self,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user=authenticate(username=username,password=password) if not user: return forms.ValidationError("This user doesn't exist") if not user.check_password(password): return forms.ValidationError("Incorrect Passwordt") if not user.is_active: return forms.ValidationError("User nO longer Active") return super(UserLoginForm,self).clean(*args,**kwargs) Traceback: Environment: Request Method: POST Request URL: http://localhost:8000/login Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', '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') Traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\login\views.py" in login 15. username=form1.cleaned_data.get("username") Exception Type: AttributeError at /login Exception Value: 'ValidationError' object has no attribute 'get' If there is anything else you people want me to post tell me in the comments .Thanks in advance -
Django autocomplete a foreign key field with a previous value (Forms)
I use form wizard to create a multiple step form based on 2 models. models.py : class Author(models.Model): refCode = models.IntegerField(unique=True) lastName = models.CharField(max_length=20) firstName = models.CharField(max_length=20) birthDate = models.DateField() description = models.TextField() style = models.ForeignKey(Style) class Book(models.Model): refCodeAuthor = models.ForeignKey(Author) title = models.CharField(max_length=100) summary = models.TextField() view.py : class AuthorWizard(SessionWizardView): form_list = [AuthorForm, DescriptionForm, BookForm] def done(self, form_list, form_dict, **kwargs): form_values={} for form in form_list: form_values.update(form.cleaned_data) auth = Author(**form_values) auth.save() return render(self.request, 'done.html', { 'form_values':form_values, }) I have 3 steps, corresponding to form_list AuthorForm DescriptionForm BookForm When I am on BookForm, i don't want to display refCodeAuthor but autocomplete this field with the value of refCode in the step AuthorForm. The user create a author then he add his books, he don't have to choose a refCodeAuthor although isn't in the same model. How can I achieve that ? -
unable to resolve host.no adress associated with hostname
so here are my class which I have used ..I have added internet permission in mainifest...I want to know how can I connect my local server to my app and access data of JSON generated through local server to my app (I have used my mobile phone to test this...no emulator is used) Main Activity package com.example.kiran.retrofitbasic; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { TextView mtextview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mtextview = (TextView)findViewById(R.id.textcheck); getheroes(); } private void getheroes(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(apiinterface.API.base_url) .addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object .build(); //creating the api interface apiinterface.API api = retrofit.create(apiinterface.API.class); Call<List<Hero>> call = api.getheroes(); call.enqueue(new Callback<List<Hero>>() { @Override public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) { List<Hero> heroList = response.body(); mtextview.setText(heroList.get(0).getFirstname()); } @Override public void onFailure(Call<List<Hero>> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } **apiinterface class ..here i have used my local ip adress to connect ** package com.example.kiran.retrofitbasic; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; /** * Created by kiran on 2/20/2018. */ public class apiinterface … -
Image is not displaying in django template
I am having problem with displaying image in the Django template.Apart from imagefield other field are showing properly.Please find below template and model.Note that I haven't declared any image field in my model.Any help will be much appreciated. Model.py class any(models.Model): Status=models.CharField(max_length=10,choices=Status_choices,default='SUCCESS') Smoke=models.CharField(max_length=10,choices=Smoke_choices,default='SUCCESS') Sanity=models.CharField(max_length=100,choices=Sanity_choices,default='YES') Template: <table class = "table table-striped table-bordered"> <thead> <tr> <th>Tag</th> <th>Smoke</th> <th>Status</th> <th>Sanity</th> </tr> </thead> {% for result in results %} <tbody> <tr> <td> {% if result.Status == SUCCESS %}<img src='/static/test/img/release.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% elif result.Status == FAILURE %} <img src='/static/test/img/block.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% elif result.Sanity == NO %}<img src='/static/test/img/thumbs-down.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> {% endif %} </td> <td>{{ result.Smoke }}</td> <td>{{ result.Status }}</td> <td>{{ result.Sanity }}</td> </tr> </tbody> {% endfor %} -
Django 1.11.8 - Slug - Unexpected Keyword argument
I am new to django and I have started building my first app a couple of days ago. I first went through the MDN Tutorial and the Django Tutorial - building 2 "dummy" apps. I am currently trying to develop a photo gallery app that will display all pictures belonging to a certain album. I am able to accomplish that using in my urls.py and a class-based view, though, I would like to get a cleaner URL using . I would like my URL to look like mysite.com/myapp/my-album-name vs mysite.com/myapp/1 I know they are similar questions that have been asked here, I've went through most of them, read the Django doc about Single Object Mixins, Class Based Views and I am still not understanding how to get slug to work. So far I've tried to: Implement a slug field in my models and the corresponding slug values in my admin.py file: models class Album(models.Model): album_name = models.CharField(max_length=100, help_text="Enter the name of your album" ) album_creation_date = models.DateField(auto_now_add=True) album_modified_date = models.DateField(auto_now=True) slug = models.SlugField(max_length=50) Views class albumPictures(generic.DetailView): model = Album Admin class AlbumAdmin(admin.ModelAdmin): list_display = ('album_name', 'album_creation_date') slug = prepopulated_fields = {'slug': Album.album_name} admin.site.register(Album, AlbumAdmin) Error Message: <class 'Albums.admin.AlbumAdmin'>: (admin.E030) The … -
Ajax form submit not working second time [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 19 answers I am using Django and here are the get and post methods. After refreshing page, on first form submit, Ajax jquery is called. On success, it returns json.msg which is another form rendered as given in below post call. When I try to submit this rendered form, ajax is not called but it directly calls the django POST method. On ajax success, I tried '$('#school').unbind('submit').submit();'. This way, it ensured to call ajax on every form submit. But, the above method, refreshed the whole page which I do not want. May I know how can I unbind the previous submit without page refresh or get Ajax called(and not direct django post) on every submit. def get(self, request): ... ... return render(request, self.template_name, {'form':next_form_obj}) def post(self, request): ... t = get_template('school/fun_activities.html') msg = t.render({'form': next_form_obj}, request) return JsonResponse({'msg': msg}) Here's the Ajax call. $('#school').on('submit', function(event){ $.ajax({ type: 'POST', url: '/school/fun/', data: $("#school").serialize(), success: function (json) { event.preventDefault(); $('#msg-list').append(json.msg); #json.msg is another form }, error: function(data) { $("#msg-list-div").html("Something went wrong!"); } }); return false; }); HTML: <form id = "school" method="post" action="."> <input type="submit" value="Next" /> </form> -
Show model values as multi select options in admin
I am trying to store use the values from two different models to show as choices in form and store them in new model. Here is what I have now. models.py class Employee(models.Model): name = models.CharField(max_length=200) class Product(models.Model): code = models.CharField(primary_key=True, max_length=5) class JobQueue(models.Model): emp_name = models.CharField(max_length=200) product_code = models.CharField(max_length=5) forms.py class JobQueueForm(forms.ModelForm): emp_choices = Employee._meta.get_field('name').choices product_code_choices = Product._meta.get_field('code').choices emp_name = forms.ChoiceField(choices = emp_choices) product_code =forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=product_code_choices) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') admin.py class JobQueueAdmin(admin.ModelAdmin): form = JobQueueForm fieldsets = ( (None,{ 'fields': ('emp_name', 'product_code'),}), ) def save_model(self, request, obj, form, change): super(JobQueueAdmin, self).save_model(request, obj, form, change) admin.site.register(models.Employee, AuthorAdmin) admin.site.register(models.Product, ProductAdmin) admin.site.register(models.JobQueue, JobQueueAdmin) I do have values stored in Employee and Product models, but I dont see them as options in JobQueue model in Admin portal. Am I missing anything here? -
StreamField – TypeError: 'bool' object is not iterable
Build: Wagtail CMS(1.13.1) with Django(1.11) in python3.6. I am trying to create a pretty basic Streamfield block(CardBlock), but keep getting a type error. It is very similar to the examples in documentation, but I can not get it to work... class CardBlock(StructBlock): image = ImageChooserBlock() heading = CharBlock(classname="full title") caption = RichTextBlock() class Meta: icon = 'image' class HomePage(Page): intro = RichTextField(blank=True) showcase_title = RichTextField(blank=True) card = StreamField([('card', CardBlock())], default=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full"), MultiFieldPanel([ FieldPanel('showcase_title'), StreamFieldPanel('card'), ]), ] django is trying to "get_db_prep_value()". So, Wagtail tries to "get_prep_value()", for all children(streamchild instances) in value, as shown below. wagtail/wagtailcore/blocks/stream_block.py (line 257): def get_prep_value(self, value): if value is None: # treat None as identical to an empty stream return [] return [ { 'type': child.block.name, 'value': child.block.get_prep_value(child.value), # assign a new ID on save if it didn't have one already 'id': child.id or str(uuid.uuid4()), } for child in value # child is a StreamChild instance ] I am uncertain as to what this value is. What in my block classes needs to be changed to correct this value variable? -
ManyToManyField returns none in template
So I have these 2 models. My Course model is linked with a ManytoMany field to TeacherData. When I try to display teacher though, I get courses.TeacherData.none. What is wrong ? class TeacherData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) teacher_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) class Meta: verbose_name = "Teacher Data" verbose_name_plural = "Teachers Data" def __str__(self): return self.surname class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher = models.ManyToManyField('TeacherData', verbose_name="Taught By") slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name <ul> {% for c in courses.all %} <li>{{ c.study_programme }}</li> <li>{{ c.name }}</li> <li>{{ c.ects }}</li> <li>{{ c.description }}</li> <li>{{ c.year }}</li> <li>{{ c.semester }}</li> <li>{{ c.teacher }}</li> {% endfor %} </ul> def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) -
Regular expression for an alphanumeric string of 10 characters
I need to compose an expression for the urls.py file The get-variable var can be an alphanumeric string of 10 characters. The link looks like this http://127.0.0.1:8000/?var=fea40u7b94 -
Django: Creating multiple objects of the same instance and then list them in DRF
I want to create multiple objects of the same instance in Django Rest Framework and then return a list of these objects. So lets say I have this model: class City(models.Model): ... class House(models.Model): city = models.Foreignkey(City, ...) ... class Resident(models.Model): house = models.ForeignKey(House, ...) I now want to be able to hit a route with a postrequest like this: localhost:8000/api/city/createresidents/ And get back JSON like this: { [ { residentid = "<some_number>", residentname = "<some_name>", }, { residentid = "<some_number>", residentname = "<some_name>", }, ... ] } And in the body of the postrequest I append information about the House and the created residents, maybe which street it is, what last name the residents have, or some other data about the house or the residents from their respective model. How would I go about doing that if the view should allways create, let's say 4 residents? I tried modifying the perform_create() method of the CreateModelMixin but I could'nt get it to work. Any help would be much appreciated! -
Django fixtures with specific data
I have an app with 3 models that refer to each other in a parent-child way: class A(Model): # ... class B(Model): a = ForeignKey(A) # ... class C(Model): b = ForeignKey(B) # ... In my production database, I have hundreds objects of type A, with thousands of child objects below it. I now want to create a fixture for only a (specific) handful objects. If I run this command, my output will become huge: python manage.py dumpdata ca_myapp -o /tmp/my_app_dump.json However, when I restrict the output using this command: python manage.py dumpdata ca_myapp.A -o /tmp/myapp_dump.json --pks pk1, pk2, pk3 Then only the A objects are deserialized, but not their children. How can I easily create a fixture file with a handful of objects and their children?