Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dictionary as string in django template
I have a dictionary in this format: dict = [{ "key1": "value1" "key2": "value2" "key3": "{"name": "", "age": "", "sex": ""}" }, ] NOTE: key3 is a string holding a dictionary On the template I can actually pull key1, key2, key3 since they are straight forward. But, key3 is one more dictionary stored in string. I'm able to do this: {% for eachObj in dict%} { eachObj.key1 } { eachObj.key3 } <!-- This prints whole dictionary--> { eachObj.key3.name } <!-- This line doesn't work since it is a string --> {%endfor%} Is there some way where I can try doing like: JSON.parse(eachObj.key3) inside that for loop? -
Name is not editing after click on edit button . ( No errorr )
#Forms.py ( I have added the form for edit the user profile ) class CreateForm(forms.ModelForm): Full_name = forms.CharField(required=True) class Meta: model = Profile fields = ('Full_name') #Views.py ( edit_post is the view for edit user profile ) def edit_post(request): args = {} if request.method == 'POST': form = CreateForm(request.POST or None, instance=request.user) form.actual_user = request.user if form.is_valid(): Full_name = request.POST['Full_name'] form.save() return HttpResponseRedirect(reverse('mains:profiles')) else: form = CreateForm() context = {'form':form} return render(request, 'mains/edit_post.html' , context) #Urls.py ( edit_post url is the url of edit user profile ) path('edit_post/', views.edit_post, name='edit_post'), #Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='') Full_name = models.CharField(max_length=40,default='') email = models.EmailField(max_length=60,default='') #Edit_post.html {% extends "mains/base.html" %} {% block content %} <p><a herf="{% url 'mains:profiles' %}">Edit Profile</a> <form action="{% url 'mains:edit_post' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Edit Post"/> </form> {% endblock content %} -
HTML is there a way to limit the year to 4 digits in date input
I am developing a django app. I have date input in my form: <input type="date" name="date_of_birth" class="dateinput form-control" required id="id_date_of_birth"> It allows to enter the date with the year having 6 digits, but I wish it was only possible to enter 4. I tried max, max-length attribute with pattern. I also tried to write a simple script: $(function() { $('#id_date_of_birth').change(function() { var date = $(this).val(); console.log(date, 'change') }); }); but it only starts when I change the year. I would like the numbers to loop on 4 digits instead of 6. Can someone give me a hint how to limit the year to only 4 digits? -
Dynamic sitemap with paginated external content (API) of 1 million data
This question is not specific to my setup but I have a Nextjs app for frontend and Django app for backend. I want to create sitemap but when I fetch data from API it comes in the paginated form as usual. I can adjust the number of items in these API responses but I have ~1 million pages. So what's the approach to generate sitemap for this kind of large sites? -
How to pass selected value from dropdown in Django?
I have a combobox onchange of selection in need to load the field with list of items. I tried various method to pass the selected dropdown value to a method. I tried to call a javascript method in from datalist onChange event but it didn't work. how can we achieve this? I am tried for full day but unfortunately no luck. Model. CATEGORY_CHOICES = Choices( ('KtCoffee', 'Karnataka Coffee'), ('Atea', 'Assam tea'), ('WBRice', 'West Bengal Rice'), ('GujCotton', 'Gujarat Cotton'), ('KerCocoa', 'Kerala Cocoa'), ) class maincategory(models.Model): category = models.CharField(choices=CATEGORY_CHOICES,max_length=25) def __str__(self): return self.category VIEW def update(request): if request.method == "GET": context = { 'choices': maincategory._meta.get_field('category').choices } return render(request, 'update.html', context) HTML <div> <input list="category-input"> <datalist id="category-input" style="width:100px"> {% for des,text in choices %} <option value={{text}}>text</option> {% endfor %} </datalist> </div> -
how to merge my dataframe to models in django?
I am trying to put my dataframe into mysql database in my django project for two days but not able to do this. this is my views.py file from django.shortcuts import render, redirect from .models import App from .forms import AppForm from django.core.files.storage import FileSystemStorage import MySQLdb from pandas.io import sql con = MySQLdb.connect("localhost", "root", "1234", "djstudent" ) def list_app(request): app = App.objects.all() import pandas as pd data = [['tom', 10.0, 5], ['nick', 15.0, 3], ['juli', 14.0, 1]] df = pd.DataFrame(data, columns=['description', 'price', 'quantity']) df.to_sql(App, con=con, if_exists='replace') return render(request, 'app.html', {'app': app}) def create_app(request): form = AppForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form}) def update_app(request, id): app = App.objects.get(id=id) form = AppForm(request.POST or None, instance=app) if form.is_valid(): form.save() return redirect('list_app') return render(request, 'app-form.html', {'form': form, 'app': app}) def delete_app(request, id): app = App.objects.get(id=id) if request.method == 'POST': app.delete() return redirect('list_app') return render(request, 'app-delete-confirm.html', {'app': app}) this is my model.py file from django.db import models # Create your models here. class App(models.Model): description = models.CharField(max_length=100) price = models.DecimalField(max_digits=9,decimal_places=2) quantity = models.IntegerField() #media = models.FileField(upload_to='media', default="") def __str__(self): return self.description settingspy Django settings for crud1 project. Generated by 'django-admin startproject' using Django 2.2.2. … -
Why Django is encapsulating all the content inside the Body Tag
I have a problem that I am reproducing with a simple example. No matter what I do I do always have a page with my content inside a body (js, footer, etc) like the image attached. Can anyone help me to figure this out? Thank you. If I remove the body tag from base.html, django include a body tag itself that encapsulates the remaining content. base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %} {% endblock content %} </body> <footer> <h3>This is the footer</h3> </footer> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'bootstrap-4.4.1/js/bootstrap.min.js' %}" ></script> </html> home.html: {% extends 'base.html' %} {% block content %} <div> <h1>This is the home body</h1> </div> {% endblock content %} The render result: -
Use django filter in FullCalendar.io
I am making a fullcalendar in my Django project, and I want to use django filters to filter the calendar. I have successfully created the calendar and the filters, but I can't get it to work together. This is my latest error when using the filter in combination with the calendar. Does anyone have experience with including django filters (or another filtering approach) in a fullcalendar, or have a link to documentation that explains filtering in fullcalendar? -
Trying to deploy a second app on my linode server
I have an app running on my linode server, but since my app is not being used much and I have enough memory, I decided to host another app on same server but I have been unable to do so, I have tried so many tutorials online but I have not been successful with it. Please assist. Thanks in advance. -
Pagination and queryset
I have a queryset : items = Items.objects.all() category_query = request.POST.get('category) items = items.filter(category = category_query) I have a paginator : from django.core.paginator import Paginator paginator = Paginator(items, 18) page_query = request.GET.get('page') items = paginator.get_page(page_query) when I click on Next in the pagination it remove the active filter on my items. How can I avoid that ? -
how to change errors in Django rest framework like PK to ID
{ "status": 400, "errors": [ "designation Invalid pk "2" - object does not exist.", "provincedetails Invalid pk "10" - object does not exist." ] } I know why this errors is throwing because relation object is not exist so.. But I want to customize this error like to remove PK and add ID, is that possible to do? -
Show and hide elements in different tabs with JQuery
There are a few similar questions but not one that quite answers mine. I have a page with several different tabs, and a Django form with different filters as fields which is used in the template. The form fields 'west_region' and 'east_region' have different choices. I want to show a different filter depending on which tab is open. Can I use JQuery and the hash value to do this? This is my music.html template: {% block page-content %} <div class="card mb-4"> <div class="card-block"> <form class="ui-filter"> <div class="ui-filter--fields"> <!-- West region filter --> <div class="ui-filter--field" id="west-region"> <label for="supplier_elec">Region:</label> <div class="form-full-width">{{ form.west_region }}</div> </div> <!-- East region filter --> <div class="ui-filter--field" id="east-region"> <label for="supplier_gas">Region:</label> <div class="form-full-width">{{ form.east_region }}</div> </div> </div> <div class="ui-filter--submit"> <button class="btn btn-primary btn-block" type="submit">Apply Filters</button> </div> </form> </div> </div> <div class="row"> <div class="col"> <div class="tab-content content py-4"> <div class="tab-pane active container-fluid" id="jazz" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Jazz</h1> </div> </div> <h2>Songs</h2> {% include 'jazz.html' %} </div> <div class="tab-pane container-fluid" id="rock" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Rock</h1> </div> </div> <h2>Songs</h2> {% include 'rock.html' %} </div> </div> </div> </div> {% endblock %} {% block extrascripts %} <script> $('#music-genre a').click(function(e) { e.preventDefault(); $(this).tab('show'); }); $("ul.nav-tabs > … -
Python: CalledProcessError, command returned non-zero exit status 1
I am getting this error Command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned non-zero exit status 1. here is what I want to achieve. def get_queries(filename, num_queries=3): scored_chunks = [] absolute_file_path = os.path.join(settings.MEDIA_ROOT, filename) # pdf_to_text_output = subprocess.check_output([settings.PDF_TO_TEXT, "-layout", absolute_file_path, "-"], shell=true) pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) try: text = pdf_to_text_output.decode('utf-8') except UnicodeDecodeError: text = pdf_to_text_output.decode('ISO-8859-1') ....... I am new to Django and python, I have tried many solutions but nothing is working for me. because I don't know how it works. here is the full traceback. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/index/ Django Version: 3.1.2 Python Version: 3.7.4 Traceback (most recent call last): File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Farhana Noureen\plagtrap\main\views.py", line 302, in post results = process_homepage_trial(request) File "C:\Users\Farhana Noureen\plagtrap\main\services.py", line 435, in process_homepage_trial queries = pdf.get_queries(filename) File "C:\Users\Farhana Noureen\plagtrap\util\getqueriespertype\pdf.py", line 18, in get_queries pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 395, in check_output **kwargs).stdout File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 487, … -
Render React Static files with django
Hope you all are doing well I am trying to connect my react frontend to my django REST-API, which doesn't seem to go well at the moment, in the react development server the application is working quite well but as in terms while exporting its static files to django things seem to crash at the point. The following process was followed to achieve the goal run npm run build command to get the build directory within the react app. Copied and pasted the build/static directory to my BASE_DIR Changed my settings.py for the django project to the following STATIC_URL = '/static/' STATICFILE_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT= os.path.join(BASE_DIR,'static-root') and then finally running the command python manage.py collectstatic which copied over 160 files into my static-root directory. This is what my project structure looks like the collectstatic command doesn't seem to copy my react static files in spite the fact that I have mentioned that static directory which contains the react files. Which is the reason that I cannot access my react static files, any help on how to render the react files django or mistakes in my strategy while development would be highly appreciated. -
Download Uploaded Files in Django Admin Action
I am trying to create an admin action in django to download the selected files uploaded by the users. I can view the uploaded file one by one and use the save link as for saving the file/images. But I want to download more than one by selecting and save them to a zip folder for download in one go. I use this download users' pdf in django as reference and created the below code. I was able to download a zip file but when i opened it,it says the zip file is not valid. I believe there is something wrong with querying the file url/writing it to the zip folder. Please assist. import tempfile import zipfile def downloadPic(self, request, queryset): with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: for index, item in enumerate(queryset): projectUrl = str(item.file.url) + '' fileNameInZip = '%s.zip' % index archive.writestr(fileNameInZip, projectUrl) tmp.seek(0) response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename="pictures.zip"' return response -
Bootstrap4 HTML page is too big on mobile
I'm a relative noob with bootstrap and css. I've rebuilt this site from the ground up a couple times in the last couple of weeks to try and sort the spacing etc and currently I have the problem that the main section is slightly too big for a mobile screen in the x dimension and can be scrolled, which is obviously unwanted behaviour. I've tried so many configurations and am so confused as to where this apparent right margin is coming from. (The content fills the screen until you scroll leaving a significant sliver of background body colour. I've tried debugging by setting the background colour of different elements and the margin shows black with the body background, but white with main, i.e is between the body and the main. I have tried doing this in my css: html { overflow-y: scroll; overflow-x: hidden; // this solves the problem on a small browser window but not on mobile device. margin: 0; padding: 0; } body { margin: 0; padding: 0; } main { margin: 0; padding: 0; background-color: #000; // this is what i was referring to that leaves a white margin after scrolling if this color is in the … -
If date not in queryset add default value
Im integrating django with chartjs. I use classbasedview like below. class SingleTagChartJSONView(BaseLineOptionsChartView): def get_context_data(self, **kwargs): context = super(BaseLineChartView, self).get_context_data(**kwargs) date_year = int(str(context["year"])) date_month = int(str(context["month"])) specific_date = datetime(date_year, date_month, 1) obj_tags = mitop_tags.objects.filter( tag_publish_date__year=specific_date.year, tag_publish_date__month=specific_date.month, post_tag_single=str(context['tag'])).extra( {'day' : "date(tag_publish_date)"} ).values('day').annotate( tag_occur=Count('post_tag_single')) I get obj_tags output like this: {'day': datetime.date(2020, 10, 16), 'tag_occur': 3} {'day': datetime.date(2020, 10, 17), 'tag_occur': 3} {'day': datetime.date(2020, 10, 18), 'tag_occur': 1} {'day': datetime.date(2020, 10, 19), 'tag_occur': 2} {'day': datetime.date(2020, 10, 20), 'tag_occur': 1} {'day': datetime.date(2020, 10, 22), 'tag_occur': 6} {'day': datetime.date(2020, 10, 23), 'tag_occur': 8} {'day': datetime.date(2020, 10, 24), 'tag_occur': 8} {'day': datetime.date(2020, 10, 26), 'tag_occur': 8} {'day': datetime.date(2020, 10, 27), 'tag_occur': 6} {'day': datetime.date(2020, 10, 28), 'tag_occur': 6} {'day': datetime.date(2020, 10, 30), 'tag_occur': 3} {'day': datetime.date(2020, 10, 31), 'tag_occur': 7} I want to add default value for not existing date (record) in queryset. {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} In that case from 1-15 then missing 25 and 29. Desired output {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} {'day': datetime.date(2020, 10, 2), 'tag_occur': 0} {'day': datetime.date(2020, 10, 3), 'tag_occur': 0} {'day': datetime.date(2020, 10, 4), 'tag_occur': 0} {'day': datetime.date(2020, 10, 5), 'tag_occur': 0} {'day': datetime.date(2020, 10, 6), 'tag_occur': 0} {'day': datetime.date(2020, 10, 7), 'tag_occur': 0} {'day': datetime.date(2020, … -
For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions?
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project requires some database changes (unapplied migrations), and I'm using command python manage.py sqlmigrate to review the SQL statements. I have some questions, and any inputs will be highly appreciated: Some migrations, e.g. 0002_logentry_remove_auto_add below, SQL only contains comment, I'm wondering why. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate admin 0002_logentry_remove_auto_add BEGIN; -- -- Alter field action_time on logentry -- COMMIT; For migration 0002_auto_20160226_1747, SQL is the same for both forward and backward (--backwards) directions, and I'm also wondering 1) why, and 2) whether this should be a concern. Just want to be cautious with the production database, and thank you for your pointers. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate authtoken 0002_auto_20160226_1747 BEGIN; -- -- Change Meta options on token -- -- -- Alter field created on token -- -- -- Alter field key on token -- -- -- Alter field user on token -- ALTER TABLE `authtoken_token` DROP FOREIGN KEY `authtoken_token_user_id_535fb363_fk_auth_user_id`; ALTER TABLE `authtoken_token` ADD CONSTRAINT `authtoken_token_user_id_35299eff_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); COMMIT; (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate --backwards authtoken … -
Django queryset in multiple tables
I have this kind of query using PostgreSQL: SELECT tbl_project_lu.project_id, tbl_project_lu.house_id, tbl_project_lu.project_name AS project, tbl_house_lu.house_name, tbl_project_lu.description, tbl_house_mbr.person_id FROM ((tbl_house_lu INNER JOIN tbl_house_mbr ON tbl_house_lu.house_id = tbl_house_mbr.house_id) INNER JOIN tbl_project_lu ON tbl_house_lu.house_id = tbl_project_lu.house_id) INNER JOIN tbl_proj_mbr ON (tbl_project_lu.project_id = tbl_proj_mbr.project_id) AND (tbl_house_mbr.house_mbr_id = tbl_proj_mbr.house_mbr_id) WHERE person_id = 'foo'; What is the best way to use this kind of query in django? Can Django ORM handle this kind of query or do I have to use stored proc for this? -
Getting error after changed sqlite to mysql, table doesn't exist?
i've finished developing a django project and wanted to change sqlite3 to MySql for a better database option. I tried in an empty project to change database, it worked like a charm. But now i changed db of my project and when i try to do python manage.py makemigrations it returns; django.db.utils.ProgrammingError: (1146, "Table 'tvekstra-django-tracker.tvchannels_channels' doesn't exist") Any help is appreciated, thanks. -
How to get access to authenticated, logged in user in vue.js and django rest framework
I want to get access to authenticated, currently logged in user, eg. to username and id, and to put it in to the form by default when I'm using POST method. My login component: import axios from 'axios'; export default { name: 'LoginForm', components: { }, data(){ return{ username: '', password: '', token: localStorage.getItem('user-token') || null, } }, methods: { login(){ axios.post('http://127.0.0.1:8000/auth/',{ username: this.username, password: this.password, }) .then(resp => { this.token = resp.data.token; localStorage.setItem('user-token', resp.data.token) this.$router.push(this.$route.query.redirect || '/') }) .catch(err => { localStorage.removeItem('user-token') }) } } } </script> Could you help me? -
Setting up Domain on DigitalOcean to Django & Nginx
Finishing up site migration, I've been able to get it running on the droplet IP I've also checked if IP propagation is complete and I've added the domain to digitalocean When I try the domain I get This site can’t be reached. I've tried to set up the nginx file to match this server { listen 80; server_name http://safariguides.org 162.243.173.84 safariguides.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/webapps/kpsga; } location /media/ { root /home/sammy/webapps/kpsga; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and in the settings file DEBUG = True ALLOWED_HOSTS = [ 'http://safariguides.org', 'http://162.243.173.84/', '*' ] finally adding the * for maximum matches. checking for errors in nginx logs shows this sammy@kpsga:~/webapps/kpsga/kpsga$ sudo tail -F /var/log/nginx/error.log 2020/11/03 06:55:50 [warn] 70740#70740: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [alert] 70778#70778: *14 open socket #16 left in connection 9 2020/11/03 07:00:36 [alert] 70778#70778: *15 open socket #17 left in connection 10 2020/11/03 07:00:36 [alert] 70778#70778: aborting 2020/11/03 07:00:36 [warn] 70858#70858: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [warn] 70869#70869: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:04:34 [warn] 70893#70893: server name "http://safariguides.org" has suspicious … -
access database from dajngo views class
when I run my server,(in my website) in this case I get Error that is table not found. when I call this function in another class(not in views) it works! How can I solve this problem? `def calculate(request): vt =sql.connect('../db.sqlite3') imlec = vt.cursor() imlec.execute("SELECT pain from kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsa = imlec.fetchone() for i in idsa: i image_a = Image.open(str(i)) image_a_array = np.array(image_a) print("1.resim Array") print("*************************************************************************") print(image_a_array) imlec.execute("SELECT pain_two FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsb = imlec.fetchone() for i in idsb: i image_b = Image.open(str(i)) image_b_array = np.array(image_b) print("2.resim Array") print("*************************************************************************") print(image_b_array) imlec.execute("SELECT pain_three FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsc = imlec.fetchone() for i in idsc: i image_c = Image.open(str(i)) image_c_array = np.array(image_c) print("3.resim Array") print("*************************************************************************") print(image_c_array) imlec.execute("SELECT pain_four FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsd = imlec.fetchone() for i in idsd: i image_d = Image.open(str(i)) image_d_array = np.array(image_d) print("4.resim Array") print("*************************************************************************") print(image_d_array) return render(request,"anasayfa.html")` -
Which field in Django model to choose for a file downloaded via API endpoint?
I am using Django 2.2 LTS I have a function that will download a file from endpoint def download_as_file(url: str, auth=(), file_path="", attempts=2): """Downloads a URL content into a file (with large file support by streaming) :param url: URL to download :param auth: tuple containing credentials to access the url :param file_path: Local file name to contain the data downloaded :param attempts: Number of attempts :return: New file path. Empty string if the download failed """ if not file_path: file_path = os.path.realpath(os.path.basename(url)) logger.info(f"Downloading {url} content to {file_path}") url_sections = urlparse(url) if not url_sections.scheme: logger.debug("The given url is missing a scheme. Adding http scheme") url = f"https://{url}" logger.debug(f"New url: {url}") for attempt in range(1, attempts + 1): try: if attempt > 1: time.sleep(10) # 10 seconds wait time between downloads with requests.get(url, auth=auth, stream=True) as response: response.raise_for_status() with open(file_path, "wb") as out_file: for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB chunks out_file.write(chunk) logger.info("Download finished successfully") return (response, file_path) except Exception as ex: logger.error(f"Attempt #{attempt} failed with error: {ex}") return None I also intend to have a Django model to store metadata associated with that downloaded file. class DownloadedFile(models.Model): # other fields but i skipped most of them here local_copy = models.FileField(upload_to="downloads/") … -
Custom user creation form always invalid in Django
I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks My forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, regLinkModel): super(CustomUserCreationForm, self).__init__() self.linkInfo = regLinkModel def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['fname'] user.last_name = self.cleaned_data['lname'] user.password1 = self.cleaned_data['password1'] user.password2 = self.cleaned_data['password2'] if commit: user.save() return user My Models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password): if not email: raise ValueError("User needs email address") if not username: raise ValueError("User needs username") if not first_name: raise ValueError("User needs first name") if not last_name: raise ValueError("User needs last name") user = self.model( email=self.normalize_email(email), password = password, username =username, first_name = …