Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i get specific field in a form?
So what I'm trying to do is, I get long text from a user via the modelform I've created. Then in my models, I want to save the first sentence of the text. In order to do this, I believe I have to get the data(long text) from the form, and use a function to leave nothing but the first sentence. But I have as a beginner in Django, I have no idea on how to get an individual field from a form. So this is my codes: models.py class InputArticle(models.Model): objects = models.Manager() authuser = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'dansang', null=True, default=None) title = models.CharField(max_length=100) contents = models.TextField(max_length=100000) first_sentence = models.CharField(max_length=100) def __str__(self): return self.title forms.py class InputArticleForm(forms.ModelForm): class Meta: model=InputArticle fields=['title', 'contents'] I want to later display the title, contents, and first sentence in a separate page. I very much appreciate your help :) -
managed=False ignored and default_permissions=() bugged?
Django : 2.2.9 Python : 3.7 I try to create a dummy model to store my custom permissions. I don't want Django to create a table in my database nor create default permissions. My model look like this : class Permissions(models.Model): class Meta: managed = False, default_permissions = (), permissions = ( ("approbations_write", "Modifier/Emettre les approbations"), ("config_read_saufmdp", "Lecture configuration applicative avec mot de passe masqués"), ("config_write", "Modification configuratin applicative"), ("config_deploy_read", "Lecture configuration interne DEPLOY"), ("config_deploy_write", "Modification configuration interne DEPLOY"), ("ssh_write", "Effectuer un échange de clé SSH"), ("historique_read_normal", "Lecture de l'histrique sans conf DEPLOY interne"), ("historique_read_full", "Lecture de l'histrique sans restrictions"), ("releases_write", "Purge des releases potentiellement bloquées"), ) I use makemigrations and my options are in the migration file : migrations.CreateModel( name='Permissions', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'permissions': (('approbations_write', 'Modifier/Emettre les approbations'), ('config_read_saufmdp', 'Lecture configuration applicative avec mot de passe masqués'), ('config_write', 'Modification configuratin applicative'), ('config_deploy_read', 'Lecture configuration interne DEPLOY'), ('config_deploy_write', 'Modification configuration interne DEPLOY'), ('ssh_write', 'Effectuer un échange de clé SSH'), ('historique_read_normal', "Lecture de l'histrique sans conf DEPLOY interne"), ('historique_read_full', "Lecture de l'histrique sans restrictions"), ('releases_write', 'Purge des releases potentiellement bloquées')), 'managed': (False,), 'default_permissions': ((),), }, ), Still when I do the migrate, Django create the table … -
xhtml2pdf how manage the class attribute?
In my django project i have to create a pdf file from my html. For this purpose i use xhtml2pdf and in my html section i write: <style type="text/css"> body {margin:0;padding:0;background-color:#FAFAFA;font:8pt "Tahoma";} * {box-sizing:border-box;-moz-box-sizing:border-box;} th, td {border:1px solid black;border-collapse:collapse;} @page { size: a4 portrait; margin: 1cm auto; padding: 1cm; margin: 1cm auto; border: 1px #D3D3D3 solid; border-radius: 5px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.1); } table { -pdf-keep-in-frame-mode: shrink; border:1px solid black; border-collapse:collapse; } p {margin:0;padding:0;line-height:1.4em} .column-50-left {width:49.5%;display:inline-block;vertical-align:top;padding-right:15px} .column-50-right {width:49.5%;display:inline-block;vertical-align:top;padding-left:15px} .invoice {font-size:6pt} .invoice td {height:50px;vertical-align:top;padding:5px;} .destinatario td {height:120px;vertical-align:top;padding:5px;font-size:6pt} .description th {height: 30px} .description td {height: 50px} .top-10 {margin-top:10px} .top-15 {margin-top:15px} .top-20 {margin-top:20px} .padding-top-4 {padding-top:4px} .padding-bottom-15 {padding-bottom:15px} .padding-bottom-30 {padding-bottom:30px} .border-top {border-top:1px solid #000000} </style> but when i use my attributes on elements for apply the styles nothing appen for example: <table style="width:80%" class="invoice top-10"> or <div class="border-top top-10 invoice padding-top-4 padding-bottom-15"><p>PORTO / <em>Freight</em></p></div> How can i apply my class style to my pdf output in xhtml2pdf? So many thanks in advance -
Django: show selected item detail after selected jinja templates
I use Django and his templates (jinja). I have list view and detail view. I would like, that after selecting the item in list view, I populate the detail view with it's content. Inside content item, there is all necessary data. Is there more elegant way to use power of jinja templates to do this? -
How to upgrade Django Q and Django without clearing the queue?
When deploying the project after upgrading Django and Django-Q. I got the following log. Is there a way to avoid that error but still keep the tasks running in the queue to avoid downtime? 08:59:03 [Q] INFO Process-1:440 pushing tasks at 12192 Process Process-1:440: Traceback (most recent call last): File “/usr/lib/python3.6/multiprocessing/process.py”, line 258, in _bootstrap self.run() File “/usr/lib/python3.6/multiprocessing/process.py”, line 93, in run self._target(*self._args, **self._kwargs) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/cluster.py”, line 340, in pusher task = SignedPackage.loads(task[1]) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/signing.py”, line 31, in loads serializer=PickleSerializer) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/core_signing.py”, line 36, in loads return serializer().loads(data) File “/home/ubuntu/py34env/lib/python3.6/site-packages/django_q/signing.py”, line 44, in loads return pickle.loads(data) AttributeError: Can’t get attribute ‘simple_class_factory’ on <module ‘django.db.models.base’ from ‘/home/ubuntu/py34env/lib/python3.6/site-packages/django/db/models/base.py’> -
ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version)
ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later I met with this problem at the django project, mismatching version for the sqlite3 and the django. this occurs at the centos7 env, and I also want a convenient solution that works in the container env. -
Including ffmpeg in Django project
I am making a very simple Django app (it's a test for non-Django course) and I need to analyse a mp3 file in there, so I try to turn it into wav with this: sound = AudioSegment.from_mp3('upload/' + filename) sound.export('upload/wavfile', format="wav") rate, data = wav.read('upload/wavfile') I have installed ffmpeg by pip install ffmpeg in venv terminal, since I want to my code to run not only on my machine. The ffmpeg and ffprobe folders have appeared in /venv/lib/python3.7/site-packages/ however when I run my server I get the warning: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning) and when I load file in web page it throws [Errno 2] No such file or directory: 'ffprobe': 'ffprobe' at the first line of the code above. I would really appreciate any help with how I can use ffmpeg in my app or other ways to handle my mp3 file. -
Overriding Django Admin get_queryset with raw() results in DatabaseError
To speed up my admin page, I've decided to override my get_queryset() with a raw query however it results in: Database error: Something’s wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user. Is there some step I'm missing?. I've already confirmed that the query works in PSQL so I don't see what's going wrong. I've tried cutting it down to just the following but it still errors out. def get_queryset(self, request): return MyObject.objects.raw('SELECT * FROM myapp_myobject') -
Python Django - How to Pass HTTPS URL as function parameter in manage.py shell
I'm trying to call a function insert_db in the python shell. insert_db requires an https url to call some other functions. In Terminal in my Django python project folder, I type './manage.py shell' to get the python shell for Django going. After that: from send_values.api.send_to_db import insert_db insert_db('https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json') I'm getting the following error: requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h? send_to_db.py code: # python send_to_db.py 'https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json' from ..models import Correlations from .lambda_async_s3_uri import filter_complete import sys def insert_db(args): print(args) table_values = filter_complete(args) for value_set in table_values: new_value_set = Correlations.objects.create(value_set) # new_value_set = Correlations.objects.create(experimentName=item[3], colLabel=item[5], rowLabel=item[4], rowNum=item[0], colNum=item[1], cor=item[2]) new_value_set.save() def main(args): insert_db(args) if __name__ == '__main__': main(sys.argv[1:]) Any help is appreciated. Please let me know if you need more information. Notes: 1) I know the insert_db function works like it is supposed to (taking the url, downloading some files, parsing through them for some data, and making some calculations from that data). Before making this Django project, in a pure Python project, I used to call it like this: python send_to_db.py 'https://www.encodeproject.org/search/?searchTerm=H3K4ME3&type=Experiment&replication_type=isogenic&assembly=GRCh38&award.rfa=ENCODE4&format=json' At that earlier point, instead of trying to add it to the Django database, I was just printing the values insert_db would calculate (which … -
django: api call view: on redirect the request method does not change to GET
I have viewA() and viewB() I am sending a POST request toviewB()` using curl curl --location --request POST 'http://127.0.0.1:8000/viewB' \ --header 'Content-Type: application/json' \ --data-raw '{ "item" : "new" }' inside viewB() i have a redirect(..to viewA) after redirected to viewA() when i debug inside viewA() i see that the request.method as POST instead of GET Why redirect() does not change request.method to GET -
Google Docs gives No Preview available in iframe Django
I have implemented previewing documents in iframe using google docs. But when executed it gives no preview available. Can someone help with it? Do I have to enable anything in settings.py in Django? -
Rediect to view or URL from Model in Dajngo
When user tries with brute-force attack with more than 10 unsuccessful attempts (in login page), then I am locking user. So part of this as shown in below code, I am moving user from login view to '/login_lock/' view as shown in urls. But not sure for some reasons I am unable to move to /login_lock/ and re-iterates login page/view with invalid login credentials Validation Error. Could you please help me how can I move to login_lock view with a call from user_login_failed_callback (this call in models.py). @receiver(user_login_failed) def user_login_failed_callback(sender, credentials, **kwargs): username = credentials['username'] user = User.objects.get(username=username) profile = user.get_profile() if profile.failed_login_count <= 9: profile.failed_login_count = profile.failed_login_count+1 profile.last_login_attempt_date_time = timezone.now() profile.save() else: return HttpResponseRedirect('/login_lock/') url(r'^login/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login.html'}), url(r'^login_lock/$', auth_views.login, {'template_name': 'dau_gui_app/registration/login_lock.html'}), -
django template custom filter
I'm fairly new to django and I believe this is django template related question. I've got a project template where there is a certain value, namely {{ tenant_name }} which tells the tenant name. I've used for loop to find out all tenant names which works fine. How ever, all of the tenants have units under them and when I try to display units per tenant with for loop it loops all units to all tenants which is not what I want to do. note: self.tenant can't be used in this case as the user doesn't have a tenant yet. I've tried to solve this using custom filter, by registering it and loading it to the template and then filtering like so: {{ tenant_name|filter_units }}, however this doesn't seem to work for some reason. My question is this: is it possible to extract tenant_name from the template to the filter, use that value in the filter to search for units and return it back to the template? If so, could you possibly show me how? If it is not possible, is there a better way to accomplish this? Thanks in advance. -
Django: Error in creating custom fields in Django
I tried this on my model: class NameField(models.CharField): def __init__(self, *args, **kwargs): super(NameField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return str(value).lower() class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.NameField(validators=[name_regex], max_length=100) postalcode = models.IntegerField(unique=True) class Meta: unique_together = ["state", "name"] Now I am getting error as: AttributeError: module 'django.db.models' has no attribute 'NameField' How to resolve this error? -
Django: Combining Two serializers int one JSON response
I am trying to export data from two models for a user in the format of "Level":[ { "level":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, ] "Key":[ { "key":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, ] In order to do this my code is serializer.py class LevelSerializer(serializers.ModelSerializer): book_ID = serializers.SlugRelatedField( source='book', many=False, read_only=True, slug_field='book_ID' ) class Meta: model = Level fields = ["date_added", 'book_ID', "level", ] class KeySerializer(serializers.ModelSerializer): book_ID = serializers.SlugRelatedField( source='book', many=False, read_only=True, slug_field='book_ID' ) class Meta: model = Key fields = ["date_added", 'book_ID', "mykey", ] view.py def api_get_all(request): if request.method == 'GET': all_levels = Level.objects.filter(user=1) all_key = Key.objects.filter(user=1) level_serializer = LevelSerializer(all_levels, many=True) key_serializer = KeySerializer(all_key, many=True) combine_serializer = level_serializer.data + key_serializer.data return Response(combine_serializer) However if I execute my above implementation I get [ { "level":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, { "key":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" } ] How can I make it so that it is serialized in a parent key? Any help is appreciated -
Django Ajax 405 (Method Not Allowed) CBV
I'm having trouble in POST-ing and DELETE-ing through Ajax call ! I've defined the methods on class! idk what is happening. Any help will be appreciated 😀 urls.py: path('<section>/add_wish/<slug>/', views.AddToWishlistView.as_view(), name='add_to_cart'), my view : class AddToWishlistView(LoginRequiredMixin, View): model = Wishlist http_method_names = ['POST'] def POST(self, request, *args, **kwargs): wished_product = get_object_or_404(Product, slug=self.kwargs['slug']) new_item = self.model.objects.get(customer = self.request.user) new_item.product.add(wished_product) return HttpResponse(status=201) and Ajax here ! $('.buy').click(function(e){ e.preventDefault(); let _this = $(this); var slug = _this.children().data('id'); var section_slug = _this.data('section'); $.ajax({ type : 'POST', url : '../'+section_slug + '/add_wish/' + slug + '/', success: function(data){ if(data.success = true){ _this.addClass('clicked'); } }, async : false, error : function(data){ console.log("ERROR"); console.log(data); alert('LOOSERR'); } }) }); -
How to make autocomplete filter in django admin form with class based model
I want to add a dropdown with autocomplete filter such as select2 into django admin form with class based model. i have tried several tricks avilable over the internet but not succeeded. here are some code snippet i have. i want to show all category for a post which is already available into model. in my model.py class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) featured_image = models.ImageField(null=True, blank=True, upload_to="blog/", verbose_name='Featured Image') author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = RichTextUploadingField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on', 'title'] def __str__(self): return self.title def _generate_slug(self): value = self.title slug_candidate = slugify(value, allow_unicode=True) self.slug = slug_candidate def save(self, *args, **kwargs): if not self.pk: self._generate_slug() super().save(*args, **kwargs) my admin.py class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status', 'category', 'author','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} actions = [export_as_csv_action("CSV Export", fields=['title','slug','author','featured_image','status','created_on','updated_on'])] how my form looks into django-admin please suggest anything how to add i filter for category dropdown filter with autocomplete. -
Problem while inititliazing a django project in travis CI
./app/settings.py:89:80: E501 line too long (91 > 79 characters) ./app/settings.py:92:80: E501 line too long (81 > 79 characters) ./app/settings.py:95:80: E501 line too long (82 > 79 characters) ./app/settings.py:98:80: E501 line too long (83 > 79 characters) The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. -
How do I show validation error in django?
I am new to Django. I am doing simple crud but without using forms.py. How do I show validation error message in template. I want to know if there is way to perform crud operation without creating forms.py. Please do consider any mistake in questions since I am new to django. Also any help will be appreciated. This is views.py def category_save(request): if request.method == 'POST': name = request.POST['name'] slug = request.POST['slug'] image = request.FILES['image'] category = Category(name=name, slug=slug, image=image) category.save() return redirect('dish:category') This is template <form action="{% url 'dish:category_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="name">Name:</label> <input type="text" name="name" class="form-control"> </div> <div class="form-group"> <label for="slug">Slug:</label> <input type="text" name="slug" class="form-control"> </div> <div class="form-group"> <label for="image">Choose Image:</label> <input type="file" name="image" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save</button> </form> -
Unexpected error while request parsing using a serializer
While parsing my request data from front-end and converting into JSON format using a serializer. I am getting some unexpected errors. while request parsing pattern using a serializers given as mentioned below, it shows me following error: {'phone_number': {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got str.']}, 'cont_email': {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got str.']}} I have a Model: class RestaurantContactAssociation(models.Model): restaurant=models.ForeignKey(Restaurant) contact=models.ForeignKey(Contact,null=True,blank=True,related_name="restaurantcontact_association",on_delete=models.SET_NULL) class PhoneNumber(models.Model): contact = models.ForeignKey(Contact,related_name='contact_number') number = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class ContactEmail(models.Model): contact = models.ForeignKey(Contact,related_name='contact_email') email = models.EmailField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) The serializers that I have created are: class PhoneNumberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PhoneNumber fields = ('number') class ContactEmailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ContactEmail fields = ('email') class CrmContactSerializer(serializers.ModelSerializer): phone_number = PhoneNumberSerializer(source = 'contact_number') cont_email = ContactEmailSerializer(source = 'contact_email') class Meta: model = RestaurantContactAssociation fields = ('id','phone_number','cont_email','contact') The part of code which calls this serializer: request.data['phone_number'] = '9999999999' request.data['cont_email'] = 'tim@gmail.com' contact_name = request.data.get('c_name',None) contact_serializer = CrmContactSerializer(data=request.data) if contact_serializer.is_valid(): contact_serializer.save() Can someone please offer advise, that what am I passing wrong in it? -
Django: Uppercase/Lowercase values of Django Model attributes should be treated as same
I have model city: class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100) postalcode = models.IntegerField(unique=True) class Meta: unique_together = ["state", "name"] In this model name of city with all the cases (Uppercase/lowercase) should be treated as same like Udaipur/udaipur/udaiPuR all should be treated as same. -
Django-allauth Discord redirect uri is incorrect
According to Discord, the redirect url should start with https://discordapp.com/api/oauth2/authorize? yet when I pass {% provider_login_url 'discord' %} into my "Login with Discord" button, its redirect uri starts with https://discordapp.com/oauth2/authorize? (without the /api/). If I manually pass in the proper redirect url, it works fine. But using the {% provider_login_url 'discord' %} redirect gets an 'incorrect redirect_uri' error. If I look at the DiscordOAuth2Adapter() class from the allauth Github, it looks like it has the proper authorize_url. class DiscordOAuth2Adapter(OAuth2Adapter): provider_id = DiscordProvider.id access_token_url = 'https://discordapp.com/api/oauth2/token' authorize_url = 'https://discordapp.com/api/oauth2/authorize' profile_url = 'https://discordapp.com/api/users/@me' def complete_login(self, request, app, token, **kwargs): headers = { 'Authorization': 'Bearer {0}'.format(token.token), 'Content-Type': 'application/json', } extra_data = requests.get(self.profile_url, headers=headers) return self.get_provider().sociallogin_from_response( request, extra_data.json() ) I'm clearly missing something here. -
Django template forloop and if condition problem
if looped reach 7, it will add or change td just like the second picture showed {% for match in matches %} <tr> <td class="tblcore">{{match.id}}. {{match.Marking__Marking}}</td> </tr> {% endfor %} this is i want result -
pycharm Cannot load facet Django
I created a django project and opened it using pycharm community, and it showed error: Cannot load facet Django. I already installed django in pycharm, but it still shows this error. -
How to create a backend with Django and GraphQL that process a data from Angular then post back a result?
I'm totally a beginner to back-end. I already created the front-end for a web app by Angular which allows us to draw a number on a white space (28 pixels x 28 pixels), then sends the image as a 2D array to its back-end. The back-end then uses a machine learning model to guess which number it is. I'm trying to use Django as my back-end with GraphQL to make an API to receive data, but I'm totally confused after watching and reading some tutorials about Django. How can I create a GraphQL API with only one field which receives my array properly? And where should I put the logic to my Django back-end? Please give me some advice or resources. Thank you very much!! My back-end will simply receive a 2D array, process it then will send the result back to Angular to display and nothing else.