Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use paginator in Django?
I have a for loop and am trying to get a paginator to work. What code do I need with the buttons at the bottom of the html to get the pages to be split? {% for post in page.get_children|slice:":4" %} ... {% endfor %} <button class="">Previous</button> <button class="">Next »</button> I have tried this code below but the text isnt appearing? {% if page.get_children.has_next %} <a href="?page={{ page.get_children.next_page_number }}">next</a> <a href="?page={{ page.get_children.paginator.num_pages }}">last &raquo;</a> {% endif %} -
update model after another model updated django
i have 3 model CustomUser, Artist and UserProfile what i am trying to acheive here when user register its automatically created userprofile and artist and when i update userprofile its update the artist model custom user model class CustomUser(AbstractBaseUser, PermissionsMixin): artist_choice = [ (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ] artist_category = models.IntegerField(choices=artist_choice, null=True) email = models.EmailField(max_length=100, unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) #country = CountryField() USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) artist model class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return self.name custom user profile class UserProfile(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) user = models.OneToOneField(CustomUser, related_name='userprofile', on_delete= models.CASCADE) # email = models.EmailField(max_length=100, unique=True) image = models.FileField(upload_to=None, max_length=100) artist_category = models.IntegerField(choices= CHOICES, null=True) mobile_number = PhoneNumberField(null=True) country = CountryField(default = 'IN') city = models.CharField(blank=True, max_length=100) bio = models.TextField(blank=True) def __str__(self): return self.user.name creating userprofile … -
Django TestCase APIClient post request with vs Request package
When I use python's request package to post some data (to Amazon S3) which contains a dict consist of a file and some other string data, request package automatically sets the content-type to multipart/form-data. response=requests.post(data['url'],files=fields) This posts the file and it works great. But Because I am in Django I want to use APIClient or Client to do the same thing. First I tried this: awsclient= APIClient() content_type = 'multipart/form-data' response=awsclient.post(data['url'],data=fields,format=content_type) I get this error Invalid format 'multipart/form-data'. Available formats are 'multipart'. Set TEST_REQUEST_RENDERER_CLASSES to enable extra request formats. I could not find a lot of info on this. So I tried this awsclient= APIClient() content = encode_multipart('TestCaseBoundry', fields) content_type = 'multipart/form-data; boundary=TestCaseBoundry' response=awsclient.post(data['url'],content,content_type=content_type) which also does not work. I get a 404 error from the server. What are some of the ways to debug this Is it suppose to be field= or content_type= for 'multipart/form-data' How would you track down why this is happening ? WireShark? Is there a way to print the request headers of Client or ApiClient? I have written a javascript code which does the same post with XMLHttpRequest using FormData and that also uses multipart/form-data and it works great. Long story short I can just … -
storing and accessing users properly in django session
Here I am trying to store selected users in some django session and for this I have tried like this but while retrieving the users from session in another view I am getting empty queryset.How can i get the users which are stored in session in another django fucntion? storing selected users in session selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users')) initial = {'users':[]} session = request.session.get('users',initial) if selected_users: for user in selected_users: if not user in session['users']: session['users'].append(user.email) print(session['users']) here trying to retrieve these session's users in another view sess = request.session.get('users',{'users':[]}) users = get_user_model().objects.filter(pk__in=sess["users"]) print('sess',users) #didn't worked request.session['users'] # didn't worked either -
Django migrate after inspectdb - Problem with existing foreign key fields
For a mysql database (schema previously maintained from sqlalchemy orm), I have generated django models with the inspectdb management command. The models work fine, e.g. with relations usable from the admin views. That means I can choose related models for the foreign key form fields. The initial migration made with makemigrations look ok , but the foreign key fields are missing. The models at that point still have the meta class setting managed=False . After changing managed to True , the migrations want to create the foreign key fields. Even if the db_column is explicitly set (and, of course, that fields exists). That might look something like this. class SomeThing(models.Model): name = models.CharField(max_length=128, blank=True, null=True) mandant = models.ForeignKey( 'Owner', models.CASCADE, db_column='owner_id' ) When applying the migration, it errs because the field already exists. What is the best way to deal with this situation ? Why does django not get the foreign key fields in the first inspectdb step ? Is there a way to hint to the migration system that the field already exits? -
Django >> contrib/auth/models.py >> Templates ? Ar these the only templates >> django/forms/templates/django/forms/widgets
I have been searching for a while - my usecase is simple and common. Have to use "django_registration-redux" to give users a Register link . Format the HTML template enough , to make it presentable . The register form is being provided by - class AbstractUser within the file = django/contrib/auth/models.py . The templates being used are from DIR django/forms/templates/django/forms/widgets . Adding anything in here - say i add some HTML to the file input.html , does not give the desired results . Also adding formatted html within the file django/contrib/auth/models.py , in the class AbstractUser(AbstractBaseUser, PermissionsMixin): , also doesnt give desired results. I tried adding - help_text = format_html('<div style="color:grey;"> {} <strong><b>{}</b></strong> {}</div>', 'Username is a Required Field. Your UserName for' , 'DigitalCognition', 'can have max - 150 characters. You may use Letters, digits and @/./+/-/_ only.'). Finally my Question - Where to find the base.html or any kind of scaffolding templates for these widgets , i understand tinkering with these widgets is incorrect , thanks -
How can I display an image on a web page in django that is on my desktop?
I am loading data from postgresSQL database. This data is stored in the database by my python program. Not I am fetching data with the same functions I am using in my program. I want to create a bar chart before displaying it on my HTML webpage in Django. I created a chart using matplotlib and saved it on the desktop. Now I want to fetch that image and display it. I tried giving a link directly to that image but that doesn't load the picture. -
Django UnitTest KeyError Testing a "Standad" CreateForm
This is my Modell of which I want to UnitTest the CreateForm: And these are my UnitTests: This is the CreateForm: And Finally, the Console Output when I try to run the Test with: py -3 manage.py makemigrations -v3 py -3 manage.py migrate -v3 isort -rc . pmanage.py collectstatic --noinput -v3 py -3 manage.py test -v3 coverage3 run --source=catalog --omit=*migrations* manage.py test -v3 coverage3 report -m py -3 manage.py runserver -v3 This is the Console Output: Here are all the Images in Plain searchable copyable Text: models.py #!/usr/bin/python3 # -*- coding: utf-8 -*- import uuid from django.db import models from django.urls import reverse # Create your models here. class context(models.Model): """Model representing a context. (for example telba.de)""" CONTEXT = models.CharField(verbose_name='Kontext', primary_key=True, unique=True, max_length=200, help_text='') COUNTRYPREFIX = models.IntegerField(verbose_name='Ländervorwahl', help_text='') CITYPREFIX = models.IntegerField(verbose_name='Ortsvorwahl', help_text='') ROOTNUMBER = models.IntegerField(verbose_name='Nummer', help_text='') EXTENSIONSFROM = models.IntegerField(verbose_name='Nebenstellen von', help_text='') EXTENSIONSTILL = models.IntegerField(verbose_name='Nebenstellen bis', help_text='') PORTSCOUNT = models.IntegerField(verbose_name='Anzahl erlaubter Nebenstelen', help_text='') CALLPERMISSIONS_CHOICES = ( (u'0', u'WorldWide'), (u'1', u'Europe'), (u'2', u'National'), (u'3', u'None'), ) CALLPERMISSIONS = models.CharField(verbose_name='Anrufberechtigungen', max_length=1, choices=CALLPERMISSIONS_CHOICES, help_text='') def __str__(self): """String for representing the Model object context.""" return self.CONTEXT def get_absolute_url(self): """Model representing a context.""" return reverse('context-detail', args=[str(self.CONTEXT)]) forms.py class contextCreateForm(ModelForm): # def __init__(self, context, *args, **kwargs): def … -
Multi FormSet error "Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited"
modelformset_factory error "Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited." I want to create an dynamic form with multiple input fields add or remove using jQuery. But I got error when I try to run my code. I mentioned my code down please check and help me to solve this problem. Thanks I follow a tutorial and Github code. Here is link Youtube: https://www.youtube.com/watch?v=Tg6Ft_ZV19M Github code: https://github.com/shitalluitel/formset views.py def acc_journal(request): journalEntryFormset = modelformset_factory( AccountsJournalVoucherEntery, form=AccountsPymtVoucherForm) form = AccountJournalVoucherForm(request.POST or None) journalEntryset = journalEntryFormset( request.POST or None, queryset=AccountsJournalVoucherEntery.objects.none(), prefix='journalentries') if request.method == 'POST': if form.is_valid() and journalEntryset.is_valid(): try: with transaction.atomic(): journalvc = form.save(commit=False) journalvc.save() for journalEntry in journalEntryset: entery = journalEntry.save(commit=False) entery.journalvc = journalvc entery.save() except IntegrityError: print('Error Encountered') return redirect('accunts-journal') context = { 'acc_journal_acti': 'active', 'main_header': 'Accounts', 'header_heading': 'Journal', 'acc_journals': Accounts_journal_voucher.objects.all(), 'form': form, 'formset': journalEntryset } return render(request, 'accounts/journal.html', context) model.py class Accounts_journal_voucher(models.Model): journal_voucher_id = models.AutoField(primary_key=True) acc_jurnl_vc_num = models.CharField(max_length=50, blank=False) acc_jurnl_vc_loc = models.CharField(max_length=50, blank=False) acc_jurnl_vc_date = models.DateField(auto_now=False) acc_jurnl_vc_ref_num = models.CharField(max_length=50, blank=True) acc_jurnl_vc_total_debit = models.DecimalField( max_digits=30, decimal_places=2, blank=True, null=True) acc_jurnl_vc_total_credit = models.DecimalField( max_digits=30, decimal_places=2, blank=True, null=True) acc_jurnl_vc_info = models.TextField(blank=True) acc_jurnl_vc_added_by = models.CharField(max_length=200, blank=True) acc_jurnl_vc_date_added = models.DateTimeField( default=datetime.now, blank=True) def __str__(self): return self.acc_jurnl_vc_num class AccountsJournalVoucherEntery(models.Model): ajve_id = models.AutoField(primary_key=True) ajve_journal_vc = … -
How to format Django form with UIKit styling
I am struggling to see a way to style a django form in the style of a uikit horizontal form. UIKit has the styling I want and Django has the validation and templating I want.A way to implement a datepicker too would be useful. I have tried the plain django form template with .as_p and .as_table. I have also tried to use Meta and widgets but couldn't get that to work. I can't see how I can add the needed uikit tags to each element and add the uk-form-controls div. template.html <form class="uk-form-horizontal uk-margin-large uk-align-center"> <div class="uk-margin"> <label class="uk-form-label" for="form-horizontal-text">Job Title</label> <div class="uk-form-controls"> <input class="uk-input uk-form-width-large" id="form-horizontal-text" type="text" placeholder="Some text..."> </div> </div> forms.py class job_form(forms.Form): job_title = forms.CharField(label='Job Title', max_length=50) hiring_manager = forms.CharField(label='Hiring Manager', max_length=50) job_description = forms.CharField(label='Job Description', max_length=50) salary = forms.IntegerField() closing_date = forms.DateField() I am expecting to be able to have the uikit form styling with the templating and validation of django forms but am yet to get it to work. -
How to know which version of apps been used in django [duplicate]
This question already has an answer here: How can I get a list of locally installed Python modules? 27 answers I have been using django for my web project. I forgot to add requirements.txt file. Now I have already installed so many apps even third party apps. How do I know which version of apps I have been installed and their names? Comand line This is the comand line I used to know which apps been using in the django project but the thing is I can only get the few app names with this comand not the version. python manage.py makemigrations -
How can I get the worker address for Celery's app.control.broadcast
I wish to broadcast a panel command to a specific worker using app.control.broadcast, using the destination parameter. What exactly does the destination list expect as an address to a worker? And how can I get that address from the worker (which I know is an unusual request but is easiest for my workflow here.) -
I am learning django, how to change function to class in the views.py
How to change function to class in the views.py I want to change the view to something like this: https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/#createview class NewTopic(CreateView): model = Topic fields = ['title', 'category', 'author', 'text'] template_name = 'app_a/new_category.html' This is not correct, i want to modify it. models.py class Category(models.Model): title = models.CharField(max_length=200, default='') author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default=localtime) def __str__(self): return self.title class Topic(models.Model): title = models.CharField(max_length=200, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(default='') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title views.py def new_topic(request, pk): category = Category.objects.get(pk=pk) if request.method == 'POST': form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.author = request.user new_topic.category = category new_topic.save() form.save_m2m() return HttpResponseRedirect(reverse('app:category', args=[pk])) else: return render(request, 'app/index.html') context = {'category': category, 'form': form} return render(request, 'app/new_topic.html', context) forms.py class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['title', 'author'] class TopicForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea(attrs={"rows":5,'cols': 50})) class Meta: model = Topic fields = ['title', 'category', 'author', 'text'] urls.py urlpatterns = [ re_path(r'^new_topic/(?P<pk>\d+)/$', views.new_topic, name='new_topic'), ] I don't know how to modify it, thank you! -
how to make form Sub heading using django form
I want to make subfields in Django enter image description here -
Django after migration UndefinedColumn error in production
I have a website in production. I have an app, with a model. It contained a markdown_file attribute: markdown_file=models.FileField(upload_to='/media/') But since the number of file is limited, I decided to make it a markdown_filename attribute with a choices selection box: markdown_filename=models.CharField(max_length=30,null=True,blank=True,choices=MENU_MARKDOWN_FILE_CHOICES) Therefore, I modified this model and made migrations locally. I pushed the code in production and run: python manage.py migrate After I checked with showmigrations and sqlmigrate, that the modification I made were there. Then, I checked in the database, that the fields were correctly modified. But, I still get this error, when trying to access the website: ERROR:django.request:Internal Server Error: / Traceback (most recent call last): File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column showcase_subpage.markdown_file does not exist LINE 1: ...bpage"."slug", "showcase_subpage"."html_content", "showcase_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./showcase/views.py", line 10, in home return render(request, 'showcase/home.html', context) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/srv/data/web/vhosts/default/local/lib/python3.7/site-packages/django/template/loader.py", line … -
Trying to display loop on new line python
I am trying to get the following code to output to a new line each time. However, when I view on the webpage, it doesn't output as expected. I have tried \n and || in the code if (form.getvalue("username")=="$username"): self.wfile.write("Table: Users \n") self.wfile.write("Username | Password\n") self.wfile.write("test") Output: Table: Users Username|Password test I don,t receive any errors -
Django URL Page error when link is clicked twice
I have a url defined as: path("home/projects/",project_view,name = "viewProject") This render correctly when i click on the 'Details' link on project_view.html <li> <a href="projects" data-toggle="tooltip" class="tip-bottom" title="All Projects"> <i class="fa fa-list" aria-hidden="true">Details</i></a> </li> But while i am on the same page,if i click the same link again i get an error: home/projects/ [name='viewProject'] "Page not found...The current path, home/projects/projects, didn't match any of these" I understand what the error means,but how can i redirect the page to "home/projects/" if the link is clicked twice? -
Performing two actions with one form in django
Here I am trying to perform two actions deleting or sending email to selected users.For sending emails a form will be required so I stored checked users in a session like this and after sending email i am removing all the users from session with session['users'].clear(). But neither it throws any errors nor it sends the email it just renders the send_mail_selected template. What's wrong with this code? Deleting the selected users working fine def selected_users(request): form = SendMailForm() selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users')) initial = {'users':[]} session = request.session.get('users',initial) if selected_users: for user in selected_users: if not user in session['users']: session['users'].append(user.email) print('hello1',session['users']) if selected_users and request.method == 'POST' and 'delete_selected' in request.POST: count = selected_users.count() selected_users.delete() messages.success(request, '{} users deleted.'.format(count)) return redirect('view_users') elif request.method == 'POST' and 'mail_selected' in request.POST: form = SendMailForm(request.POST or None) config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] for email in session['users']: email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[email], connection=backend) email.send() # clearing users from session after email sends session['users'].clear() messages.success(request, 'Your mail sent.') return redirect('view_users') else: print(form.errors) return render(request, 'send_mail_selected.html', {'users': selected_users,'form':form,'session':session}) -
Frontend and backend languages
I'm currently planificating a web development for statistical analysis of big data of social media. I'm looking for some advice for good frontend and backend languages. For backend i'm pretty sure i'll use Django, because python has a great capability for big data analysis but i'm lost in frontend languages. I've seen some people that recommend going with JS, some people just stick to Django. Can you please give me some advice on this frontend languages, in which case should i use it and why? -
Generating multiple objects with random start and end dates which NEVER overlap?
I'm creating 20 random objects for my fixtures like this: EVENT_TYPE = [ 'A', 'B', 'C', ] for _ in range(20): start_date = get_random_date(date(date.today().year, 1, 1), now()) Event.objects.create( category=random.choice(EVENT_TYPE), start=start_date, end=get_random_date(start_date, start_date + timedelta(days=180)), ) What I want to do: having 20 objects with "unique" date ranges. For example Object1 starts at 01.01.2019 and ends at 10.01.2019 and has an EVENT_TYPE of "A". So no other object created should have a date range between those two dates with the same EVENT_TYPE. They can have a start date at 10.01.2019 or an end date at 01.01.2019, but never something between those dates. BUT as you can see my objects also have categories, which split them, so if obj1 and obj2 have the same date range, but a different EVENT_TYPE thats totally okay. Right now my code does that totally random. I tried to figure out a way to achieve that, but just couldn't come up with a smart idea. Does someone know a clever solution to this problem? How could I check if one object is in between the date range of another and let say just change its date to the beginning or end of that object so that it … -
Django import: Ignore created value from TimeStampedModel
I have a model which is inherited from TimeStampedModel and I am trying to import data using Django import_export. The imported data contains "created" column providing the datetime values which are different from current date time. The import is successful but it is using the created value from TimeStampedModel rather that the one from the file. Is there anything that can be done in the import_obj function to override the created value from the TimeStampedModel? The format of date time in the file is in the expected format and is one of the supported formats. class TestResource(resources.ModelResource): class Meta: model = MyModel def import_obj(self, obj, data, dry_run): for field in self.get_fields(): self.import_field(field, obj, data) Object creation date is always the current datetime rather than the datetime in the imported file. -
rest_framework.exceptions.ParseError: JSON parse error - Invalid control character
I'm trying to create a decrypting API. But when i pass a encrypted data as string it return this error. However if i escape the next line characters it will work. This is the non-formatted message, and i can expect it only in this format. (Details changed) { "passphrase": "not_passphrase", "message": "-----BEGIN PGP MESSAGE----- Version: GnuPG v2 jA0ECQMCVady3XMDJV3X0kcBF+zdkfZOMhISoYBRwR3uk3vNv+TEg+rJnp4/yYIS pEoI2S82cDiCNBIVAYWB8WKPtH2R2YSussKhpSJ4mFgqyOA01uwroA== =KvJQ -----END PGP MESSAGE-----" } I am using Django Rest framework. I'm not that deeply familiar with the settings process. I've done up a lot of reading including STRICT_JSON and UNICODE however i was not able to achieve a working solution. Any guidance is appreciated. -
Convert request.get and request.post data to dictionary
I'm trying to convert request.GET and request.POST to dictionary I tried doing request.GET.dict() and json.dumps(request.GET). somehow it returns dict like structure. for eg: {'name': 'abc'}, but type of this dict is str -
Django multiprocessing database concurrency
I am stuck with the following database concurrency problem. I am building a django webapp using psycopg2 to comunicate with a PostgreSQL database. The queries are run from different processes. In order to lock rows all the queries are inside a transaction atomic block. with transaction.atomic(): self.analysis_obj = Analysis.objects.select_for_update().get(pk=self.analysis_id) However sometimes I get random error like: 'no results to fetch', 'pop from empty list', 'error with status PGRES_TUPLES_OK and no message from the libpq'. Any idea to deal with this problem? Many thanks. -
when i click a images then show 3 images on other html page but these 3 images is different for every clicked images
i want to access related class object through value class because img field of value class relates with 3 images of related class by Foreign Key this is my models.py class value(models.Model): img = models.ImageField(upload_to='images/') price = models.IntegerField() class related(models.Model): u_id = models.ForeignKey(value,on_delete=models.CASCADE) image=models.ImageField(upload_to='images/') loc = models.CharField(max_length=20) this my views.py def home(request): rels = value.objects return render(request,'rel/home.html',{'rels':rels}) def detail(request,id): det = get_object_or_404(value,pk=id) det1 = det.id u_id = related.objects.get() return render(request,'rel/detail.html',{'det':det,'u_id':u_id}) this my html page {% for u in u_id.all %} <div class="container"> <img src="{{ u_id.image.url }}" alt=""> </div> {% endfor %} get() returned more than one related -- it returned 3! (on browser window ) i want that when i click a image which is available on my home.html then show 3 images on other html page but condition is that these 3 images is different for every images which is available on home.html