Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
New to Django, unsure how to write queryset tying FK's together
For anyone frequenting the django tag, you may realize I am new to django (and haven't actually done development in a long time). I am struggling with queries with the ORM. I have two models, User & Department. Department has a leader that is a FK to a user. How do I return all instances of department and its associated first & last name of the user? Something like: SELECT Department.dept, User.first_name, User.last_name FROM Departments, Users WHERE Department.leader = User.Id OR Department.leader = NULL Thanks for any help, my mind is just not accepting thinking of queries in terms of the ORM yet. -
Django select_related() but only some fields
I would like to use select_related() but without loading all the fields of the model loaded via select_related. I'd just like to filter the model fields loaded via select_related without affecting the other queryset fields. There is the solution to use only() and explicitly specify all fields but this is not practical when you have a lot of fields. The solution of using exclude() and excluding only fields is not practical either in case of evolution. (Adding fields to the model) Is there another way? With an example, it will be more understandable: class User(model.Model): username = models.Charfield(max_length=50) # ... many fields here class Musician(models.Model): created_by = models.ForeignKey(User) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) # ... # many of fields here I would like to select all fields of the "Musician" model and only username of User by performing a single SQL query using Django ORM. -
Dynamically update price js or jquery from selected option
I would like to dynamically update the content of a span supposed to display the price of the selected option. PS: I'm using Django + Python to generate the options Here is my code : <select class="form-control" id="materials"> {% for material2 in materials %} <option value="{{ material2.name }}" data-price="{{ material2.price }}">{{ material2.name }} + <span class="material_price">{{ material2.price }}€</span></option> {% endfor %} </select> <span id="price_material"></span> Does anyone have an idea of how I could do that using Jquery or Javascript? -
Python3/Django/Gunicorn/Nginx - Can't upload file (Encoding)
I've recently deployed my django project on DigitalOcean Ubuntu 16.04 with Nginx and Gunicorn. I use django-import-export in this project. When I try to upload file through admin page, I get a weird error (the DEBUG mode is True) Imported file has a wrong encoding: 'ascii' codec can't decode byte 0xc4 in position 323: ordinal not in range(128) Which is not a common Django debug page. I can't figure out where is the problem. Python3 shouldn't have encoding problems. Do you know what to do? -
Django Import from CSV Integrity error if certain fields changed
I am working on an import feature to a Django Admin page to import user data. I want to import from a CSV the following: Email, location, school, job This works fine when I am importing for the first time, or if no fields change afterwards. The issue I am running into is where a field outside of email changed, I am getting an integrity error for duplicate entries with the same email. I want to be able to update the fields that changed instead of trying to create a new entry. Here is my code, any ideas? Thanks! csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding=request.encoding) reader = csv.reader(csv_file) # Skip header row next(reader, None) for row in reader: try: _, created = UserData.objects.get_or_create( email=row[0], location=row[1], school=row[2], job=row[3],) except IntegrityError: _, created = UserData.objects.update( location=row[1], school=row[2], job=row[3],) csv_file.close() -
Python find word occurences in list of phrases and link word to phrases
Let's say, I have a .txt file with phrases divided by new line (\n) I split them in list of phrases ["Rabbit eats banana", "Fox eats apple", "bear eats sanwich", "Tiger sleeps"] What I need to do: I need to make list of word objects, each word should have: name (for examples "eats") frequency(how many times it occured in phrases, for word "eats" frequency = 3) list of phrases it belongs (for example word eats belongs to phrases [0,1,2] What I've already done: Right now, I am doing it simple, but not effective: I get the list of words(by splitting .txt file by space character (" ") words = split_my_input_file_by_spaces #["banana", 'eats', 'apple', ....] And loop for every word and every phrase: for word in words: for phrase in phrases: if word in phrase: #add word freq +1 What is the problem with current aproach: I will have up to 10k phrases, so I encountered some problems with speed and performance. And I want to make it faster I saw this interesting and promising way of counting occurences(but I don't know how can make a list of phrases each word belongs to) from collections import Counter list1=['apple','egg','apple','banana','egg','apple'] counts = Counter(list1) … -
How to display multiple objects from fields in Django Admin
I am a bit stumped as to how I can add multiple access_token and items_ids in Django Admin. The models and apps involved are as follows. This is my first post so please forgive if it isn't in proper format. Trans/models.py class Exchange(models.Model): created = models.DateTimeField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='token', on_delete=models.CASCADE) access_token = models.CharField(max_length=300, blank=True, default='') item_id = models.CharField(max_length=300, blank=True, default='') request_id = models.CharField(max_length=300, blank=True, default='') class Meta: ordering = ('item_id',) I have setup a userprofile section for the admin: Users/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE) avatar_url = models.CharField(max_length=256, blank=True, null=True) dob = models.DateField(verbose_name="dob", blank=True, null=True) public_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='public_token') access_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='access_token') item_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='item_ID') just_signed_up = models.BooleanField(default=True) def __str__(self): return force_text(self.user) class Meta(): db_table = 'user_profile' users/forms.py class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('user', 'public_token', 'access_token', 'item_id',) users/admin.py class UserProfileAdmin(admin.ModelAdmin): search_fields = ('user', 'dob', 'public_token', 'access_token', 'item_id',) ordering = ('user',) list_select_related = ('user',) admin.site.register(UserProfile, UserProfileAdmin) class UserProfileAdminInline(admin.TabularInline): model = UserProfile I'm really just stumped as I tried making many to many field but couldnt seem to link correctly and or the process broke when testing in a sandbox environment. Any help would be … -
Django autocomplete fields do NOT work when using a horizontal filter on a many to many field
I am using django's auto complete lite to make a custom forum. In this model there is another field which I would like to apply a horizontal filter to. However whenever I apply the filter, the autocomplete forms do not work anymore. @admin.register(model) class modelAdmin(VersionAdmin): form = autoCompleteForm filter_horizontal = ('many_to_many_field',) Open to any solutions, I have searched around and cannot seem to find any other similar problem. -
Got "ValueError: invalid literal for int() with base 10: 'Trancel'" when using two paramenters in detailview in Django
I am trying to use two other url tags other then pk and slug in a detail view. I have the following code snippet: views.py class UseCaseDetailView(DetailView): template_name = "useCaseExtract/useCaseDetail.html" model = UseCaseProfile context_object_name = 'usecaseprofile' '''I am trying to override the get_object method of DetailView to accept url tags project and usecasename instead of pk and slug''' def get_object(self): obj = get_object_or_404(UseCaseProfile, project=self.kwargs['project'], useCasename=self.kwargs['useCasename']) return obj urls.py ... path('/UseCaseDetail/', UseCaseDetailView.as_view(), name='UseCaseDetail') ... in my template file, I have the following link: /Trancel/UseCaseDetail/Nothing after I clicked the link, I got: ValueError: invalid literal for int() with base 10: 'Trancel' can you some please explain to me why I am getting this error? -
Pass PK into model form (not logged in user)
I would like to use a model form on the django.auth user, but I want to be able to pass in the PK to the model to manage other users, not the logged in user. Is there a way to do this or do I need to create a regular form? Django admin site is not appropriate for my use case. Something like (which doesn't work of course...): def edit_user(request,pk): if request.method == 'POST': user_form = UserEditForm(queryset=User.objects.get(pk=pk), data=request.POST) if user_form.is_valid(): user_form.save() messages.success(request, 'User updated successfully') else: messages.error(request, 'Error updating your profile') else: user_form = UserEditForm(queryset=User.objects.get(pk=pk)) return render(request, 'edit_user.html', {'user_form': user_form }) Thanks for your help. BCBB -
Django import-export Invalid Dimensions
I'm trying to use django import-export to handle my csv file importing. If the excel file converted to csv only has 1 row, the code works. But when I tried to add multiple rows, it gave me a dimension error. I'm quite new to the library so I would appreciate any kind of help. my excel rows: id card_number total 101021 25 101023 30 101024 20 101025 10 views.py @staticmethod def post(request): print(request.data) shift_type = request.POST.get('shift_type') beep_shift = BeepTransactionView.shift_get_or_create(shift_type) beep_resource = BeepTransactionResource() dataset = Dataset() new_transactions = request.FILES['file'] imported_data = dataset.load(new_transactions.read().decode('utf-8'), format='csv') dataset.insert_col(1, col=[beep_shift.id, ], header="shift") print(dataset) result = beep_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): beep_resource.import_data(dataset, dry_run=False) # Actually import now return Response(data={ "data": "it worked" }, status=status.HTTP_200_OK) -
Django annotate data by date for empty result
Suppose I have a object model A, and it has a field called created, which is a datetime type field. If I use annotate to count how many A are created each day, I can use A.objects.annotate(date=Trunc('created', 'day', output_field=DateField()) ).values('date').order_by('date').annotate(count=Count('id')) After that, I can get the result, which looks like [{date: '2018-07-22', count:1 }, {date: '2018-07-23', count:1 }, {date: '2018-07-25', count:1 }] However, notice that I miss a 2018-07-24 because it didn't create any A in that day. Is there any way to let result to have {date: '2018-07-24', count:0 } inside that queryset? -
Broken virtualenv after brew update
I did an update/upgrade of homebrew. After that, in all my django-projects virtualenvs, Python got broken. What I did: Reinstallation of virtualenv package: $ pip uninstall virtualenv && pip install virtualenv $ virtualenv --no-site-packages .virtualenv $ source .virtualenv/bin/activate Rebuild virtualenv $cd .virtualenv/ $ find . -type l -delete $ virtualenv . OK, Python back in business Launch local server $python manage.py runserver django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib Referenced from: /Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/_mysql.so Reason: image not found. Did you install mysqlclient or MySQL-python? mysql issue $pip uninstall MySQL-python $pip install mysqlclient Launch server again $python manage.py runserver [...] File "/Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/easy_thumbnails/engine.py", line 12, in <module> from easy_thumbnails import utils File "/Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/easy_thumbnails/utils.py", line 15, in <module> from easy_thumbnails.conf import settings File "/Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/easy_thumbnails/conf.py", line 334, in <module> settings = Settings() File "/Users/marta/work/webDev/scaleway_servermg/vetrinamg/.virtualenv/lib/python2.7/site-packages/easy_thumbnails/conf.py", line 21, in __init__ super(AppSettings, self).__init__(*args, **kwargs) TypeError: __init__() takes exactly 2 arguments (1 given) Could anyone point me to the correct solution? I have the sensation that, as soon I fix a problem, a new one shows up. Thank you for any help you could provide -
Django - Getting all the options from a Select in POST without selecting them
Regarding this question: Django - POST get options from select i want to get in the views (request.POST) all the elements from a select, without having to select them. Is this possible or do i have to make a function when clicking the submit to select all of them before accesing the view? -
Use Django Model Manager in DRF Serializer for Generic Relation
I'm struggling to use model.Manager in my serializer. Suppose my model: class Report(models.Model): name = models.TextField() ... votes = GenericRelation(Vote, related_query_name='reports') and my votes model and model manager (like/dislike/okay): class VoteEnum(ChoiceEnum): Like = 'Like' Dislike = 'Dislike' Okay = 'Okay' class VoteManager(models.Manager): use_for_related_fields = True def likes(self): return self.get_queryset().filter(vote=VoteEnum.Like.name) def dislikes(self): return self.get_queryset().filter(vote=VoteEnum.Dislike.name) def okays(self): return self.get_queryset().filter(vote=VoteEnum.Okay.name) def reports(self): return self.get_queryset().filter(content_type__model='report') //dont pay attention to enum.name here class Vote(models.Model): vote = models.CharField(verbose_name="Vote", choices=VoteEnum.choices(), max_length=30) user = models.ForeignKey(User, verbose_name="User") content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() objects = VoteManager() So, what I want: In my Report serializer I want to return number of likes/dislikes without making additional properties to the report instance: def likes_count(self, report): return (Vote.objects.filter(report=report, vote='Dislike').count()) But to to use methods defined in my VoteManagerclass. Is it possible? Of course, I can leave it as is, but I am worried about performance impact of this approach (for 3 properties I'd have to filter 3 times...) and I'm not really eager to copy such properties for each model that I'd like to add votes to. That would be disgusting, I'm trying to avoid such copy/paste. I bet there is almost out of the box way to do … -
How to add a user to a ManyToManyField when creating User in Django?
Models.py: class RegularUser(MyUser): MyUser.is_staff = False MyUser.is_superuser = False class Meta: verbose_name = 'Usuario Regular' verbose_name_plural = 'Usuarios Regulares' class AdminUser(MyUser): usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra", blank=True) MyUser.is_staff = True class Meta: verbose_name = 'Administrador' verbose_name_plural = 'Adminsitradores' I want the next: I log in the admin site as AdminUser, which have staff permission. Then I can create RegularUsers. When I create a new RegularUser I want link this Regular User to the AdminUser through the ManyToManyField so this RegularUser owns to the AdminUser. And the AdminUser could manage this RegularUser in the adminSite. -
Namespacing URL names with multiple parameters in Django 2.0
How do I properly reference the edit_product.html line to the Edit_Product in urls.py with 2 parameters? I tried looking for examples but I couldn't find any. This is the error I received: Reverse for 'Edit_Product' with arguments '('eiffel',)' not found. 1 pattern(s) tried: ['shop/edit_product/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$'] urls.py from django.urls import path from . import views app_name='shop' urlpatterns = [ path('create_product/', views.CreateProduct, name='Create_Product'), path('edit_product/<slug:c_slug>/<slug:product_slug>/', views.EditProduct, name='Edit_Product'), path('', views.allProdCat, name='allProdCat'), path('<slug:c_slug>/', views.allProdCat, name='products_by_category'), path('<slug:c_slug>/<slug:product_slug>/', views.ProdCatDetail, name='ProdCatDetail'), ] edit_product.html <td><a href="{% url 'shop:Edit_Product' category.slug | product.slug %}">{{ product.name }}</a></td> -
Dynamically change span text based on selected option javascript
I'm trying to change dynamically the text of a span based on the the option that got selected. PS: I'm using Django + Python to generate options Here is my code : <select class="form-control" id="materials"> {% for material2 in materials %} <option value="{{ material2.name }}">{{ material2.name }}</option> {% endfor %} </select> <span id="material_display></span> I've tried : var selected_material = document.getElementById("materials").value; document.getElementById("material_display").innerTEXT = selected_material But that didn't work out. -
Persistent user defined variable in django
I want to create a website-feature in Django2 where an administrator can modify the "server state" by setting a flag. If the flag is true a normal user can query a list of special-content items. If it is false the normal user will see a message saying that the content will soon be available. Think of a job-scheduling app where the staff can pick tasks to do, after the boss checked the global flag to publish the already defined jobs within the organisation. I've tried to find the best practice for this but could not find the answer. I was thinking of some sort of persistent global variable in Django but I don't think it's supported. The next thing I thought of was to implement a model with a boolean field and a time field with the date and time it was created. The administrator can reach a custom admin page and store a new model instance with the desired bool value. Next thing is to always query the latest instance of this model and check the boolean value every time a user wants to display the particular page where the, sometimes hidden, content will be displayed. This is what … -
SuccessMessageMixin not working with FormView
I have a class-based FormView that I would like to display a message after a successful submission, but however, I could not see the message. Can someone please point out what I'm doing wrong? views.py class MaintenanceRequestCreate(SuccessMessageMixin, LoginRequiredMixin, FormView): model = MaintenanceRequest template_name = 'catalog/maintenancerequest_form.html' form_class = MaintenanceForm success_message = "Success!" Is there anything else I need to do? According to the documentation this is all I need to add. -
How do I use OAuth's user model as foreing key in my models?
I am using social-auth-app-django==2.1.0 and I am trying to create a model in my models.py which uses the user as a foreing key.I've looked through the documentation but couldn't find anything related to that matter. So right now my models.py looks like this: class Deck(models): deck_name = models.CharField(max_length=30) user_id = models.ForeignKey(USER_MODEL ) #what do I type here? class Card(models): card_back = models.CharField(max_length=150) card_front = models.CharField(max_length=150) card_strength = models.IntegerField() card_last_trained = models.DateTimeField() deck = models.ForeignKey(Deck, on_delete=models.CASCADE) -
Programatically trigger the rendering of a bokeh plot
I have a lot of plots on my page and I don't want them to fire all on page load, but trigger them as the user scrolls down, or after a while. I use the components module, so I'm unsure where to put a setTimeout or something like that. in Django view I have: from bokeh.resources import CDN from bokeh.embed import components script, div = components(plot.make_box_plot(), CDN) and then in tag: {% if div %} {{ div | safe }} {% endif %} {% if script %} {{ script | safe }} {% endif %} Does bokeh have some api for this? This doesn't work as I get a js syntax error: <script> window.plot_script = {{ script }}; // and then use in a js file inside setTimeout </script> -
Best Python Web framework for manipulating text? e.g. Django/Flask
I have written python code that compares two text files. I now want to implement this code dynamically within a webpage containing 2 text areas. Which framework would be the most ideal or easy to get this done? The main thing I want is quick functionality in implementing my code. Kind regards. -
Html class tag not detected within Jquery when datatables populated using a json dict
I have a datatable, with one of the columns with a "PRINT" option. The table visually looks like this: The HTML for the rows are loaded from a JSON dict generated from django views. The HTML for the column 3 is like this: <button class="classname_for_js"> PRINT IT </button> I have a javascript file: print.js: jQuery(".classname_for_js").on('click', printData); printData() is a function that calls a printing API for printing. For debugging I am trying to console: jQuery(".classname_for_js").on('click', function(){ console.log("Printing....."); }); However, I get nothing on the console. I have another datatable whose data is not populated from a json dict, for which the Print button works correctly. Is there anything I could be doing wrong? -
Django: Handle ValidationError in admin list view
I have a model with some custom validation rules. I have overwritten the model's save method like this: def save(self, *args, **kwargs): if not self.is_everything_OK(): raise ValidationError('Something went wrong') super().save(*args, **kwargs) It is registered in admin as an inline of another model. When I try to save it in the change form, django beautifully handles the error: However, if I edit the parent model in list view, django is unable to handles the error and shows the familiar yellow error screen (or error 500 in production mode) Should I place the validation rules to some other method, for instande model.clean()?