Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django auth Group name as ChoiceField in Django Rest Framework
I want to override my choicefield in DRF.. especially i want to return django group as ChoiceField in OPTIONS Eg: My Group Models are, id group_name 1 Lead 2 Admin 3 Junior 4 Senior here i want to return Group Name as choices in http request OPTIONS how do i do it? -
Django query without extra or Raw
I want to write a query such as Select * from my_table where 'parameter1' LIKE CONCAT("%", col_1, "%") OR 'parameter2' LIKE CONCAT("%", col_1, "%") AND (col_2 IS NULL OR 'parameter3' LIKE CONCAT ("%", col_2, "%") AND (col_3 IS NULL OR col_3='parameter4'). I have been trying out the following. first_partial_qs = ModelName.extra(where=["%s LIKE CONCAT ('%%', col_1, '%%')"],params=[something1]) first_final_qs = first_partial_qs | ModelName.extra(where=["%s LIKE CONCAT ('%%', col_1, '%%')"],params=[something2]) second_qs = ModelName.filter(col_2__isnull=True) | ModelName.extra(where=["%s LIKE CONCAT ('%%', col_2, '%%')"], params=[something3]) third_qs = ModelName.filter(Q(col_3__isnull=True) | Q(col_3=something4)) I want to know how would I do final_qs = first_final_qs AND second_qs AND third_qs But since life is not that simple (for django developers since they will be deprecating extra(), I want to find a way to do it without using extra(). One option would be to use raw() but is there a more Django-ish way of doing this? -
How to apply all Django migrations initially
In Django < 1.7, you could apply all schema changes to a blank database by running: manage.py syncdb --all However, in Django >= 1.7, even though the syncdb command is technically still there, this functionality seems to have been removed, since the --all option is no longer available. The command itself appears to be just a wrapper around migrate, so running it just applies all migrations individually, which can take a huge amount of time if you have a lot of migrations. I have a script that initializes a blank database with my schema, and what used to take a minute now takes nearly 30, which is an insane performance drop for an upgrade. Is there any way to get the old functionality back? -
Django Context Syntax
I am getting a syntax error in my context: 'meta_description':meta_description The arrow points the the colon. Here is my view which gives me the error: from django.shortcuts import render, get_object_or_404 from .models import Category, MenuItem def show_category(request, category_slug): c = get_object_or_404(Category, slug=category_slug) menuitems = c.product_set.all() template_name="menu/category.html" page_title = c.name meta_keywords = c.meta_keywords meta_description = c.meta_description context = { 'c':c, 'menuitems':menuitems, 'page_title':page_title, 'meta_keywords':meta_keywords 'meta_description':meta_description } return render(request, template_name, context) What is causing this? Thanks -
Form validation is switching validations in django
I have a view in a django project and it has a form that a user fills out and submits. he fills in age, city, phone, privacy. Now when it is submitted and checked for validation. I notices that i am getting an error because it is trying to validate the form in the wrong def within the views.py file... The form is passed and submitted to the prifle_setup def. but i am getting an erro that it is being validated in the UserHome def instead. Am i missing something or is there something small that is wrong with my code. can anyone help. this is what I have right now as well as the error message... View.py file: def profile_setup(request): if 'username' not in request.session: return redirect('login') else: username = request.session['username'] currentUser = User.objects.get(username = username) if request.method == 'POST': if form.is_valid(): cd = form.cleaned_data age = cd['age'] city = cd['city'] phone = cd['phone'] privacy = cd['privacy'] new_profile = Profile.objects.create( user = currentUser, age = age, city = city, phone = phone, privacy = privacy, ) return redirect('home_page') else: form = ProfileForm() message = 'form was not valid' parameters = { 'form':form, 'currentUser':currentUser, 'message':message, } return render(request, 'tabs/profile_setup.html', parameters) … -
How to include 'apostrophe' (`) in url?
This is my regex [\w!@#$%^&*\u2019()+,.;:\'"-_ ]. It is allowing all the special characters except apostrophe (`). I am getting the following error Reverse for 'view_project' with arguments '(u'FOGG Men\u2019s',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['dashboard/items/v/(?P<projectname>[\\w!@#$%^&*\\u2019()+,.;:\'"-_ ][\\w!@#$%^&*\\u2019()+,.;:\'"-_ ]+)$'] Can someone tell me how to allow apostrophe in urls? -
DJANGO REGISTRATION
I want to build a mini social network. How do I get users to register on the site first(not login). I heard Django has a registration form and table built into it. I looked up some tutorials and I saw them use UserCreationForm(). I need a better understanding and which table does it save the data to. Thanks for your help -
django rest make an api of database information schema
How can I make an API to show information schema such as columns name or tables name. For showing column name I wrote this code: class ColumnNameView(APIView): def get(self, request, format=None): rawquery="SELECT column_name FROM information_schema.columns WHERE table_schema = 'MySchema' AND table_name = 'MyTable'" queryset=MyTable.objects.raw(rawquery) response_data = {} response_list = list() for i in queryset: response_data["id"] = i.column_name response_list.append(response_data) return Response(data=response_list) But got this error: Raw query must include the primary key and for table name I have no idea. Any advice will be thankful... -
How to get the link of a table in the admin page
For example admin/appname/mytable I need to get the link of my tables to put in the navbar, how can I do this ? -
How to convert an Charfield Primary key to AutoField in Postgres
I have a model like the following in My Django Application order_id = models.CharField(max_length=120, default=uuid.uuid4, unique=True, primary_key=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False,null=True) delivery_address = models.CharField(max_length=200, blank=True) order_by = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE); order_Description = JSONField(null=True, blank=True) I want to convert the order_id to an AutoField so that my final column would look like order_id = models.AutoField(primary_key=True) but I encounter the following error during migration django.db.utils.ProgrammingError: operator class "varchar_pattern_ops" does not accept data type integer. I searched online but I am not able to find a proper solution for the above issue. I am sorry if this question had already been asked before. Thanks for the help in advance. -
Pointing Django to Different Template Directory
I am currently building a Django ecommerce site that is based on Django-Oscar. By default the latter comes with a basic Bootstrap theme and styles. I moved these template files into project_root/templates/oscar It is my understanding that if I were to override these templates, it would override the original Oscar templates located in the virtualenv. The next step is that I downloaded a different theme that I would like to use for the site. In particular, I would like that theme to reside in project_root/templates/main_theme The trouble is that I cannot seem to get Django to pickup the templates from that directory. If I delete project_root/templates/oscar, it appears to resort back to the default Oscar templates. If I place a base.html into project_root/templates/ and make that base.html to be the main file of the new theme, it is displayed. However, I would still like to break it up into smaller files and have them "live" in a separate directory. How can I accomplish this? Is there a more prudent way of going about this? Here are some relevant settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'django.contrib.sites', 'compressor', 'widget_tweaks', ] + get_core_apps() TEMPLATES = [ { 'BACKEND': … -
Django Rest API TypeError when using ChoiceField
I encountered a TypeError when trying to use the ChoiceField in my serializers. from rest_framework import serializers from rest_framework.fields import ChoiceField from comp_track_sys.models import Campaign from contacts.models import CList class EditCampaignSerializer(serializers.ModelSerializer): class Meta: ... def __init__(self, *args, **kwargs): super(EditCampaignSerializer, self).__init__(*args, **kwargs) user = self.context['request'].user clists = CList.objects.filter(company=user.profile.company) self.fields['clist'] = ChoiceField(choices=clists) I have tried to do ChoiceField(choices=json.dumps(clists)), but still got the error. TypeError: <CList: Testing> is not JSON serializable -
How to order django rest framework queryset from serializer field?
How can i order a drf queryset from a serializer field? Since the field is too complicated, i couldnt order the queryset using annotate and I cannot store the value in the model as well. -
How to use Django models ForeignKey?
I used two ForeignKey in Table 'Posts' to connect Table 'User', one is for username and another is for icon, like: user = models.ForeignKey(UserInfo, related_name='user_name') icon = models.ForeignKey(UserInfo, related_name='user_icon', null=True) In my views, I try to iterate Table 'Posts': class AllPosts(View): def get(self, request): all_posts = Posts.objects.all() return render(request, 'community.html', { "all_posts":all_posts, }) Here's how I iterate in my template: {% for post in all_posts %} {{ post.user }} {{ post.icon }} {{ post.title }} {{ post.content }} {% endfor %} Results: <img class="icon" src="/media/None"> <span class="name_span">klawens</span> So the post.user show the correct result, but the icon is a None, I don't know how to use ForeignKey to connect the exact key I want, and what's the related_name for exactly? -
Django add fields dynamically in a Model
I'm building an eCommerce Web and I need to do following : Add category(name, slug) Inside category, add category attributes dynamically: name, value What I wanted is when I add category in admin page, I want to add dynamically two fields with + button. I enter attribute_name, attribute_value, I want to add two more fields etc... I really don't know where to start. I've created simple Category model as class Category(models.Model): category_name = models.CharField(max_length=30) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.category_name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.category_name -
django subquery with outerref
i'm trying to use django's Subquery function and I need to perform a complicated annotate on a Drink objects queryset. Here are the models. class Drink(models.Model): ingredients = models.ManyToManyField(Ingredient, blank=True) class Ingredient(models.Model): name = models.CharField(max_length = 1000) user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) I would like to perform annotate so that I get the count of the intersection of each drink's ingredient queryset and the user's ingredient queryset. Here is a shot at it. user_ingredient_qs = user_obj.ingredient_set.all() drink_qs = Drink.objects.all() drink_qs = drink_qs.annotate(count_need=Count(Subquery(OuterRef('ingredients'))&user_ingredient_qs)).order_by('count_need') However, i'm stuck because I don't know how to access the drink's ingredient queryset at OuterRef('ingredients') Here is how to do it on a single object def get_count_need(self, obj): ingredient_qs = obj.ingredients.all() user = self.context['request'].user user_qs = User.objects.filter(username=user.username) if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() user_ingredient_qs = user_obj.ingredient_set.all() return (user_ingredient_qs & ingredient_qs).count() return 0 However, I need to do it with annotate for my purposes. Any ideas? Thanks -
Jinja doesn't display things (Python 3.6-PyCharm-Django)
I'm very new in Django, so problem is: Trying to paste some tags in html doc with jinja, but it doesn't work.Jinja's code. html file P.S.: Tried to paste Jinja's code in empty html file, but still doesn't work. -
How to raise an error for all erros from a custom clean method
I have a model Students and another called Classroom, When creating a new student object in the database I need to check if the Classroom I'm assigning the student has places. I'm doing this with signals, If I raise the error for "There's no places" in the signal I get that yellow page with the error, not the beautiful page of the django admin with the error. So I did this and it worked, I'm getting the error in the django admin. def clean(self, *args, **kwargs): try: super(Student, self).save(*args, **kwargs) except ValidationError: raise ValidationError("There are no places for this classroom !") Only, As I have Classroom as a related object, If I don't put a classroom I get the yellow page with the error. RelatedObjectDoesNotExist Student has no Classroom So How can I expect this error without removing my ValidationError: -
Custom UpdateView in Python
I am trying to get a custom UpdateView to work in Python/Django. I believe that the code that I've writtten is mostly correct, as it seems to be returning the proper Primary Key ID in the URL when I click on the associated dropdown. The problem is that I am not seeing any of the data associated with this record on the screen in update mode. The screen appears in edit mode, but there is no data. I suspect the problem is perhaps the django template in the html form? However, I have played with the form and used {{ form }} and it too returns a blank form. I've played with this all afternoon and I'm out of guesses. Here is my view: def updating_document(request, pk): doc = get_object_or_404(Doc, pk=pk) form = Update_Doc_Form(request.user, request.POST) if request.method == 'GET': if form.is_valid(): form.save() return HttpResponseRedirect(reverse('App:main_procedure_menu')) else: print("Form is invalid!") return render(request,'Doc/update_doc.html',{'form':form }) I also have an associated form... Form.py class Update_Doc_Form(forms.ModelForm): class Meta: model = Doc exclude = ['user'] doc_name = forms.CharField(widget=forms.TextInput) description = forms.CharField(required=True,widget=forms.Textarea) team = forms.CharField(widget=forms.Select) document = forms.CharField(required=True,widget=forms.Textarea) def __init__(self, *args, **kwargs): super(Update_Doc_Form, self).__init__(*args, **kwargs) self.fields['doc_name'].widget.attrs['class'] = 'name' self.fields['description'].widget.attrs['class'] = 'description' self.fields['team'].widget.attrs['class'] = 'choices' self.fields['team'].empty_label = '' I'm … -
Django static files organization
I'm working in new app in Django and I researching for the best way to organize my project. At this moment each app will be an independent module for my system, each one will have their own models, templates, urls, etc.. but now I just confuse about how to set my static files. If I create a new folder static for each app (which actually is an option) I may have to import from other apps. What I really want to do is keep inside the app just the files for the app, in special JavaScript, and keep plugins and frameworks like jQuery and React.js for global usage. project_name - app - migrations ... - static (just app js) - js - templates - item.html - list.html - project_name - static (global) - plugins - jQuery - bootstrap - react - css - sass - js - elements - components - img - __init__.py - manage.py Would be a good idea to make something like this? How would be the best way to organize this folders? -
Unable to make a simple calculation in django
i have a view and i am trying to perform a simple mathematical calculation and I am getting an error that is throwing me off. So I have a method that will take in two variabes, a decimal value and a integer. I want to take the numbers and divide the decimal by the integer. I am getting the following error and I dont know why... this is the method def SplitEven(record, amount): record_count = record.count print(record_count) print(amount) split_amount = amount/record_count print(split_amount) rounded_amount = round(split_amount, 2) print (record_count) print (amount) print (split_amount) return rounded_amount This is the error message: unsupported operand type(s) for /: 'str' and 'int' C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in addTransaction taxSplit = SplitEven(record, amount) C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in SplitEven split_amount = amount/record_count Here is what comes up from the print statements: [25/Jul/2017 16:14:10] "GET /static/css/blog.css HTTP/1.1" 404 1649 6 6 6.00 [25/Jul/2017 16:15:05] "POST /39/72/add_transaction/ HTTP/1.1" 500 83164 -
Requests toolbelt multipart uploading file with CSRF fails
I am trying to upload an .ipa file from my DRF backend to a 3rd party app using python Multipart data encoder (http://toolbelt.readthedocs.io/en/latest/uploading-data.html). However, I am getting the following error- ('Connection aborted.', BrokenPipeError(32, 'Broken pipe')) If I remove the 'rb' attribute, I get the following error instead- 'utf-8' codec can't decode byte 0xe3 in position 10: invalid continuation byte Could someone please point out what's wrong here? Btw, I decided to use the requests toolbelt since I might upload huge files. class upload_binary(generics.GenericAPIView): def post(self, request, format=None): URL = "http://localhost:9020/" csrf = requests.get(URL).cookies['csrftoken'] post_url = "http://localhost:9020/upload/" upload_file_name = "SomeApp.ipa" media_dir = settings.MEDIA_ROOT upload_file_path = os.path.join(media_dir, upload_file_name) filedata = MultipartEncoder(fields = { 'csrfmiddlewaretoken': csrf, 'file1': ('file', open(upload_file_path, 'rb')) }) headersdict = {'X-CSRFToken': csrf, 'Content-Type': filedata.content_type, "Referer": "foo"} upload_bin_req = requests.post(post_url, data = filedata, headers = headersdict) return JsonResponse({}) -
Ordering of custom Django middleware
In a Django app, I have two middlewares. One is called NoWWWRedirectMiddleware, it's purpose is to redirect www to no www. The second is called XForwardedForMiddleware. It populates REMOTE_ADDR with the first value of HTTP_X_FORWARDED_FOR (if it exists). My question is about middleware ordering in settings.py. Currently, I have it ordered like so: 'myproj.middleware.NoWWWRedirect.NoWWWRedirectMiddleware', 'myproj.middleware.XForwardedFor.XForwardedForMiddleware', ################## Other Middleware ################### 'user_sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', My question is: shouldn't the top two be the other way around? I'm hazy about how to order them, and am currently going with gut feel. -
Django using UpdateView within a detail view?
I'm having issues with this update view: class UpdateRules(UpdateView): model = BlackList fields = ['numkey','bnum','days','blocked'] success_url='/' I'm trying to create an edit form for each object in a list, which is itself on a detail view page. Here are the urls for both, starting with the detailview: url(r'^(?P<id>\d+)/$', views.post_detail, name='detail'), url(r'^update_rules/(?P<pk>[\w-]+)$', UpdateRules.as_view(),name='update_rules'), So the detail view page uses a slug for the object id. The context for the top level object is "instance", and the objects that i'm trying to update are 'obj' so I assume when calling the updateview i need to do something like this: {% for obj in instance.blacklist_set.all %} <li><a href="{% url instance.id 'update_rules' obj.pk %}"><p style="font-size: 20px">{{obj.bnum}}</h2></a></li> <p>{{obj.pk}}</p> {% endfor%} I just keep getting "NoReverseMatch at /2/", when the the slug for the page is /2/. Have been trying lots of variations with no success. Any ideas? -
Why django-background-tasks doesn't create table background_task_completedtask
I run package background_task_completedtask on Django 1.11 and python 3.5.2 from http://django-background-tasks.readthedocs.io/en/latest/: Python: 2 & 3 Django: 1.8–1.11 When I run migrations I got the output: - Remove field creator_content_type from completedtask - Delete model CompletedTask and migration: class Migration(migrations.Migration): dependencies = [ ('background_task', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='completedtask', name='creator_content_type', ), migrations.DeleteModel( name='CompletedTask', ), ] and all gone good but when I run tasks django raise an error django.db.utils.OperationalError: no such table: background_task_completedtask Why django remove this table and how can I avoid it? Should I just ignore this migration or there is some more clever way? P.S. I already check simial questions but I didn't find the solution.