Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert fob to tiff in python3
I need to convert the fob file to tiff file in python. I tried with the following code. But it is not working. Could you please anyone guide me to do this task in python. from PIL import Image img = Image.open('/Users/administrator/Desktop/367069291_1.FOB').convert('RGB') img.save('sample.tiff', format='TIFF', compression='tiff_lzw') I am getting this error: raise IOError("cannot identify image file %r" % (filename if filename else fp)) OSError: cannot identify image file '/Users/administrator/Desktop/367069291_1.FOB' -
Django bulk creation: too many terms in compound SELECT
So I am trying to generate a lot of data to test my database and I am using the following statement to generate ItemLists: for __ in range(0, 1000): list_cache = [] for __ in range(0, 10000): list_cache.append(ItemList()) ItemList.objects.bulk_create(list_cache, ignore_conflicts=True) When I try to execute the code the error django.db.utils.OperationalError: too many terms in compound SELECT shows up. It originates from the last line of the code sample. I found that when I move the list_cache outside of both for loops and only call the bulk_create once, it works fine. But as a one million line statement isn't optimal, I tried to split it into smaller batches, as you can see. -
Django - Stuck On Creating a Pricing System
I am making a "booking airbnb" website. On my apartment detail page I have a JQuery UI Date Picker calendar which the user uses to put in start and end dates of the reservation. Once that is done and the user submits the form I want to refresh the site, and when refreshed display the dates the user picked, as long with price per day and total price. In my models I have created: models.py: class Apartment(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) apartment_price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) size = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class ApartmentImages(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="image") image = models.ImageField("image") def __str__(self): return self.image.url class ApartmentPrices(models.Model): apartment = models.ForeignKey(Apartment, on_delete="models.CASCADE", related_name="price") price_start_date = models.DateField(blank=True, null=True) price_end_date = models.DateField(blank=True, null=True) price = models.IntegerField() def __str__(self): return self.apartment.title class Reservation(models.Model): apartment = models.ForeignKey(Apartment, related_name='reservations', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) name = models.CharField(default="", max_length=200) def __str__(self): return self.name this is what I have in my view so far. I have tried many different things, but … -
how to fix the 'django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library'
I am trying to store location of stores in my django database, i tried installing geodjango for the purpose which gives me the above error. i have installed python postgresql osgeow psycopg2 also modified the envirenment variables as per geodjango documentation i tried installing gdal manually using -http://www.gisinternals.com/query.html?content=filelist&file=release-1911-x64-gdal-2-2-3-mapserver-7-0-7.zip the generic core components my settings.py file- import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] INSTALLED_APPS = [ ... 'django.contrib.gis', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'services', 'USER': '*******', 'HOST': 'localhost', 'PASSWORD': '******', 'PORT': '5434', } when i run python manage.py check it gives me the error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. i have already set the gdal ibrary path to gdal data directory, it still isn't working. Please help with whatever's wrong above. Also suggest if there is any other way to store locations in django database? -
How to wait for the twilio callback until it changes from TBD to the actual price?
I am trying to wait for the callback after the price is generated because it comes back as None and my model is Float field, so it throws a value error(ValueError: could not convert string to float: 'one'). To counter this, I thought of using the sleep function. Unfortunately, it did not work when I asked the callback to sleep for 10 sec, so to be safe I asked the callback to sleep for 80 sec. Doing this I realised that Twilio has a timeout of 10 sec, so I got an error(11205 HTTP connection failure) How do I fix this? views.py @login_required def start_campaign(request, campaign_id): # send_campaign.apply_async(args[]) try: campaign = Campaign.objects.get(pk=campaign_id) campaign.status = 'started' campaign.save() account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) phone_numbers = Contact.objects.filter(phone_book=campaign.phone_book) xml_url = 'http://XXX.ngrok.io/call-center/assets/' + str(campaign_id) callback_url = 'http://XXX.ngrok.io/call-center/events/' + str(campaign_id) for phone_number in phone_numbers: call = client.calls.create( method='GET', status_callback=str(callback_url), status_callback_event='completed', status_callback_method='GET', url=xml_url, to=str(phone_number), from_='+1XXX' ) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'all_campaigns': campaign } return render(request, "CallCenter/start_campaign.html", context) def events(request, campaign_id): time.sleep(80) campaign = Campaign.objects.get(pk=campaign_id) campaign.status = 'completed' campaign.save() account_sid = 'XXX' auth_token = 'XXX' client = Client(account_sid, auth_token) sid = request.GET.get('CallSid', default=None) detail = client.calls(sid).fetch() check … -
Incorporating Recaptcha Email Form Into Existing Django Project
I would like to incorporate an email form with Google Recaptcha similar or identical to this: https://github.com/maru/django-contact-form-recaptcha Into this existing django github project: https://github.com/justdjango/video-membership Where a website visitor could send emails to a Gmail account that I own directly from the form. I edited the code from the video membership github project to include a contact page for this purpose. How can this be accomplished? video-membership-master/courses/urls.py: from django.urls import path from .views import ContactPageView app_name = 'courses' urlpatterns = [ path('contact/', ContactPageView.as_view(), name='contact') ] video-membership-master/courses/views.py from django.views.generic import TemplateView class ContactPageView(TemplateView): template_name = 'contact.html' video-membership-master/courses/templates/contact.html: {% extends 'courses/base.html' %} {% block content %} <h1>Contact</h1> {% endblock %} -
Is there a way to add class in my html element in Django using forms?
I want to add a class attribute in my template but my code doesn't work. I have already tried the other answers from Stackoverflow but none of these worked for me. class LoginForm(forms.ModelForm): class Meta: model = User fields = ['username','password'] def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={ 'id': 'id_username', 'class': 'input', 'placeholder': 'Enter username'}) The output have no changes at all. -
Nginx can access static folder but not other folders inside it. Throws sub-folder/index.html is not found
I am trying to deploy my django app on google cloud platform. I am using nginx and gunicorn. I am following this guide - https://medium.com/@_christopher/deploying-my-django-app-to-a-real-server-part-ii-f0c277c338f4. I have created a file - le_website - under the folder sites-available. This is the code - ''' server { listen 80; server_name 10.xxx.x.x; location = /favicon.ico {access_log off;log_not_found off;} location = /static/ { root /home/jainpriyanshu1991/learnEarn/le-webiste; } location = / { include proxy_params; proxy_pass http://unix:/home/jainpriyanshu1991/learnEarn/le-webiste/le_website.sock; } } When I try the url myIPaddress/static/ , it works and shows the folders inside it. But it does not work for any subfolder within static. It gives "/usr/share/nginx/html/static/img/index.html" is not found for img folder inside static. Similarly, when I try the url myIPaddress/ it opens the homepage of website but again, it does not work for any other link and gives error. For about page it gives error "/usr/share/nginx/html/about" failed (2: No such file or directory). -
How to create a save method in an abstract model that checks whether an instance exists?
I have the following models: class PlaceMixin(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) sublocality = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) class Bar(PlaceMixin): pass class Restaurant(PlaceMixin): pass Bar and Restaurant have almost same save() method: def save(self, *args, **kwargs): try: bar = Bar.objects.get(id_google=self.id_google) except Bar.DoesNotExist: Do something super().save(*args, **kwargs) def save(self, *args, **kwargs): try: restaurant = Restaurant.objects.get(id_google=self.id_google) except Restaurant.DoesNotExist: Do something super().save(*args, **kwargs) I was wondering if I can put the method in the Abstract model and pass it to the two inherited model? def save(self, *args, **kwargs): try: temp = self.objects.get(id_google=self.id_google) except self.DoesNotExist: Do something super().save(*args, **kwargs) Something like this? But you can query in an abstract model. I basically need to check if an instance exists for executing an action. -
assertRaises won't raise ValidationError
When testing an ImageField with an invalid file passed to it, Django is asserting that no ValidationError is being raised. This is being done in a with self.assertRaises context. However, when I access form.errors.as_data() it shows that a ValidationError is technically being raised. I'm not clear on what is happening. #tests.py from django.core.exceptions import ValidationError class SubmitProfileForm(TestCase): @classmethod def setUpTestData(cls): cls.data = { 'email': 'test@email.com', 'birth':'2019-01-01', 'coding_level': 'Hobbyist', 'bio': 'About me...', 'github': 'http://www.github.com', } cls.image = open(join(dirname(__file__), 'images/test_file.txt'), 'rb') cls.file = { 'avatar': SimpleUploadedFile( name=cls.image.name, content=cls.image.read() ) } def test_invalid_file_uploaded(self): with self.assertRaises(ValidationError): form = ProfileForm(self.data, self.file) form.errors print(form.errors.as_data()) # forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ( 'email', 'birth', 'coding_level', 'bio', 'github', 'avatar' ) # models.py class Profile(models.Model): hobby = "Hobbyist" develop = "Developer" coding_level = ( (hobby, hobby), (develop, develop) ) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) email = models.EmailField() birth = models.DateField(verbose_name="Date Of Birth") coding_level = models.CharField( verbose_name="Experience", max_length=20, choices=coding_level, default=hobby, blank=False ) bio = models.TextField( verbose_name="User Bio", validators=[MinLengthValidator(10, message="Add more to your bio!")] ) github = models.URLField( verbose_name="GitHub link", validators=[check_submitted_link], unique=True ) avatar = models.ImageField(upload_to="images/%Y/%m/%d/") Actual result: print(form.errors.as_data()) '''{'avatar': [ValidationError(['Upload a valid image. The file you uploaded was either not an image or a … -
Trouble understanding axios error handling in react
I am learning about react and django. I have installed django-rest-auth to handle account creations and authentication for users. I also wanted to learn about react and I have install axios to make http request to my django rest api. I want to have a "splash" page where users would first access the site. If the user is already logged in they'll see their profile and other content. If the user isn't logged in they should be presented a login page. Here's my App.js code I have so far. import React, { useState, useEffect } from 'react'; import axios from 'axios'; import logo from './logo.svg'; import './App.css'; function LoginPage(props) { console.log('LoginPage props are:'); console.log({ props }); return (<div className="LoginPage">props are: {props}</div>) } function SplashPage(props) { const [currentUser, setCurrentUser] = useState(null); console.log('SplashPage props are:'); console.log({ props }); const userUrl = 'http://localhost:8000/rest-auth/user/'; console.log('userUrl is:' + userUrl); axios.get(userUrl) .then(res => { setCurrentUser(res.data); }) .catch((error) => { console.log(error.response); return (<div><LoginPage /></div>); }) return (<div className="SplashPage">[{userUrl}] [{currentUser}] </div>); } function App() { return ( <div> <SplashPage /> </div> ); } export default App; Heres my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker … -
How to change the value of an attribute in another class when performing a Post Django
I am making a Sale where with a Foreignkey I obtain an order by selecting it, this order has a status of "Pending", what I want is that when making a sale with all the necessary data entered, store those values in the database and at the same time update the order status value, which is in another table. This is my Sale Model: class Venta(models.Model): fecha = models.DateField(default=datetime.now, null=True, blank=True) pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) total = models.CharField(max_length=200, default=1) cliente = models.CharField(max_length=100) nit = models.CharField(max_length=10) def get_absolute_url(self): return reverse('control:venta-detail', args=[str(self.id)]) def __str__(self): return str(self.id) Order Model: class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') def get_absolute_url(self): return reverse('control:pedido-detail', args=[str(self.id)]) def __str__(self): return str(self.id) and the View to create a new Sale: class VentaCreate(CreateView): model = Venta form_class = VentaForm success_url = reverse_lazy('control:ventas') template_name_suffix = '_crear' @method_decorator(permission_required('control.add_venta',reverse_lazy('control:ventas'))) def dispatch(self, *args, **kwargs): return super(VentaCreate, self).dispatch(*args, **kwargs) And in what I have investigated in my view I tried this: def estado_pedido(request, pk): pedido = get_object_or_404(Pedido, pk=pk) if request.method=='POST': pedido.estado = "Finalizado" pedido.save() But I don't know how to pass the id of the selected Order, and I don't know what I should "return" -
Please help me with my dilema - Did I miss some valuable info or my employer wanted too much on Python Junior interview?
Here is some non-tech question from newbie Python programmer. So today I did first try to take a job. Employer called me and started first interview. He asked some basic questions like whats a difference between list and set etc., But then he asked me how actually Float type works in Python. He meant not like how float() method work but how actually Python stores and handle float variable "under the hood". I couldnt anwser that because I have never met such info and never even had a clue to learn that. And immidiately I got rejected. Btw I use Python almost everyday along with Java. I do undarstand all basics and OOP stuff, including some of patterns. I do have three crossplatform projects on Python/Kivy, who use internet sync, Pusher and openCV API, so I guess Im not total noob here. So my question to you guys - is that me missing some valuable info or my employer asked a hard question for a Junior programmer? Thank you for you attention. Please if you know what am I missing please hit me with it right in my face -, its really important for me :) -
How to create multiple graph by json element in d3.js
I am trying to generate multiple graph by each json element's name with d3. I think I could use plain javascript array filter function but I'm not entirely sure on how to implement that. So I have https://i.imgur.com/X4AFyfD.png but I want something like https://i.imgur.com/kmqfWDr.png where each graph is a selected event. I thought about making multiple table in my database for each events but I think its better to work with large data rather than multiple smaller ones. I've read https://medium.com/turo-engineering/react-meets-d3-6a40881d0d73 but I'm not sure if I can apply it to my project. This is also running django and react and using webpack. scatterPlot.js file import * as d3 from 'd3'; (function() { var margin = { top: 20, right: 20, bottom: 30, left: 40 }, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var xValue = function(d) { return d.bweight; }, xScale = d3.scaleLinear().range([0, width]), // value -> display xMap = function(d) { return xScale(xValue(d)); }, xAxis = d3.axisTop(xScale); var yValue = function(d) { return d['total']; }, yScale = d3.scaleLinear().range([height, 0]), // value -> display yMap = function(d) { return yScale(yValue(d)); }, yAxis = d3.axisLeft(yScale); var cValue = function(d) { return d.event; }, … -
Gmail + Django SMTP: "smtplib.SMTPServerDisconnected: Connection unexpectedly closed"
When following this I receive this error smtplib.SMTPServerDisconnected: Connection unexpectedly closed , and I notice none of my Django SMTP requests are working? I enabled insecure applications on my Google account already. Please help. -
Using property of related object to dynamically produce argument for ImageField
I have a model called Image that has a foreign key to another model, Tag. I want to dynamically generate the upload_to argument for the ImageField. Here is the Tag model: class Tag(models.Model): ... @property def image_path(self): # joins the hierarchy as a relative path from media folder # ['doberman', 'dog', 'animal', 'null'] --> 'images/animal/dog/doberman/' return '/'.join(['images'] + self.tag_hierarchy[-2::-1]) + '/' ... And the Image model class Image(models.Model): featured_tag = models.ForeignKey( to=Tag, null=False, blank=True, default=get_object_or_404(Tag, name='null'), on_delete=models.CASCADE ) image = models.ImageField( # I want to access the object directly and obtain the path upload_to=featured_tag.image_path # AttributeError: 'ForeignKey' object has no attribute 'image_path' ) ... How would I dynamically generate the path for the upload_to argument? -
How to make recursive django admin inline relationships
I need to create an arbitrarily deep modular structure using Django admin. The nested_admin package has gotten me part of the way there, but there's a key piece of functionality that's still eluding me — the ability to create an object B inline off object A and then create another object A off that instance of object B. Here's a closer look at my models (simplified): class ChatConditional(models.Model): triggering_question = models.ForeignKey( 'texts.MessageChain', on_delete=models.CASCADE, ) keyword = models.CharField(max_length=50, blank=False, null=False) keyword_response = models.ForeignKey( 'texts.MessageChain', related_name='keyword_answer', on_delete=models.CASCADE, ) class MessageChain(models.Model): conditional_trigger = models.ForeignKey( 'texts.ChatConditional', blank=True, null=True, ) message = models.TextField(max_length=160, blank=True, null=True) So in the admin, I want to be able to create a ChatConditional to serve as a response to a certain MessageChain. Then once I create that Conditional, create another MessageChain to send that will potentially link to another Conditional. Here's what my admin models look like: class SMSConditionalAdmin(nested_admin.NestedStackedInline): model = ChatConditional extra = 0 fk_name = "trigger" inlines = [SMSChainAdmin] class SMSChainAdmin(nested_admin.NestedStackedInline): model = MessageChain extra = 0 inlines = [SMSMessageAdmin, SMSConditionalAdmin] And now you can likely see the problem: In order to fully define the SMSConditionalAdmin, I need to set up an inline relationship to SMSChainAdmin, and vice … -
Running Django unittests on PostgreSQL
I'm trying to switchover a Django unittest suite to use PostgreSQL as its backend. Changing the Django test settings was finally trivial, but now I'm getting a lot of subtle errors when the tests load fixtures. After hours of tinkering, I found the problem was because Django's not resetting the id counters on the tables, so even though all rows are deleting from each table between tests, all new fixtures don't use the Id's in the fixture but instead us an Id that's 1 plus the maximum Id used in the last test. Very frustrating. So I dug through the code to see why this was happening, and if it was a bug in my usage of Django 2.2, and I found the django.test.TransactionTestCase even has a nifty little _reset_sequences() method for resetting all table sequences between tests. However, I'm using the standard django.test.TestCase, and for some reason, in the _fixture_setup() method, it explicitly disables _reset_sequences() and assert an error: AssertionError: reset_sequences cannot be used on TestCase instances if you try to call it. Why is this? As is, Django's failing to reset table counters, and is breaking my unittests. Why can't table sequences be reset in the standard TestCase? -
DJango data migration not creating and deleting records
I have an application that manages services as a platform. A Customer has many Programs. A Code has Foreign Keys Customer and Program. They both can be null. I need to create a copy of each Code-with-no-program for each Program and delete the former afterwards. So with that in mind currently I am running this migration: # Generated by Django 2.2.4 on 2019-10-17 18:29 from django.db import migrations def code_update_program(apps, schema_editor): Code = apps.get_model("projects", "Code") Program = apps.get_model("projects", "Program") Customer = apps.get_model("customers", "Customer") db_alias = schema_editor.connection.alias for customer in Customer.objects.all(): old_codes = Code.objects.using(db_alias).filter(customer=customer, program=None) for program in Program.objects.filter(customer=customer): Code.objects.using(db_alias).bulk_create( [ Code( program=program, customer=customer, key=c.key, value=c.value, description=c.description, ) for c in old_codes ] ) old_codes.delete() class Migration(migrations.Migration): dependencies = [ ("projects", "0048_project_program_add_related_query_name"), ("customers", "0032_customer_plan_refactor"), ] operations = [migrations.RunPython(code_update_program)] ./manage.py migrate will do everything successfully, but when I verify the state of my data, the data is still the same! So it's not working. Any pointers are kindly appreciated. -
Link to child to parent in Django model
I have a Place Model: class Place(models.Model): name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) sublocality = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) admin_area = models.CharField(max_length=100, null=True, blank=True) country = models.CharField(max_length=100, null=True, blank=True) postal_code = models.CharField(max_length=100, null=True, blank=True) region = models.CharField(max_length=1000, choices=REGION, null=True, blank=True) longitude = models.CharField(max_length=20, null=True, blank=True) latitude = models.CharField(max_length=20, null=True, blank=True) id_google = models.CharField(max_length=200, null=True, blank=True) website = models.CharField(max_length=2000, null=True, blank=True) icon = models.CharField(max_length=200, null=True, blank=True) adr_address = models.CharField(max_length=500, null=True, blank=True) date_created = models.DateTimeField(_('date created'), default=timezone.now) date_modified = models.DateTimeField(_('date_modified'), auto_now=True) Originally I create place to save information about a city, like San Francisco or New York. Now I want to create a new model called Bar: class Bar(Place): location = models.OneToOneField(Place, verbose_name=_('location'), related_name='bar', blank=True, on_delete=models.PROTECT, parent_link=True) date_inception = models.DateField(null=True, blank=True) date_closed = models.DateField(null=True, blank=True) I would like to link the bar to a particular city in the Place model. So I'm linking one row of the an inherited model with its parent. Can I avoid creating a city model and the Bar should Foreignkey into? Is this doable? If so, how do I do it? -
Receiving error when trying to instal Heroku packages
When I am trying to install the required packages for deploying my project (Learning Log) to Heroku, it keeps giving me this error: Josephs-MacBook-Pro:learning_log joseph$ source ll_env/bin/activate (ll_env) Josephs-MacBook-Pro:learning_log joseph$ pip install psycopg2==2.7.* DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Collecting psycopg2==2.7.* Downloading https://files.pythonhosted.org/packages/c2/a0/ba2c28c13bce130f971158da8fc03c231ce7778a89935eb1c3e3e6437e7c/psycopg2-2.7.7-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (1.5MB) |████████████████████████████████| 1.5MB 1.3MB/s Installing collected packages: psycopg2 ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/psycopg2-2.7.7.dist-info' Consider using the `--user` option or check the permissions. (ll_env) Josephs-MacBook-Pro:learning_log joseph$ -m pip install psycopg2==2.7.* -bash: -m: command not found I don't know why it keeps saying python 2.7 as I downloaded python3 and have been using it the whole time. Also when I tried running the server yesterday for Learning Log it would not work (it was running fine before). I eventually re-downloaded python3 bootstrap4 and django(in the environment) and got run server to work. side note: I have to type the 3 at the end of python3 … -
How to add another 'Add +' button with custom URL in Django Admin
I have a model list page in /admin of my Django project. On the top right corner, there is a button to add a new object. I wish to create a new button right next to it, which takes me to my custom form. How can this be done? "Add Category +" on the top right corner I have tried editing overriding Django Admin Templates No success there. -
Django Crispy Form - Populate For after submit
I'm building a django app. I'm trying to re-populate the form after submit with the same submitted data. I'm using crispy form. It's not working. Below is my code. I would really appreciate any help. # models.py class Group(models.Model): group_name = models.CharField(max_length=220) group_location = models.CharField(max_length=220) # forms.py class CreateGroup(forms.Form): group_name = forms.CharField(label='Group Name', widget=forms.TextInput(attrs={'placeholder': 'Group Name'})) group_location = forms.CharField(label='Group Location', widget=forms.Textarea(), required=False) # views.py def create_group(request): title = "Create New Group" if request.method == 'POST': form = CreateGroup(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, 'create_group.html', {'title': title, 'form':CreateGroup, 'form_data': form.cleaned_data}) else: form = CreateGroup return render(request, 'create_group.html', {'form': form, 'title': title}) # create_group.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block body_content %} <div class="container-fluid"> <form action="/creategroup/" method="post" id="post-form"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4 mb-0"> {{ form.group_name|as_crispy_field }} {{ form.group_location|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Create Group</button> </form> </div> {% endblock %} -
How to create a DRF API to return all possible field choices available along with User list as dict
I am creating an API using DRF, and I want to send a JSONResponse which will contain a list of all users (from django User model) and available choices for few fields as a dict. I tried to create a GenericAPIView with queryset of all active users and in serializer I tried to return the field choices and list of users but the result contains field options along with each user object. I want to keep all users data under key "user_list" and field options under "field1_choices", "field2_choices". GenericAPIView: class TicketPropertiesView(generics.GenericAPIView): authentication_classes = [ CsrfExemptSessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] serializer_class = TicketPropertiesSerializer def get(self, *args, **kwargs): serializer = TicketPropertiesSerializer(data = User.objects.filter(is_active = True), many = True) serializer.is_valid() return JsonResponse(serializer.data, safe = False) Serializer: class UserPropertiesSerializer(serializers.ModelSerializer): user_list = serializers.SerializerMethodField() field_1_choices = serializers.SerializerMethodField() field_2_choices = serializers.SerializerMethodField() FIELD_1_MAP = FIELD_1_CHOICES FIELD_2_MAP = FIELD_2_CHOICES def get_user_list(self, obj): queryset = User.objects.filter(is_active = True) user = [] for obj in queryset: user.append({ "id": obj.id, "username": obj.username, "first_name": obj.first_name }) return user def get_field_1_choices(self, *args): field1_choices = [] for i in self.FIELD_1_MAP: field1_choices.append({"id": i[0], "choice": i[1]}) return field1_choices def get_field_2_choices(self, *args): field2_choices = [] for i in self.FIELD_2_MAP: field2_choices.append({"id": i[0], "choice": i[1]}) return field2_choices class Meta: model … -
Django ChromeDriver Disable Downloads
I am using Selenium and ChromeDriver in a Django application. When I navigate to a particular page it downloads a file(that I don't want). When the browser runs with the head it saves files to my downloads folder. When it runs headless it downloads files to the project folder(same level as manage.py). I want to navigate to the page, but not make any downloads. I looked at the documentation: https://cs.chromium.org/chromium/src/chrome/common/pref_names.cc?l=38 https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup And a handful of posts on SO. It's still downloading the file. How do I stop it? Is this a chromedriver issue or a Django issue? scrape.py options = webdriver.ChromeOptions() options.add_argument('headless') driver = webdriver.Chrome(options=options) prefs = {"profile.default_content_settings.popups": 2, "download_restrictions": 3, "profile.default_content_setting_values.automatic_downloads": 1, "safebrowsing.enabled" : True } options.add_experimental_option("prefs", prefs)