Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add multiple table rows by one submission in Django
Here is my Html input which have same name input for all rows with different values <input type="text" class="form-control" name="name" value="Name1"> <input type="text" class="form-control" name="name" value="Name2"> <input type="text" class="form-control" name="name" value="Name3"> <input type="text" class="form-control" name="name" value="Name4"> <input type="text" class="form-control" name="name" value="Name5"> <input type="text" class="form-control" name="name" value="Name6"> Here's my view after the form is submitted records must be added to multiple rows NOT IN ONE ROW if request.method == 'POST': names = request.POST.getlist('name') for name in names: Test( name= name ).save() return HttpResponse('success') I tried this method but it only saves one row of the last value. -
How to get the page number of a particular object in Django Rest Framework pagination?
How can we send an id of a particular object in the url and get the page number of where that object exists? I'm using Django Rest Framework as my project backend and I have enabled pagination in order to get a list of items. Now I need to send the item id in the url and get the corresponding page where that item belongs. Can I do this with Django Rest Framework... My front-end is React JS. Any answer would be great! Thank you! -
Is there possibility to connect django webapp to hadoop
i am trying to connect my django webapplication to hadoop(as data source), but i am unable to do so. Can someone tell me is there possibility to connect webapp to hadoop as data source. -
How can I get API error response in desired format?
This is how i am getting the error messages. By default, i am getting 'serializer.errors' as dictionary of list and i want them in list of dictionary format -
How can I solve this python problem?[django]
Why cannot I migrate. It says assertion error. Here is the pic # Create your models here. class Product(models.Model): product_id= models.AutoField() product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="" ) subcategory = models.CharField(max_length=50, default="" ) price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.product_name -
Django static files working from template but not from CSS file
I am just getting back into Django, and I have a new project set up here in the development server. I set up static files and I have been able to load the files from the templates however when the files are accessed via CSS there is a 404 error. Here is how the image is accessed in CSS: background-image: linear-gradient(rgba(206, 27, 40, 0.25), rgba(206, 27, 40, 0.25)), url(../images/cta01.jpg); The 404 error in the browser is looking in the staic/images/ folder but his location is not being served. I know this static file thing is always tricky butt I don't remember it being such as issue before. What am I doing wrong? Here is the settings file and main URL file. Also I tried to use whitenoise and it seems to be working but same behavior: static files load in templates but not from CSS. settings.py """ Django settings for tmx_intranet project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # … -
Modifications in Django admin after pen test
We have performed a pen test on django admin module using a paid online tool as suggested by our client. It has raised a red flag for a chance of XSS attack in the user groups query. I have tried manually injecting java script in the query. It was accepting script but not executing. But I need to prove technically it was safe from XSS attack. Can someone help me with this? -
I have formset ignoring all attributes
forms.py class DocumentForm(ModelForm): prefix = 'document' document = FileField( required=True, widget=FileInput(attrs={ 'accept': '.xls,.xlsx,.csv', 'aria-label': 'File Upload', 'class': 'form-control' }) ) header = IntegerField( required=True, label='헤더 행# (첫 행=0)', widget=NumberInput(attrs={ 'class': 'form-control', 'min': 0, 'value': 0 }) ) class Meta: model = Document fields = ['document', 'header'] exclude = ['description', 'uploaded_at'] DocumentFormSet = modelformset_factory( Document, form=DocumentForm, fields='__all__', max_num=2, extra=1 ) views.py def compare(request): file_paths, header_dict, step = [], [], 'start' header_dict, step = [], 'start' doc_forms = DocumentFormSet(request.POST or None, request.FILES or None) ...(removed other code)... return render(request, 'compare/index.html', {'formset': doc_forms, 'user': request.user}) Note that I render as {{ formset }} and also the formset should only render 4 inputs. I don't understand why the form is like so. Why is that happening even with extra and max_num set? Anyone can answer this I really need help. -
Django: Get an attribute (imagefield) from a Foreign Key's reverse relation object
I've been struggling with the right syntax for this. I want to create a gallery of photo albums, and have a selectable cover photo for each album. But to do this, I need to grab the reverse relation object and then choose the imagefield attribute from it. I know how to use the relation manager to filter the cover photo object (based on a cover boolean attribute) but not how to then get the imagefield attribute from that object (to then reference in the template for img src). Here is my models.py from django.db import models def make_pic_path (instance, filename): albname = instance.album.name path = 'AlbPics/{0}/{1}'.format(albname, filename) return path class Album(models.Model): name = models.CharField(max_length = 100) dates = models.CharField(max_length = 100) description = models.CharField(max_length = 1000) def cover_photo (self): return self.albumpicture_set.filter(cover = True) def __str__(self): return self.name class AlbumPicture(models.Model): picture = models.ImageField(upload_to = make_pic_path, blank = True) picture_desc = models.CharField(max_length=200) album = models.ForeignKey(Album, on_delete=models.CASCADE) cover = models.BooleanField() def __str__(self): return self.picture_desc and the views.py: from django.shortcuts import render from .models import Album, AlbumPicture from django.contrib.auth.decorators import login_required @login_required def alb_gallery(request): gallery = Album.objects.all() context = {'gallery': gallery, } return render(request, 'gallery/gallery.html', context) And the template gallery.html (or my best guess) … -
django ImageField subclass, abstract value
I'm trying to subclass the Django ImageField. This is quite complicated as I'm finding out. There seems to be some basic ORM stuff that just isn't making sense to me, for instance: Where does the ORM field (ImageField) instance store the value that gets stored in the DB? Where does (ImageField) actually declare its db field type? It looks likes the ImageField returns an FieldImage object with a self.name attribute contains the same value which gets stored in the db. However, I' like to intercept that and abstract it so I can change the value without breaking the underlying operation of ImageField. So far I'm like 20hrs in on reading through the docs and haven't come up with the answer. Anyone successfully been able to abstract the value? I'm trying to store a bunch of JSON that contains the relative file name, instead of just the relative file name. example: #Image Field currently stores: './images/products/myimage.png' #My subclass should instead store: "{'source':'./images/products/myimage.png','other_info':'./images/products/myimage.png'}" -
Django two web pages have seperate apps or a single app
I am new in Django. Can anyone please help me. I have created 2 webpages 1 is for registration and 2nd is for login. Now i can i use both forms in simgle app or two seperate apps for both the pages. And also tell me about models.py page in this problem. Thank you -
How I can solve this python problem?[django]
Why cannot migrate. What the problem it shows type error. Here is the models from django.db import models # Create your models here. class Product(models.Model): product_id = models.AutoField product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="" ) subcategory = models.CharField(max_length=50, default="" ) price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.product_name -
Give the default url when a given url is not present in urls.py in template django
I have configured URLs in my database table for dynamic side bar creation. Due to some change in requirement, I have moved some views from a one application to an other application. Because I forgot to change the urls in database, I am getting an error in the application. Adding sample code here custom tag: @register.inclusion_tag('common/sidebar.html', takes_context=True) def show_sidebar(context, active_module_name): request = context['request'] module_list = AppAuthsService.get_user_module_list(user=request.user, active_module_name=active_module_name) return {"modules": module_list} {% if modules %} {%for module in modules %} <li class="nav-item"> <a class="nav-link {{ module.isactive }}" href="{% url module.url %}"> {{module.name}} </a> </li> {% endfor %} {%endif %} Here I want that, it should not break the application. Instead of that there should be optional url argument if urlmatch is not resolved in the {% url module.url %}. -
How to set permission all model table for django
permission:, add , update , delete , views role : like, admin , employee , staff, customer -
Heroku app is live but can't be found on search engines
I've uploaded a Django site using Heroku. It is live on the URL but I can't find it on google, even when I use site: I haven't registered a domain name for it yet, so it's still appname.herokuapp.com. I'm not sure if that's the reason why, as my WordPress site from 4 years ago is quite searchable and it still uses .wordpress.com. Is it because Heroku doesn't allow public sites without a domain registration or maybe Heroku needs us to sign up for subscription plans? Thanks in advanced. -
Will Developer created a Database for storing user and user id under Django?
Some I am designing a bunch of databases for storing bookmarks. I think I will create three of them. User ---- Id Username Tag --- Id Title Description Bookmark -------- Id UserId TagId Title Url I knew Django already create and store users and unique user id when created an account. So normally, do I need to create a whole new database for storing users? -
Why I'm facing thisproblem in python-(django)?
#django Why I cann't migrate.It shows type error:expected string or bytes like object.Why this is showing Can anyone help me to solve this problem? -
Sendgird Web API python example code not working: 401 unauthorized
The problem: Sendgrid web api python example code showing error 401: Unauthorized The settings: server-heroku, framework-django, sendgrid single sender authorized but not domain. Heroku add-on attached. The code: /sendgrid.env:export SENDGRID_API_KEY='the api key' /view.py def Contact(request): message = Mail( from_email='customerservice@shionhouse.net', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return render(request, 'core/contact.html') By the way, is sendgrid really worth awhile? Or is it just better off using django default SMTP anyway? -
Django test : can authenticate, but not login
I am trying to make a unit test on a rest api. I am using the StaticLiveServerTestCase and so, a temporary in-memory database to make the tests. This needs to have some pre-populated data put in it, this is why I do create a user (which own a "Bristol") in my models. The main thing, I think, is an issue with the authentification : I can authenticate and do a client.login, but it is refused on the API-side :-/ The error I get from the API is a 403=>Invalid username/password, I can't figure out why can I do a client.login and a django.contrib.auth.authenticate, but not passing them in a HTTPBasicAuth (which works in the production server). Something here is to be analysed with the way the "user" is saved in the database. I have seen this question : Django's self.client.login(...) does not work in unit tests where the answer is about a different way to save the password on the database, but it goes back as far as 2015 and it seems that now with django 3 which I am using, the difference disapeared. Here is the code : class test_api(TestCase, StaticLiveServerTestCase): def test_03_get_all_bristol(self): owner_pwd = "pwd" owner, bristol = … -
Django - unable to handle form submission with dynamic field
In my Django form, I have one select field that needs to be populated dynamically based on some information about the current user. I am able to get the field set up correctly and rendered in the form - however, I'm getting an error when submitting the form because it's getting hung up on some of the logic that I have in the form's __init__ method that only makes sense in the context of generating the form in the first place. I'm super-new to Django, and I'm not quite familiar with the design principles for this sort of situation. In my app's admin.py, I have a method that's used for creating a custom view for a data export form - the relevant parts of it are set up like so... # admin.py from organizations.models import Organization from .forms import ExportForm class SomeModelAdmin(SimpleHistoryAdmin, SoftDeletionModelAdmin): def export_view(self, request): authorized_orgs_queryset = Organization.objects.viewable_for_user(request.user).all() authorized_orgs = [{'id': org.id, 'name': org.name} for org in authorized_orgs_queryset] context = dict( self.admin_site.each_context(request), form = ExportForm({'authorized_orgs': authorized_orgs}), ) if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): # do some stuff with the form.cleaned_data and return a .csv file as a response return response return TemplateResponse(request, 'export.html', context) So the … -
Django tabular inline show current user as default
Kindly help with below issue. I am stuck from long time. I have two models, media and review Review any media item is reviewed then the review get stored in review model. In admin site I have created tabular inline so that I can see media along with its review, When I click add another review, a new review line is getting added. What I need is by default it should show the Reviewer as current logged in user. Here is the review model, class Review(models.Model): """Represents a review made by an Account on an object """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() review_item = GenericForeignKey('content_type', 'object_id') reviewer = models.ForeignKey( Account, blank=True, null=True, on_delete=models.SET_NULL, help_text="Account of the reviewer", ) RECOMMENDATION_CHOICES = [ ("pending", "pending"), ("accepted", "accepted"), ("declined", "declined"), ] recommendation = models.CharField( max_length=64, choices=RECOMMENDATION_CHOICES, default="pending", help_text="Recommendation of the reviewed object", ) description = models.TextField( blank=True, null=True, help_text="Optional field for reviewer to make comments", ) Here is the admin.py code, class ReviewInline(GenericTabularInline): """Inline for Review models """ model = Review # Limit extra inline forms extra = 1 class MediaAdmin(admin.ModelAdmin): """Admin interface for the Media model """ # *** Form settings *** # Split up the forms into fieldsets fieldsets … -
Django CustomUser model - Two Db Errors
Currently working on a new project: photo blog using custom users. For my user model, I've inherited from AbstractBaseUser with the attributes below. With a top down approach, I've created a custom user (CustomUser) and created two user types using proxy models (Contributor and Producer). Each type then has further attributes using OneToOneFields with CustomUser (located in ContributorMore and ProducerMore, respectively). Relatively straightforward, however I'm consistently running into two issues, second is most important so please take a look! Whenever I update my migrations, I run makemigrations users successfully. However, when subsequently running migrate, I consistently receive the following error: OperationalError: foreign key mismatch - "users_contibutermore" referencing "users_customuser". I can get around this by deleting the migrations folder from my users app, rerunning makemigrations and then migrate - but I have to do this each time I change my model. Any ideas what could be causing this? It has obviously only happened since introducing my ContributorMore and ProducerMore models. However, the code in these must be correct as the migrations run ok when I delete the migrations folder as described. Further, I followed Daniel Feldroy's youtube tutorials on this. The second issue is my recent addition of profile_pics attribute to … -
Why does Django models OneToOne query all objects for drop-down when ForeignKey does not?
models.py class PumpLog(models.Model): # work_order = models.OneToOneField('WorkOrder', on_delete = models.CASCADE) work_order = models.ForeignKey('WorkOrder', on_delete = models.CASCADE) class WorkOrder(models.Model): completed_on = models.DateField('Completed On', null=True, blank=True) template_.html {{ form.work_order|as_crispy_field }} As you can see there is a FK relationship between PumpLog and WorkOrder. When the PumpLog-Update page loads it only queries the selected/related WorkOrder. If the drop-down to select the work order is clicked - it queries additional WorkOrder as the user scrolls or searches. I am trying to convert it to OneToOne. But when I switch it to OneToOne I notice that it retrieves all WorkOrders - which can take 1-4 minutes to load. I noticed this by placing print(self.index) in the WorkOrder's __str__ method. In the console I see it list every single WorkOrder one-by-one. But if I switch it back to FK it only displays the index of the one already selected in the drop-down. This doesn't seem to be a widget or crispy_form issue because I see the same behavior when I remove or revert those. I understand to some degree that it needs access to all of the work orders so that the user can select whichever one. BUT it doesn't seem to need to load all … -
Django model instance from queryset not updating on save()
I have the following code VocabFromDatabase = Vocab.objects.filter(User = U, IsCard = True).order_by("LastStudyDate") VocabFromDatabase[0].Mnem = "Passed" VocabFromDatabase[0].save() According the docs save() should save the changes, but it seems to silently fail. After some fiddling around it seems the problem isn't with save() but rather with assigning a value to a property of one of the objects from the queryset. However everywhere I look tells me to either use update() (which I think would update all the objects in the queryset, which I do not want), or that save() should work. Is there something I'm not aware of, or something I'm doing wrong here? -
What does Django's Exception class' "code" argument do?
I read that: Provide a descriptive error code to the constructor: # Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value')) from this page: https://docs.djangoproject.com/en/3.1/ref/forms/validation/#raising-validationerror However, I cannot find what the code= parameter is used for. I was able to find an example use case here: https://www.fullstackpython.com/django-forms-validationerror-examples.html with: raise ValidationError( error, code="InvalidSql" ) raise django.forms.ValidationError( _('Date must be later than %(date)s.') % {'date': min_value.strftime('%m/%d/%Y'), }, code='minimum') That's about the only time I've seen code= used but I still can't figure out why it is useful and where it comes into play.