Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get absolute url displays link to current page
I'm using get a class based List view. I have got the queryset in my view and passed it to my template. I want users to click the name of the property and be sent to the details view. Models.py class Property(ModelWithFlag): name = models.CharField(max_length=50) def get_absolute_url(self): return reverse('view-listing', kwargs={'slug': self.slug}) Views.py class PropertyListView(generic.ListView): model = Property def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['no_footer'] = True context['property_list'] = self.get_queryset() return context property_list.html {% for instance in property_list %} <a href=" {{instnce.get_absolute_url}} " > {{instance.name}} </a> {% endfor %} -
How to order coordinates with Mongoengine?
I'm working with Django and Mongoengine, I use GeoJson coordinates and I have to sort a coordinate list closest to the farthest, I have a starting point but I want to know if mongoengine can order those coordinates and what is the way to do it. -
How to prevent PyCharm debugger from restarting on code changes?
While debugging in PyCharm with a Django project, if I add a break point, and then edit a line of code, let's say something simple like x = 2, the debugger will automatically terminate and restart. Is there a way to prevent this? Obviously a restart is needed to rerun code, but it would be nice to walk through break points and add code as I go without starting from the beginning. -
How do I make form entries mirror eachother?
Hi so I am working with angular2 javascript for my django app and I was wondering if there was any way that I could make my two form entries mirror eachother? This is what I have so far: <input class="form-control" ng-model="price_level.price_point[1].edit_price_per_case" name="price_per_case1" type="text" min="0" ng-pattern="/^[0-9]*(\.[0-9]{1,2})?$/" required style="width: 65px;"> <span ng-show="price_level.edit"> <input class="form-control" type="text" min="0" ng-pattern="/^[0-9]*(\.[0-9]{1,2})?$/" name="price_per_case0" ng-model="price_level.price_point[0].edit_price_per_case" ng-required='price_level.edit' style="width: 65px;"> </span> I would like it so that when I enter the top input it auto fills the bottom input or even vice versa. -
Override django user with AUTH_USER_MODEL
I have override the default User model in my app with AUTH_USER_MODEL. Here is the user model I want to use in my app, which is tied closely to a legacy database: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): name = models.CharField(max_length=128, blank=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) normalized_email = models.EmailField(unique=True) However, django complains that fields such as first_name, last_name, etc. are not provided. Is there a way to remove some of the existing fields in the User model? Or does specifying a custom user model only allow you to add additional fields on top of that? Is there a simple way to delete them, or do I basically have to add those fields (and ignore them) in order to use the django User? -
Django template variable not recognized in script tag but recognized in regular h1 tag. what could cause that?
<script> var my_data = {{ passed_data }} </script> <body> <h1>{{ passed_data }}</h1> </body> This is the basic idea behind the code. I suspect it may be a scope issue -
Django + VueJS + RestAPI Based Project Guideline
Hello Devs :) WHO I'M & WHAT I WANT TO ACHIEVE ? I'm teen boy working on an Open Source Project (now, it's just in my pc), this project is my dream project & i'm working on this from months. Basically this is sort of Social Media Platform but not exactly a Social Media, it's for Creators & Professionals of Art, Tech, Writing, Journalism etc fields. It's just rough idea basically want to clear on which kind of project i'm working. PROGRESS I complete the design section using HTML5, CSS3, Bootstrap4, little JS Core, little JQuery. REMAINING Now the Backend part, in past i worked in PHP alot, but now i want to work in something new and interesting, so i choose, Python Django, but here i know that there is something called SPA & Front-End JS Framework (basically i know about it but never worked in it, but in JS, i did), which gives me a push and interest to learn and work in, i searched alot and finally choose VueJS, because it's lightweight and easy to learn & work. I learned that both Backend & Frontend would be separate and will be connected using RestAPI, which i found … -
Django Pass Model Field as Parameter to URL Stored in Another Model
I have three models: class Entity(models.Model): entity = models.CharField(primary_key=True, max_length=25) class Report(models.Model): report = models.CharField(max_length=50) report_link = models.CharField(max_length=300) class Item(models.Model): entities = models.ManyToManyField(Entity, related_name='entities') report = models.ForeginKey(Report) A view is built off of the Item model: def activity_list(request): items = Item.objects.select_related('report').prefetch_related('entities') return render(request, 'items/item_list.html', {'items':items}) This view gets routed to a template: {% for item in items %} <tr> <td> {% for entity in item.entities.all %} {{ entity }}{% if not forloop.last %}, {% endif %} {% endfor %} </td> <td>{{ item.report }}</td> <td>{{ item.report.report_link|urlize }}</td> </tr> {% endfor %} This line (<td>{{ item.report.report_link|urlize }}</td>) manifests like this in the browser: https://server.domain/reports/specificReport?entity= How would I pass the entities into the URL to filter the report? The desired result would look like this: https://server.domain/reports/specificReport?entity=12345 ...or if there are multiple entities for one item: https://server.domain/reports/specificReport?entity=12345,56789 Each report in the Report model has a link, but the link does not necessarily take the entity parameter, so it wouldn't be ideal to globally change all links (i.e. through jQuery or some other JS). However, there is JS running on this page, so it is possible to use that...although I think a Django option might be best. One thing I've thought about is adding an … -
Django - Migration doesn't work and strange error
I'm new to django. I'm trying to create a custom user model but everytime I try to migrate I get a strange error. Maybe you can help me. Here are my files: models.py: from django.db import models from django.contrib.auth.models import User from datetime import date, datetime class User(models.Model): username = models.CharField(max_length=31, unique=True) first_name = models.CharField(max_length=31, unique=True) last_name = models.CharField(max_length=31, unique=True) password = models.CharField(max_length=1023) email = models.CharField(max_length=255, unique=True, primary_key=True) typeOfPerson = models.CharField(max_length=15, default="G") birth_date = models.DateField() registration_date = models.DateTimeField( #default=str(date.today()) + " " + str(datetime.now()) auto_now_add=True ) ip_address = models.CharField(max_length=31, blank=True) classNumber = models.CharField(max_length=2, blank=True) shortName = models.CharField(max_length=3, blank=True) rank = models.CharField(max_length=15, default="Normal") forms.py: from django import forms from .models import User from django.contrib.auth.hashers import make_password class SignUpForm(forms.ModelForm): typeOfPerson = forms.ChoiceField(label="Was bist du?", required=True, choices=( ("S", "Schüler"), ("L", "Lehrer"), ("E", "Elternteil"), ("G", "Gast"), ), widget=forms.Select(attrs={ "id": "select", })) username = forms.CharField(max_length=31, min_length=3, required=True, widget=forms.TextInput(attrs={ "placeholder": "Benutzername", "id": "username", })) first_name = forms.CharField(max_length=31, min_length=3, required=True, widget=forms.TextInput(attrs={ "placeholder": "Vorname", "id": "name", })) last_name = forms.CharField(max_length=31, min_length=2, required=True, widget=forms.TextInput(attrs={ "placeholder": "Nachname", "id": "surname", })) email = forms.EmailField(max_length=255, min_length=6, required=True, widget=forms.TextInput(attrs={ "placeholder": "E-Mail", "id": "email", })) birth_date = forms.DateField(label="Geburtsdatum", required=True, widget=forms.DateInput(attrs={ "id": "date", "type": "date" })) classNumber = forms.IntegerField(max_value=13, min_value=5, required=False, widget=forms.NumberInput(attrs={ "placeholder": "Klassenstufe", "id": … -
Segmentation fault when database is there
I am using django2.1 and trying to set up a local mysql connection. The database is local and on, however I run into a Segmentation Fault error whenever trying to connect: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'file', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } I know these settings are valid because I'm currently connecting to the same db with the same django settings in another app (using django 1.4). Django==2.1.2 mysqlclient==1.3.13 pytz==2018.5 The strange thing is, it does show a valid mysql error if I try and connect to the wrong db: django.db.utils.OperationalError: (1049, "Unknown database 'bad-database'") But if I enter in the correct db, it gives me this error: Segmentation fault: 11 Is there a way to fix this? -
Django - Stripe subscription
i have a view that use stripe to charge amount and then redirect the user to subscription page but how i can prevent user form access the url directly Charge view : def testview(request): charge = stripe.Charge.create( amount=2000, currency="usd", source="tok_visa", # obtained with Stripe.js description="Charge for jenny.rosen@example.com" ) return render(request, 'test.html') My subscription view: def create_sub(request): plan1 = "plan_DiiAhydC7AxqeG" plan2 = "plan_DiiAypModfV7VJ" plan = request.GET.get('plan') if plan == '1': active_plan = plan1 elif plan == '2': active_plan = plan2 sub = stripe.Subscription.create( customer=request.user.stripe_id, items=[ { "plan": active_plan, }, ] ) My html charge template: <form action="/test/create-sub?plan=2" method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="stripe_api_code" data-amount="100000" data-name="Bilpard" data-description="Paid plan" data-image="https://stripe.com/img/documentation/checkout/marketplace.png" data-locale="auto"> </script> </form> -
Django template is not rendering vuejs components even if vue js files are injected
I am trying to inject vuejs components inside my django's base template, but unfortunately, the components are not getting rendered. Even though necessary vuejs js files are there. So, I am injecting the vuejs build's files app.js, manifest.js and vendor.js inside base.html (django template). I created a vuejs component named article-list in ArticleList.vue file. The problem is inside django's template, I am not being able to access this component. It is rather rendered as html tag inside template. The files are given below: base.html: <body> <header> {% include 'backend/nav.html' %} </header> <div id="app"> {% block content %} {# Use this block for loading CONTENT files from other html files which extend this base.html #} {% endblock content %} </div> <footer> {% include 'backend/footer.html' %} </footer> <script src="{% static 'dist/js/app.js' %}" async></script> <script src="{% static 'dist/js/manifest.js' %}" async></script> <script src="{% static 'dist/js/vendor.js' %}" async></script> {% block js %} {# Use this block for loading JS files from other html files which extend this base.html #} {% endblock js %} </body> home.html: {% extends "backend/base.html" %} {% block title %}Home{% endblock title %} {% block content %} <h3>Vue Js component Below:</h3> <article-list> </article-list> {# NOT GETTING RENDERED#} {% endblock content %} App.vue: … -
Django, How to update the DateTimeField() of model by the view
As mentioned in the title, I have a model containing the DateTimeField() models.py class DataRow(models.Model): last_edit_date = models.DateTimeField(default=datetime.now()) I would like to update this field every time I call the model in view. I tried to do it as follows: views.py data_row = get_object_or_404(DataRow, pk=row_id) data_row.last_edit_date = datetime.now() data_row.save() I also checked the auto_add=True attribute and calling the .save() method of model, but it did not work either. -
Override JSON data in Django RestFramwork
Right now with the current Views functions I am getting the data given below: {"item": "zxmnb", "category": "zxc", "price": "zxc", "restaurant": 1} Here is my views file: class RestaurantMenuView(generics.RetrieveAPIView): lookup_field = 'item' serializer_class = MenuSerializer def get_queryset(self): return Menu.objects.all() But the issue is I want the data to be in a format as: "restaurant": "name"{ "item":"some item" "category": "some category" "price": "some price" } I want to mention that Restaurant is another model in my models class,Now I know that if I use restaurant I will only get the pk. But what I want is the JSON to be displayed like that. -
Accessing foreign key values in django ListView of GCBV
I have two models related by a Foreign key as follows. (Only shown important fields here.) in model: class Category(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField() ... class Price(models.Model): category = models.ForeignKey(Category) # referred to above model sub_type = models.CharField(max_length=4, choices=CHOICE_SUB_TYPE) price = models.DecimalField() ... I'm going to display Categories in a ListView along with related pricing details. In order do that, I need to set related pricing objects for each Category object. What is the best and efficient way to do this? -
Django settings are not configured
I just uninstalled python 3.6 and installed python 3.7 and as i install django into a virtual environment and then type django-admin it brings out this error. Note that only Django core commands are listed as settings are not properly configured(error: Requested setting INSTALLED_APPS, but settings are not configured.You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). then when i try django-admin runserver it shows django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured.You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Python Django tables with checkbox delete option
I am new to Django and currently trying to display a table with a checkbox which displays the list of records from the database and would have a delete button to delete multiple records using checkbox. How to display a table with checkbox and delete button? Appreciate your help! Here is my code related to it: models.py class Customer(TimeStamp): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100,blank=True,help_text="Long-form name (optional)") comments = models.TextField(blank=True) class Meta: ordering = ['-id'] def __str__(self): return self.name def get_absolute_url(self): return reverse('App_CUS:customer_list') views.py class CustomerListView(ListView): queryset = Customer.objects.order_by('id') model = Customer paginate_by = 10 context_object_name = 'customers' template_name = 'App_CUS/customer_list.html' customer_list.html customer_list.html: {% extends 'index.html' %} {% load buttons %} {% block content %} <div class="pull-right"> {% if perms.App_CUS.customer_add %} {% add_button 'App_CUS:customer_add' %} {% delete_button 'App_CUS:customer_delete' %} {% endif %} </div> <h1>{% block title %}Customers{% endblock %}</h1> <div class="col-md-9"> <div class="table-responsive"> <table class="table table-hover table-headings table-bordered"> <thead> <tr> <th class="pk"> <input class="toggle" title="Toggle all" type="checkbox"> </th> <th>ID</th> <th>Customer Name</th> <th>Description</th> </tr> </thead> <tbody> {% for customer in customers %} <tr> <th class="pk"> <input class="toggle" title="Toggle all" type="checkbox"> </th> <td>{{ customer.pk }}</td> <td>{{ customer.name }}</td> <td>{{ customer.description }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> -
How to install google cloud sdk on python 3.5.2
I am following the guide to install google cloud sdk. But when I use the statement from google.appengine.ext import ndb I get an error no module named google.apengine.ext. I think it is due to my google cloud sdk not being installed in Python 3.5. So my question is that how to install that package in Python 3.5. Is there a possibility to install it in virtual env? -
GraphQL on AWS lambda: The request could not be satisfied. How to solve 403 error?
I have deployed an GraphQL API to AWS Lambda using the Zappa Framework. If I do a request from my local machine to the local server version like this everything works fine: import requests url = 'http://127.0.0.1:8000/graphql' token = '...' headers = {'Authorization': 'JWT '+token} query = { 'query' : '{ ...} r = requests.get(url=url, json=query, headers=headers) print (r.text) If I do the same request to my AWS URL https://xyz.execute-api.eu-central-1.amazonaws.com/production/graphql it yields the following error: <H1>403 ERROR</H1> <H2>The request could not be satisfied.</H2> <HR noshade size="1px"> Bad request. <BR clear="all"> <HR noshade size="1px"> <PRE> Generated by cloudfront (CloudFront) It should be noted that the GraphiQL view works properly under the mentioned AWS URL where I can do my queries without any problems. Am I missing something to get it going from other devices machine to machine? Cheers! -
SendGrid Django Template tags returning HTTP Error 400: Bad Request
Having an annoying issue. I am using Django to send data to sendGrid templates. But when I add substitutions I get a HTTP Error 400: Bad Request. If I dont add anything in the dictionary it works just fine emailing the template as expected. So I am sure the problem is in the tag format and I cant seem to find the correct combenation Python def emailSendGrid(self): mail = EmailMultiAlternatives( subject="Your Subject from sendGrid", body="SendGrid sent This is a simple text email body.", from_email="anon@test, to=["dude@test"], headers={"Reply-To": "anon@test"} ) # Add template mail.template_id = '#######################' # Replace substitutions in sendgrid template mail.substitutions = {'%testTag%': 'new content from Django'} fail_silently = False mail.send() SendGrid Template <html> <head> <title></title> </head> <body> <h3>This is a test email template from sendGrid</h3> <p> -testTag- </p> </body> </html> This should be really simple but I have tried so my combinations and googled it with no resolve. -
How to pass a request object threw all middlewares? [Django]
I want to call a view inside another view. For that I'm creating an request object and then passing to the view function but I need to populate that request object with a lot of info from the middlewares. My question is how can I pass a request object that I instantiated threw all middlewares and then pass it to the view I want? fn, args, kwargs = resolve(kwargs.get('url')) request = HttpRequest() # pass threw middlewares fn(request) -
inlineformset_factory choices not set correctly when using django-schemas
I have created an inlineformset_factory, but when I implement the Post method on my view the system mentioned that my inline form is not valid. After some debugging I found out that the choices that are in one of my inlineformset_factory fields are not accurate, this happens because I'm using django-schemas. for some reason when the inlineformset_factory is defined, it uses the public schemas and not the tenant schema, which makes the choices in my inlineformset_factory field incorrect. Note: The model that uses the inlineformset_factory has 2 Foreign Key 1 with the Configuration Object and the other with User, the issue occurs with the User. Here is the code that I have model.py class Configuration(Control): uuid = kp.ObjectIDField() name = kp.ObjectNameField() description = kp.ObjectDescriptionField() class ConfigurationMember(models.Model): uuid = kp.ObjectIDField() user = models.ForeignKey(User, on_delete=models.CASCADE) owner = models.BooleanField(default=False) configuration = models.ForeignKey(Configuration, on_delete=models.CASCADE) forms.py MemberFormSet = inlineformset_factory(Configuration, ConfigurationMember, fk_name='forecastConfiguration', fields=['user', 'owner'], can_delete=False, extra=3) View.py class ConfigurationCreateView(CreateView): model = Configuration form_class = ConfigurationCreateForm template_name = 'frontend/base/config_create.html' object = None # success_url = '' def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) member_formset … -
inserting iframe in django doesn't work on chrome
I'm trying to insert iframe in website https://vroombaby.com I added iframe in html in django 2.1.0 <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=vroombaby-20&marketplace=amazon&region=US&placement=B07H1N53F3&asins=B07H1N53F3&linkId=292eb0a8248b860392e16c503d33cdb8&show_border=true&link_opens_in_new_window=true&price_color=333333&title_color=0066c0&bg_color=ffffff"> </iframe> It displays properly under Buy on firefox but doesn't display on chrome. Any pointers. I tried adding in settings.py `X_FRAME_OPTIONS = 'ALLOW-FROM //ws-na.amazon-adsystem.com/' but doesn't seem to work. -
How to deal with awk commas using paramiko on Django?
stdout = session.exec_command('''find . -name "{}*" -type f -exec stat -c "%n %y" {} + | awk "{ print $1" "$2 }" | grep -v colegio''' .format(VARIABLE1, VARIABLE2)) I'm doing this code using paramiko 2.4 on Django 1.9.13, don't know how to deal with it, the error is: KeyError at /get_xml/index/ ' print $1" "$2 ' -
Django: Get the detail object inside Change_form template
from the Django change_form.html template. I would like to re-structure the default tabular display of the page. Its an invoice and I therefor need to render the page as invoice page. In order to do this I need the hold of the object storing the details for the page. If this was for change_list.html template, I could have accessed the object by iterating through cl.result_list like so {% for object in cl.result_list %} <tr> <td>{{ object.invoice_number }}</td> <td>{{ object.payment_type }}</td> <td>{{ object.billed_to }}</td> <td>{{ object.total_cost }}</td> <td>sup</td> </tr> {% endfor %} Similarly I want to access the obj in the change_form.html so that I can call the field name and get its value like object.invoice_number. Please any ideas on how to proceed? Thanks