Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0: TextInput in ModelChoiceField shows id instead if value
I changed ModelChoiceField to be shown as a TextInput. I have a field named 'filename' of this type: models.ForeignKey('Filename', on_delete=models.SET_NULL, null=True, blank=True) in a class as follow: models.py class Event(models.Model): name = models.CharField('Name', max_length=100, blank=True, default='') filename = models.ForeignKey('Filename', on_delete=models.SET_NULL, null=True, blank=True) class Filename(models.Model): name = models.CharField('Name', max_length=50) def __str__(self): return self.nome This is part of my 'forms.py' I use show form in frontend after defining the template (myappname/templates/myappname/event_edit.html) forms.py class EventEditForm(forms.ModelForm): def __init__(self, data=None, *args, **kwargs): if data is not None: data = data.copy() if data['filename']: f, f_created = Filename.objects.get_or_create(nome=data['filename']) data['filename'] = m.id super(EventEditForm, self).__init__(data=data, *args, **kwargs) self.fields['filename'] = forms.ModelChoiceField(queryset=Filename.objects.all(), widget=forms.TextInput(attrs={'class': 'form-control', 'value':self.instance.filename})) self.fields['filename'].required = False class Meta: model = Event fields = ['name', 'filename'] and this is my event_edit.html: <form method="post" class="form-horizontal"> {% csrf_token %} {% for field in event_form %} <div class="form-group form-group-lg"> <label for="{{ field.id_for_label }}" class="col-sm-2 control-label">{{field.label}}</label> <div class="col-sm-6"> {{ field }} </div> <div class="col-sm-4"> {{ field.errors }} </div> </div> {% endfor %} <div class="form-group"> <div class="col-sm-10"> <button type="submit" class="btn btn-primary btn-lg center-block">Save</button> </div> </div> </form> The problem is that if I override ModelChoiceField to be a TextInput the 'filename' field shows id instead of showing field name. Otherwise, If I leave it as a … -
Using a own Model to be the User login
I have a doubt about authentification with my own Model. In my project I have a Pacient Model and I need that to be saved on the Users panel in the Admin site. Basically I recover the data from a HTML form (they're generated in a , it was a request for the test) (Do not worry about the validations) models.py class Pacient(models.Model): name = models.CharField() birthday = models.DateField() email = models.EmailField() password = models.CharField() confirmPass = models.CharField() In the forms.py file class PacientForm(forms.ModelForm): name = forms.CharField birthday = forms.DateField email = forms.EmailField password = forms.CharField confirmPass = forms.CharField class Meta: model = Pacient fields =('name','birthday','email','password','confirmPass') Using those fields I can save data in the table Pacient. It can be seen in the admin site but separated from the Groups and Users under the project name. So, my question is this. How can I made the Pacient Model to be recognized as the User (in the admin site) and login using the "email" as the username? -
I Want Users to Delete Themselves - With Django
I have a blog site in which users may register an account, get a profile page (a profile app) and post blogs and comments (via a blog app) if they're loggged in. As it is, a superuser can delete another user via the admin panel, thus destroying the users account, profile, posts and comments in the proces (I've inserted on_delete=CASCADE in the models' ForeignKey fields, so when the user is deleted, everything goes). I would like to give the users the ability to terminate their own accounts at will in stead of the admin having to do it. I've tried with the following generic view and also the commented out FBV's seen below: class ProfileDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = User succes_url = reverse_lazy('/') def test_func(self): # user = self.get_object() user = self.kwargs.get('username') if self.request.user == user: return True return False # def delete_account(request, username): # user = User.objects.filter(username__iexact='username') # user.delete() # return redirect('/') # @staff_member_required # def delete_account(request, username, login_url='login'): # try: # user = User.objects.get(username = username) # user.delete() # messages.sucess(request, "your account has been deleted") # except: # messages.error(request, "the user could not be found") # return render(request, 'home.html') with this URLpattern: path('delete/<int:pk>/', ProfileDeleteView.as_view(template_name='account/delete_profile.html'), name='delete-profile'), and finally, in … -
Django: Select object contains all keywords
Here is the db looks like: id | Post | tag 1 | Post(1) | 'a' 2 | Post(1) | 'b' 3 | Post(2) | 'a' 4 | Post(3) | 'b' I withdraw the tags and save each as one row in the database. Now I want to make a search function that the user can input more than one keywords at the same time, like 'a b', and it will return 'Post(1)'. I searched for some similar situations, but seems all about searching for multi keywords in one row at the same time, like using Q(tag='a') & Q(tag='b'), it will search for the tag that equals to both 'a' and 'b'(in my view), which is not what I want (and get no result, obviously). So is there any solution to solve this? Thanks. -
Django and Javascript submitted forms
I would like to get some help in order to find a way to submit 2 forms, the first one with Javascript and the second one with Django in my HTML template. I have something like this in my HTML template : <form method="post" id="customerform" novalidate> ... <form action="" method="get" id="search-form"> ... <input type="submit" class="btn btn-danger" id="submit-choice" name="SubmitChoice" value="{% trans 'Search' %}"/> </form> <input type="submit" class="btn btn-default" value="{% trans 'Save' %}"/> </form> The first form is my important Django form in which one I have a research form. This research form should be submited with Javascript component. I wrote this, but it doesn't work : <script> var form = document.getElementById("search-form"); document.getElementById("submit-choice").addEventListener("click", function () { form.submit(); }); </script> Result : When I submit the second form with id=search-form, fields from the first one are empty and I get a messsage : this field is mandatory. -
heroku does not really seem support python & django on Window - anybody have success deploying
Heroku seems to have a dependency on gunicorn on python/django app. Gunicorn is not supported on Windows. Has anybody had success or know of a work around? My app runs fine but not under Heroku or Heroku local Error: ...site-packages\gunicorn\util.py", line 9, in <module> import fcntl ModuleNotFoundError: No module named 'fcntl' Exited with exit code null -
How to save file xhtml2pdf
i would like save my pdf file in to path but i dont information about how make this. My code: def createPDf(request): num_sale = request.POST.get('num_sale') sale_header = Sale.objects.filter(secuence_id=num_sale).first() context = { 'sale_header': sale_header, } pdf = render_to_pdf('reportes/pdf/pdfSale.html', context) # Force Download if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Sale_%s.pdf" % (str(sale_header.secuence)) content = "inline; filename='%s'" % (filename) content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None please some one suggest or link how save on path the pdf.. thanks !! -
Writing a csv file from user input in django: each character appears on a new line
In django, I have users who submit a form that contains a text area. In that text area, they paste information from a spreadsheet. This information will be tab-delimitated when they paste it. What I want to do is make a CSV file from this information (comma separated). Here is what I do: input = request.POST['data'] path = '/path/to/file.csv' in_txt = csv.reader(input, delimiter = '\t') out_csv = csv.writer(open(path, 'w')) out_csv.writerows(in_txt) However, if I use this information: Header 1 Header 2 Header 3 Item 1 Item 1 Item 1 Item 2 Item 2 Item 2 Then it gets converted into: H e a d e r 1 , H e a d e r 2 , H e a d e r 3 I t e m 1 , I t e m 1 , I t e m 1 I t e m 2 , I t e m 2 , I t e m 2 So every character is shown on a new line. Why is this happening? Using django 2.1 and python 3f -
How can I limit ImageField to a few choices in Django Admin
I have a model like with a file defined like models.ImageField(upload_to='folder_icons', null=True) I want to be able to limit the choice of this icon to a few pre created choices. I there as way I can show the user (staff member) the choices in the django admin perhaps in a dropdown ? This is similar to where I want a field where you choose between a few different avatars. Is there a custom field somewhere that can do this ? Thanks -
Shareable link app to other apps in Django project
I have a Django project which need to be able to provide unauthenticated users with shareable links. I am thinking about creating a Django-app for this: token_user with the following models: class TokenUser(models.Model): name = models.TextField() token = models.TextField() session = models.TextField() The idea is that other apps can then use this model and have shareable links generated. I'm using Django 2.1.2. Is this a good pattern? -
Django with multiple databses Mongodb and Neo4j
I am using Mongo as my primary database and Neo4j to store some relations.Hope Neo4j can reduce the query time for complicated searches in my application.I am confused regarding how to maintain relations between the two. Here my question how can we create relationship between tables from two different databases in this case? I am working on Python3.6, Django2.1, django-neomodel 0.0.4,and Djongo 1.2.30 Here is my models.py sample: class Listing(models.Model): ''' Listing Model for mongo database ''' create_time = models.DateTimeField() category = models.EmbeddedModelField( model_container=Category, ) subcategory = models.EmbeddedModelField( model_container=Subcategory, model_form_class=SubcategoryForm ) ... class Listingnode(DjangoNode): uid = UniqueIdProperty() list_id = StringProperty() status = StringProperty() created = DateTimeProperty(default=datetime.utcnow) price_range = RelationshipTo('PricerangeNodes','PRICE_RANGE') tags = RelationshipTo('TagNodes','TAGS') -
Social App Django - Association Model Error w/ Python3.7
I'm using social-auth-app-django==2.1.0 When the Association model saves using Python 3.7, the secret is saved like this in the database b'0j1KDtdsviAJOAqdSatAwNdfzsg=\n'. This causes an exception when the item is retrieved: Invalid base64-encoded string: length cannot be 1 more than a multiple of 4 If I change where when the secret is saved to: https://github.com/python-social-auth/social-app-django/blob/master/social_django/storage.py#L155 assoc.secret = base64.encodestring(association.secret).decode() it works properly. Is this a bug in the social-app-django library, or am I doing something incorrect? -
DRF CurrentUserDefault in serializer.update with PATCH request
Given the serializer below a PATCH request with {'description': 'product_3'} doesn't include user in the validated data. How could you add CurrentUserDefault() to the validated data without calling .save(updated_by=request.user)? class MySerializer(serializer.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Model fields = ('id', 'user', 'description') def create(self, validated_data): validated_data['created_by'] = validated_data.pop('user') return super().create(validated_data) def update(self, instance, validated_data): validated_data['updated_by'] = validated_data.pop('user') return super().create(instance, validated_data) -
can I send request to django /admin page?
I'm using django-rest-framework for a simple project. this api doesn't need registration and login for normal users. but it has an admin section on the frontend that can remove or add something to the website(to the database). Do I need to create a customized ProfileApi App (Login and Authentication App that overrides the default Authentication that django has provided) for having these Possibilities. Or can i send request to /admin url or another url and login and get a token without having trouble of creating another app? -
Auto relations with model database in forms django
I need to add comments to films Film model: class Film(models.Model): AGE = ((0, "0+"), (1, "6+"), (2, "12+"), (3, "16+"), (4, "18+")) name = models.CharField(max_length=50) description = models.TextField() year = models.PositiveIntegerField() age = models.IntegerField(, choices=AGE, default=0) slug = models.SlugField(max_length=50, unique=True, blank=True) image = models.ImageField() image.short_description = "Image" genre = models.ManyToManyField("Genre", related_name="films") trailer = models.URLField(, blank=True) time = models.PositiveIntegerField() def save(self, *args, **kwargs): def slug_create(name, year): return "".join((slugify(name), str(year))) self.slug = slug_create(self.name, self.year) super().save(*args, **kwargs) comment model: class Comment(models.Model): user_name = models.CharField(max_length=25) text_comment = models.TextField() data = models.DateField(auto_now_add=True) vefiried = models.BooleanField(blank=True, default=False) film = models.ForeignKey(to='Film', on_delete=models.CASCADE, blank=True, null=True) and comment form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['user_name', 'text_comment'] widgets = { 'user_name': forms.TextInput(attrs={'class': 'form-control col-3', 'placeholder': 'Name'}), 'text_comment': forms.Textarea(attrs={'class': 'col-12 my-2', 'rows': '10', 'placeholder': 'Comment'}), } I have a problems with automatically reating relation Film with comments. User can write comments only under film, so i have everytime slug, I dont know how relate it. -
Serving Django project with Gunicorn and Apache
I have a django project and I have deployed it to a CentOS server. I used Gunicorn and apache to serve the project. The problem is that the ServerName in the apache config file should be just the IP address of the server machine and if I use a name, there is a NotFound error. Bellow is the config file I have: <VirtualHost *:80> DocumentRoot "/var/www/html/wsgi-scripts/walk/mysite" ServerName passmobile #ServerName Server_IP # adding these lines for handling static files Alias /media/ /var/www/html/wsgi-scripts/walk/mysite/static/media Alias /static/ /var/www/html/wsgi-scripts/walk/mysite/static/static_root/ ProxyPass /static/ ! ProxyPass /passmobile/ http://localhost:8000/ ProxyPassReverse /passmobile/ http://localhost:8000/ <Directory "/var/www/html/wsgi-scripts/walk/mysite/static/"> Require all granted Satisfy Any </Directory> </VirtualHost> If I use an IP for the ServerName, everything is fine, but I can't as I have another website on this server machine and I want to load each website with a name appended to the IP address. For example: {server_ip_address}/passmobile => load the passmobile website and {server_ip_address}/gis => load the gis website -
Add blank field into django-jet autocomplete ajax field
Autocomplete ajax field doesn't show a blank choice: without blank How can i add it into autocomplete ajax field like so: with blank -
force both slugs in url to exist in datatabse
I have multiple categories and some details related to these categories through a Foreignkey. I have for example categorie1 and detail1. Now I can call categories in the url localhost:8000/categorie1 path('<slug>', views.CategorieView.as_view(), name='categorie_name') and details: localhost:8000/categorie1/detail1 path('<anythinghereworks>/<slug>', views.DetailView.as_view(), name='detail_name') but as written in the first slug any ulr like localhost:8000/abc/details1 will work. How can I make the pattern specific to the 2 slugs? #Model class Categorie(models.Model): name = models.CharField(max_length=50,unique=True) slug = models.SlugField(max_length=100,unique=True) def __str__(self): return self.name class Detail(models.Model): title = models.CharField(max_length=100) slug= models.SlugField(max_length=100,unique=True) categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE, related_name="details") def __str__(self): return self.title #Views class CategorieView(DetailView): model = Categorie slug_field = 'slug' template_name = "app/categories.html" class DetailView(DetailView): model = Detail slug_field = 'slug' template_name = "app/details.html" #Ulrs path('<slug>', views.CategorieView.as_view(), name='categorie_name'), path('<anythinghereworks>/<slug>', views.DetailView.as_view(), name='detail_name'), -
Migrations error __fake__.Does Not Exist: Tag matching query does not exist
Migration def add_startup_data(apps, schema_editor): Startup = apps.get_model('organiser', 'Startup') Tag = apps.get_model('organiser', 'Tag') for startup in STARTUPS: startup_object = Startup.objects.create( name=startup['name'], slug=startup['slug'], contact=startup['contact'], description=startup['description'], founded_date=startup['founded_date'], website=startup['website']) for tag_slug in startup['tags']: var=Tag.objects.get(slug=tag_slug) startup_object.tags.add(var) def remove_startup_data(apps, schema_editor): Startup = apps.get_model( 'organiser', 'Startup') for startup in STARTUPS: startup_object = Startup.objects.get( slug=startup['slug']) startup_object.delete() class Migration(migrations.Migration): dependencies = [ ('organiser', '0002_tag_data'), ] operations = [ migrations.RunPython( add_startup_data, remove_startup_data) ] Following is the Error: self.model._meta.object_name fake.DoesNotExist: Tag matching query does not exist. I cant seem to fix it...I Tried get_object_or_404 but it just leads to another error -
Does a file served through Django HttpResponse enter memory or stream from disk?
Say you have two options for serving a large file in Django, you can: Open your media directory to the public, and serve the file directly through Apache, Nginx, etc. You can process the file with Django before sending it, then send the file with something like this: from django.core.files.base import File from django.http import HttpResponse, HttpResponseNotModified def send_the_file(request, filename): # Do something ... # Send the file ... with File(open(filename, 'rb')) as f: response = HttpResponse(f.chunks()) return response Will Django stream the large file from disk like Apache would? Or will I waste threads and space reading the whole file into memory? -
Django admin multiple files upload at once
What I want to do is select a couple of files to upload and then when I submit those files will be upload by once, I referenced https://blog.rousek.name/2017/08/11/uploading-multiple-files-in-django-admin/ but this type of uploading is not what I want. I hope I can upload at Item model and django will help me to create muliple File records. class Item(models.Model): name = modles.CharField(max_length=50) class File(models.Model): iid = models.ForeignKey(Item, on_delete=models.CASCADE) file = models.FileField() -
Django: caching w.r.t url and also reflect changes
In Django i have an url which does some calculations based on dynamic data. So if i cache the url then will it return the updated results if there are any changes on dynamic data. Eg: Like purchasing. User adds list of items he wants. I have a page localhost/user/items/ which will display all the list of items he added and also with a link localhost/user/items/specs to display the specifications of all the items he added. Showing the localhost/user/items/ page takes less time. But localhost/user/items/specs takes a lot of time. How can I cache localhost/user/items/specs and also reflect any changes -
Uncaught (in promise) Error: GraphQL error: unhashable type: 'dict'
I am trying to have image upload feature but I am getting an error "Uncaught (in promise) Error: GraphQL error: unhashable type: 'dict'". I am using react-dropzone for uploading the image. It gives me File object which i then passed in mutation function with variables. Here is what, i have done mutation.py class UpdatePersonalProfile(graphene.Mutation): class Arguments: input = ProfileInput(description="These fields are required", required=True) success = graphene.Boolean() errors = graphene.List(graphene.String) profile = graphene.Field(ProfileNode) @staticmethod def mutate(self, info, **args): print ('info', args, info.context, info.context.FILES, info.context.FILES.get(args.get('input').get('avatar', None))) is_authenticated = info.context.user.is_authenticated profile = Profile.objects.get(user=CustomUser.objects.get(id=7)) profile.company_name = args.get('input').get('company_name', None) profile.bio = args.get('input').get('bio', None) profile.website = args.get('input').get('website', None) profile.avatar = info.context.FILES.get(args.get('input').get('avatar', None)) profile.job_title = args.get('input').get('job_title', None) profile.zip_code = args.get('input').get('zip_code', None) profile.save() return UpdatePersonalProfile(profile=profile, success=True, errors=None) input.py class Upload(graphene.types.Scalar): class Meta: description = '''Variables of this type must be set to null in mutations. They will be replaced with a filename from a following multipart part containing a binary file. See: https://github.com/jaydenseric/graphql-multipart-request-spec''' @staticmethod def serialize(value): return value @staticmethod def parse_literal(node): return node @staticmethod def parse_value(value): return value class ProfileInput(graphene.InputObjectType): full_name = graphene.String(description='Full Name') user = graphene.String(description='User') bio = graphene.String(description='No more than 1000 characters') website = graphene.String() avatar = Upload(description='Avatar') job_title = graphene.String() company_name = graphene.String() zip_code = … -
Set Default Local Language for Python/django app
How can I set my Default Local Language on Windows to English (South Africa)? I am trying to do this because on my dashboard's it is bringing up the $ for my totals. I tried to: django.contrib.humanize in my requirements and {% load humanize %} {{ my_num|intcomma }} on my templates but it's still bringing up dollar so I'm guessing it's picking up the local language which is set to English (United States) If this is not the problem and there is a fix... PLEASE help. -
Django Rest Framework POST and PUT Foreign Key ModelSerializer
I have a problem with a model serializer. My models class ItemState(models.Model): """Status for a item""" name = models.CharField(max_length=255, null=True, blank=True) class Item(models.Model): title = models.CharField(max_length=255) status = models.ForeignKey(ItemState, on_delete=models.CASCADE) My serializer: class ItemStateSerializer(serializers.ModelSerializer): class Meta: model = ItemState fields = '__all__' class ItemSerializer(serializers.ModelSerializer): status = ItemStateSerializer(read_only=True) class Meta: model = Item fields = '__all__' And my viewset class ItemViewSet(viewsets.ModelViewSet): """ Item view set """ queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (IsOwnerOrAdmin, ) My question is, how can i do a put or post without create a status object? I wanna replace this HTTP PUT { "title": "example", "status": { "id": 1, "name": "hello" } } by this HTTP PUT { "title": "example", "status": 1 } Thanks community!