Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to delete form form inline formset in django
I have a inline formset called WorkExperienceFormset. I am generating form clicking a button. But I am unable to delete the forms. When I click button nothing is happening. forms.py: WorkExperienceFormset = inlineformset_factory(Employee, WorkExperience, extra=0, min_num=1, fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ], widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), }, can_delete = True, can_order = True, ) template.html: <div class="work-formset"> {% for work_form in work_formset %} <div class="work-form"> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Previous Company Name</label> <div class="col-md-4 col-sm-4 col-xs-12"> <!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> --> {{ work_form.previous_company_name }} </div> </div> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Job Designation</label> <div class="col-md-4 col-sm-4 col-xs-12"> <!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> --> {{ work_form.job_designation }} </div> </div> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">Job Details</label> <div class="col-md-4 col-sm-4 col-xs-12"> <!-- <input type="text" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12"> --> {{ work_form.job_description }} </div> </div> <div class="item form-group"> <label class="col-form-label col-md-4 col-sm-4 col-xs-12 label-align">From Date</label> <div class="col-md-2 col-sm-2 col-xs-12"> <!-- … -
How to depending on request in view influence on serializer?
For example i want to choice in view to show field book as url on this book record or to show all book's record content. Or for example if i want to set the depth field in class Meta -
How to automatize task retry with Celery?
I follow the Celery documentation for automatic task retry on known exception in my Django app but my code doesn't work as there is no retry. I have a list of exceptions I would like to pass to autoretry_for but my logger just display the exception when an error occurs. What am'I missing? This is a simplified code example where the exception Exception raised is supposed to trigger a retry but it doesn't. import myapp.celery as celery @celery.app.task(autoretry_for=(Exception,), retry_kwargs={'max_retries': 5, 'countdown': 2}) def do_something(): print('Raise an exception and retry') raise Exception # do more stuff -
Execute code after Response using Django's Async Views
I'm trying to execute a long running function (ex: sleep(30)) after a Django view returns a response. I've tried implementing the solutions suggested to similar questions: How to execute code in Django after response has been sent Execute code in Django after response has been sent to the client However, the client's page load only completes after the long running function completes running when using a WSGI server like gunicorn. Now that Django supports asynchronous views is it possible to run a long running query asynchronously? -
using mySQL database to listen to tcp port for data
Curious in learning the general flow of how this would work. -planning to create a simple web app in Django which will serve as a dashboard to monitor different metrics of data which a sensor is feeding into a specific tcp port on my machine. -How would I go about creating a mySQL database on this machine to be able to pull data from the tcp port which is constantly streaming this data? -would I simply set up the server client connection using workbench and just make query calls from the IP of the host and tcp port? any advice on how to go about doing this would be greatly appreciated. -
How can I make changes to Django import_export csv file before_export with making changes to database
How can I edit the csv file before exporting using Django import_export? I know I can call before_export to do stuff with the queryset before exporting, but I specifically want to change all of a given integer field to "0" for the csv rows only and not make changes to the database. class AdminResource(resources.ModelResource): def before_export(self, queryset, *args, **kwargs): ... # I can only edit the queryset here but I need to edit the rows of the csv and leave the database -
Python Django Rest Framework: The `.create()` method does not support writable nested fields by default
I am using django rest framework to create an api endpoint. I am using the default user model django offers. I need to create a post which uses the user as a foreign key. A user called "author" in the post can have multiple posts. This is an example of a post json. [ { "author": { "id": 1, "username": "sorin" }, "title": "First Post", "description": "Hello World!", "created_at": "2020-08-05T14:20:51.981163Z", "updated_at": "2020-08-05T14:20:51.981163Z" } ] This is the model. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is the serializer. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class PostSerializer(serializers.HyperlinkedModelSerializer): author = UserSerializer() class Meta: model = Post fields = ('author', 'title', 'description', 'created_at', 'updated_at') I am getting the error "The .create() method does not support writable nested fields by default." when trying to make a post request using a "username", "title" and "description". Any help to how to solve this? -
How to query a column of a Django table when it's joined to other tables
I created a models.py with these classes: class C(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=150) posted_date = models.DateTimeField(default=timezone.now) class S(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=150) slug = models.SlugField(max_length=200) posted_date = models.DateTimeField(default=timezone.now) class C_S(models.Model): c = models.OneToOneField(C, null=False, primary_key=True, default="", on_delete=models.CASCADE,) s = models.OneToOneField(S, null=False, default="", on_delete=models.CASCADE,) posted_date = models.DateTimeField(default=timezone.now) and generated tables like: Table C: id--------------name----------posted_date Table S: id--------------name----------posted_date Table CS: c_id-------------s_id----------posted_date I want to pass C.name to the template when input_str == S.slug. It should return a list of names. What I've tried in view.py so far: def listView(request, input_str): context = { 'inputs_list': C.objects.filter(slug=input_str).values('name') } return render(request, 'app/my_template.html', context) -
Django not displaying database items
I have created a project named Test and an app named testing inside this app. I have a model named ModelTesting in the testing app. This model has only one field named prop, which is a CharField of max_length=20. I can insert the items in database without any issue but cannot display them in the homepage. Take a look at my code. Here is my models.py from django.db import models # My Model class ModelTesting(models.Model): prop = models.CharField(max_length = 20) def __str__(self): return self.prop Here is my views.py from django.shortcuts import render from .models import ModelTesting # Loads Homepage def index(request): all_testing_models = ModelTesting.objects.all() params = {'all_models': all_testing_models} return render(request, "index.html", params) And here is the bootstrap template in which I want to display the items. Also, I have edited the template myself. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>The Properties are:-</h1> {% for test_model in all_testing_mdoels %} <h3>{{test_model.prop}}</h3> {% endfor %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" … -
How to add styles to Django model field's help_text in the generic views
I have a Django model where in I want to display help text as shown below: class StaffRoles(models.Model): role = models.CharField(primary_key=True, max_length=8, verbose_name="Role", help_text='Field accepts all uppercase only') role_short_text = models.CharField(max_length=35, verbose_name='Short Desc') role_long_text = models.CharField(max_length=250, verbose_name='Description') Now when I use the model in Django generic CreateView to add a new Role, the help text is displayed in the page in a default style just next to the input field role. What I am trying to do is to add some style to the help text being displayed, and to that end I tried to modify my template code as shown below: The template code: ... {% for field in form.visible_fields %} {% if field.name == "role" %} {{ field }} <small style="color:teal">{{ field.help_text|safe }}</small> {% endif %} {% endif %} However, to my dismay the help text is displayed twice - i.e. the resultant help text as a result of the new code line added, plus the text that was originally displayed. Is there a way I may display the help text with some css styles added? -
Set current time and date as default in django model
How can I set the default value as current date and time in a model? my model is : class StudUni(models.Model): student_id = models.IntegerField(blank=True, null=True) uni_name = models.CharField(max_length=55, blank=True, null=True) last_updated = models.DateTimeField(blank=True) -
How to filter Django forms field based on the values selected in other field?
I have a very simple Django form: from django import forms from django_select2.forms import Select2MultipleWidget class MyForm(forms.Form): countries = forms.MultipleChoiceField(widget=Select2MultipleWidget) cities = forms.MultipleChoiceField(widget=Select2MultipleWidget) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields["countries"].choices = self.get_countries() def get_countries(self): # returns list of countries based on some factors def get_cities(self): # returns list of cities based on the selected countries I'd like to populate cities field's choices based on the user selections in the countries field. Of course I want to avoid clicking button and reloading the whole page, so I suppose that the use of the JS/Ajax will be needed. I found some solutions but all of them are for Django Models' forms. Do you have any ideas how to solve this problem? -
Cannot find why tables cannot be renamed
What could be the cause of that issue: Applying django_orm.0002_rename_tables_...Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "." "fergo"."tb_kel" RENAME TO "fergo"."tb_kelo" "fergo"."tb_sa" RENAME TO "fergo"."tb_sartop" There is for sure not a typo or syntax error or something. This error appears for all tables which to be renamed. Any thoughts? -
JsonResponse incorrectly sending me to a new url
I'm getting a very odd error. I'm attempting to make a login form that will check to make sure the username/password combination is correctly. After taking in the username and password, the views.py function takes in the information and authenticates. If it turns out the username/password combo is no good, it should return blanks for the data = {"username": "", "pass":""} and returned to the ajax call which should then show a text error of "Username and Password combo is incorrect". When I put in a non existing email/username value or an incorrect password for an existing email/uername it will redirect me to an entirely new url ending in /login_user/ and displays {"username": "", "pass":""} as text in some new html file. Absolutely no idea why this is occurring, an error I'm getting in console is Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8000/rab/login_user". And the command prompt is giving error of this: [05/Aug/2020 11:15:54] "POST /rab/login_user HTTP/1.1" 200 28 Forbidden (CSRF token missing or incorrect.): /rab/login_user urls.py path('login_user', views.login_user, name='login_user'), login.js $(document).ready(function() { $("#login-btn").on("click", function(e){ var tk = $(this).attr("data-token"); let username = $("#login-username").val(); let pw = $("#login-pw").val(); let data = $(this).serialize(); $.ajax({ url: $('#log-form').attr("action"), type: 'POST', … -
AttributeError: 'str' object has no attribute 'name' While starting django server
I am trying to set up this codebase in MAC Its giving me an error when I try to run the server or do the migrations. I installed the requirements, I entered the shell but when i am running the migrations i am getting this. > File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap>", line 618, in _load_backward_compatible File "/Users/cdp/.local/share/virtualenvs/Upschool-lfJt5q5d/lib/python3.8/site-packages/configurations/importer.py", line 153, in load_module mod = imp.load_module(fullname, *self.location) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/imp.py", line 234, in load_module return load_source(name, filename, file) File "/usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/cdp/Documents/Code/Python/Upschool/upschool/settings.py", line 4, in <module> … -
Getting not InMemoryUploadedFile error while trying to upload image
I'm learning to upload image via form in django but getting error TypeError at /panel/add-news/ expected str, bytes or os.PathLike object, not InMemoryUploadedFile Not getting what i'm missing forms.html <form action="{%url 'add_news' %}" method="post" class="form-horizontal form-bordered" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-md-6"> <input type="text" id="newstitle" name="newstitle" class="form-control" placeholder="News Title" > </div> <div class="col-md-6"> <select id="example-chosen" id="newscat" name="newscat" class="select-chosen" data-placeholder="Category..." style="width: 250px;"> <option></option><!-- Required for data-placeholder attribute to work with Chosen plugin --> <option value="cat1">cat 1</option> <option value="cat2">cat 2</option> <option value="cat3">cat 3</option> </select> </div> </div> <div class="form-group"> <div class="col-md-12"> <textarea type="text" id="newstxtshort" name="newstxtshort" rows="5" class="form-control" placeholder="Short text"></textarea> </div> </div> <div class="form-group"> <div class="col-md-12"> <textarea type="text" id="newstxt" name="newstxt" rows="5" class="form-control" placeholder="Body text"></textarea> </div> </div> <div class="form-group"> <div class="col-md-12"> <input type="file" id="file" name="myfile" rows="5" class="form-control" placeholder="Body text"> </div> </div> <div class="form-group"> <div class="col-md-12"> <button type="submit" class="btn btn-sm btn-primary"><i class="fa fa-angle-right"></i> Submit</button> </div> </div> </form> path in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls in main/urls.py from django.contrib import admin from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # path(r"admin/", admin.site.urls), # path(r"", include('main.urls')) url(r"admin/", admin.site.urls), url(r"", include("main.urls")), url(r"", include("news.urls")), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Models.py: … -
programming error / and Error during template rendering
I uploaded the project on heroku in static format it was working properly..as soon as i rendered the images form the database it is working in the localhost but if i try to deploy it back to heroku this error shows up.I have made the migrations... -
Slugify self.title + random numbers
I hope you're well. I've two questions for you: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) url_image = models.URLField(max_length=200, default='SOME STRING') author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) name_site = models.CharField(max_length=200, default='NA') url_site = models.URLField(max_length=200, default='https://exemple.fr/') content = models.TextField() I. I want my title (unique=False) because I have some similar titles. So is it possible to save my slug (editable=False) with slugify with something like that: slug_str = "%s %s" % (self.title, 4 random numbers like that 0476) II. Is anyone has an idea about how I can remove the models default value? If anyone has a better idea, I'm interested in Thanks a lot :) have a good holidays and take care -
social_django extend token payload - customize claims
I am using simple JWT for users registered via page and customizing token´s payload like stated here. I am also using OAuth2 with social_django with google-oauth2. After OAuth2 login I am getting response from my server access: "ey...", refresh: "ey...", user: "user@gmail.com" I would like to extend the access token payload so that after decoding I get more information. Currently I have in payload: { "token_type": "access", "exp": number, "jti": "string", "user_id": 3 } User logging via Google gets different payload than the user logged in with his account created via Django registration. Is there a way to force social_django use simple JWT or to use pipes (?) to customize payload? I was trying to use AUTHENTICATION_BACKENDS and extending BaseOAuth and GoogleOAuth classes class CustomBaseOAuth(BaseOAuth2): def extra_data(self, user, uid, response, details=None, *args, **kwargs): """Return access_token, token_type, and extra defined names to store in extra_data field""" data = super(BaseOAuth2, self).extra_data(user, uid, response, details=details, *args, **kwargs) data['uuid'] = str(user.unique_id.hex) return data and it works but the extended information gets stuck in Database field so I am still stuck cause I want this information to be returned in token's payload. Thank you for any clues. -
extracting zip file and storing it to image or file field
in my django project i want a user to upload a epub file (basically a rar file) . i want to extract the epub file to get cover of that epub and save that to imagefield or a file field my idea is to extract a file using zipfile module as a binary data, but how to convert binary data to image field or binary field @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def create_book(request, *args, **kwargs): serializer = Book_serialzier( data=request.data, context={"user": request.user}) serializer.initial_data["title"] = serializer.initial_data.get( "book").name.split(".epub")[0] serializer.initial_data["user"] = request.user.id #here i started extracting with zipfile.ZipFile(serializer.initial_data.get("book"), 'r') as my_zip: if "cover.jpeg" in my_zip.namelist(): serializer.initial_data["cover"] = my_zip.read("cover.jpeg") if(serializer.is_valid(raise_exception=True)): book = serializer.save() return Response(serializer.data) -
Django Sign-in doesn't find registerd user when created with UserCreateForm
I have an FBV here, for an e-commerce website, I have two classes, Customer and ShippingAddress, and then the default user, def signup(request): if request.method == 'POST': user_form = forms.UserCreateForm(data=request.POST) shipping_form = forms.ShippingAddressCreateForm(data=request.POST) if user_form.is_valid() and shipping_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() customer = Customer.objects.create(user=user, name=user.username, email=user.email, is_authenticated=True) shipping_info = shipping_form.save(commit=False) shipping_info.customer = customer shipping_form.save() else: print(user_form.errors, shipping_form.errors) else: user_form = forms.UserCreateForm() shipping_form = forms.ShippingAddressCreateForm() # Function from utils.py data = cartData(request) cartitems = data['cartItems'] context_dict = {'form': user_form, 'shipping_form': shipping_form, 'cartitems': cartitems} return render(request, "accounts/signup.html", context_dict) Everything Works out fine when I go to the admin panel, I have a user, customer which links to the user and a ShippingAddress which links to the customer, all the details are fine as well and work as expected, the problem, however, is at the login, I'm using the LoginView to sign in, path('login/',auth_views.LoginView.as_view( template_name="accounts/login.html"), name='login'), But when I enter the details in, it says they are incorrect, even though I'm 100% they are, I tried manually handling the login with an FBV but the same problem occurs, I also found out that when I add an account from the admin page, or superuser from the terminal, then the login works fine, … -
Upload the project to the Debian10 server. Problems with supervisor
I'm deploying the django-gunicorn-supervisor app. When starting a project via gunicorn ( gunicorn quiz.wsgi:application --bind 64.227.71.171:8000) everything works, outputs the initial nginx page on the server's IP address. The first time supervisor was started, there was an error: FATAL Exited too quickly (process log may have details) it was reported in debug.log (Error: '/home/john/Quiz/quiz/config/gunicorn.config.py' doesn't exist), then I misspelled the path to gunicorn. Here is my corrected quiz.conf file: [program:quiz] command=/home/john/venv/bin/gunicorn quiz.wsgi:application -c /home/john/Quiz/quiz/config/gunicorn.conf.py directory=/home/john/Quiz/quiz user=john autorestart=true redirect_stderr=true stdout_logfile=/home/john/Quiz/quiz/logs/debug.log Now the error is fixed, and supervisor continues to spam the same error in debager. I restarted supervisor (restart, reload, stop+start), did reread+update, but it keeps giving the same error, describing it in the same way in the debagger. I even deleted and re-installed supervisor, but the error remains the same. How can I fix this??? -
How to index models in wagtail on azure search
I need to index my models on azure using the wagtail CMS platform. I have crud functionality written that hits the AZURE service, and can create indexes based on hard coded data. def createIndex(request): endpoint = 'https://service-test.search.windows.net/' api_version = '2020-06-30' url = endpoint + "indexes?api-version=" + api_version index_schema = { "name": "hotels-test", "fields": [ {"name": "HotelId", "type": "Edm.String", "key": "true", "filterable": "true"}, {"name": "HotelName", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "true", "facetable": "false"}, {"name": "Description", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "en.lucene"}, {"name": "Description_fr", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "fr.lucene"}, {"name": "Category", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Tags", "type": "Collection(Edm.String)", "searchable": "true", "filterable": "true", "sortable": "false", "facetable": "true"}, {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Rating", "type": "Edm.Double", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Address", "type": "Edm.ComplexType", "fields": [ {"name": "StreetAddress", "type": "Edm.String", "filterable": "false", "sortable": "false", "facetable": "false", "searchable": "true"}, {"name": "City", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "StateProvince", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "PostalCode", … -
django app has css code which does not format page as required
Trying to recreate a notes app on pythonanywhere. Link suggesting how it can be done gives output like this. Attempting same is here http://lastchance.pythonanywhere.com/notes/ How does one get notes as given in first image ? <link href="http://codepen.io/edbond88/pen/CcgvA.css" media="screen" rel="stylesheet" type="text/css"> <style> body {<br /> background: rgba(222,222,222,1);<br /> margin: 20px;<br /> }<br /> </style> <h1>Django Note Taking App</h1> <ul> {% for note in notes.all %} <li>{{ note.text }}</li> {% endfor %} </ul> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> -
Joining Querysets in Django and filtering afterwards
I have two querysets, q_1 and q_2 containing items from the same model m. I want to annotate both with the same variables but different values, q_1 = q_1.annotate(a=Value(True, output_field=BooleanField())), q_2 = q_2.annotate(a=Value(False, output_field=BooleanField())) Now I want to join both querysets to one queryset q, but want to be able to filter q afterwards. Using q = q_1.join(q_2) doesn't allow filtering afterwards. After using q = q_1 | q_2 all elements of q are annotated with a = True, although the elements of q_2 should have a =False. What can i do? Thanks in Advance!