Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to store a list in Django (Not Postgres)
I have a mysql database and am storing a list. Im currently storing it as a CharField but dont know if this is the best way to do it. I know that I should be using an ArrayFeild if my db was postgres, but its MYSQL. I was content with this solution till I realized that the data was being stored like this:['COM', 'CRI', 'CUL', 'FOO'] whereas id expect it to be stored like this:[['COM'], ['CRI'], ['CUL'], ['FOO']]. forms.py TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), ('COM', 'Communication'), ) topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple()) models.py topics = models.CharField(max_length=200, default='') How the data is stored in my db: ['COM', 'CRI', 'CUL', 'FOO'] Thank you. -
DRF additional action without suffix
I am trying to use Django Rest Framework to perform an additional action from a viewset. In the urls I have: router = SimpleRouter() router.register(r'mymodels', MyModelViewSet, basename='mymodel') urlpatterns = [ url(r'', include(router.urls)), ] And in views.py: class MyModelViewSet(ListModelMixin, GenericViewSet): serializer_class = MyModelSerializer So I can send GET /mymodel/ request. I would like to be able to send PATCH /mymodel/, but I don't know how to configure the action. Currently I have: class MyModelViewSet(ListModelMixin, GenericViewSet): serializer_class = MyModelSerializer allowed_http_methods = ['get', 'patch'] @action(methods=['patch'], detail=False, url_path='', suffix='') def some_action(self, request: Request) -> Response: # do some stuff return Response() However, I have 405 method not allowed response. I can send data with PATCH /mymodel/some-action/, but I need to get rid of the last part of the url path. -
Django on migrate says relation does not exists
Hello this is not a common problem even thought this error is everywhere. I am using Django 2.2 + drf + postgresql My problem. After adding a new model. I have added a model serialzer which has a Charfield with choices. so my serializer looks something like that. class MySerializer(serializers.ModelSerializer): my_choice_field = serializer.CharField(choices = [obj.code for obj in Object.objects.all()]) When i run ./manage.py migrate it executes the serializer first and raises an error which says that the relation does not exists. What I have tried reorder INSTALLED_APPS run ./manage.py migrate my_app My goal To run migrations before loading the serializer -
filter between two model
I have two model shop1 and shop2 shop1 CATEGORY = ( ('BookShop', 'Bookshop'), ('Bakery', 'Bakery'), ('Dairy', 'Dairy'), Shop_category = models.CharField(max_length=200, choices=CATEGORY) Your_location = models.PointField() shop2 CATEGORY = ( ('BookShop', 'Bookshop'), ('Bakery', 'Bakery'), ('Dairy', 'Dairy'), Shop_category = models.CharField(max_length=200, null=True, choices=CATEGORY) Distance = models.PositiveIntegerField(null=True) Shop_location = models.PointField() i want set a filter where the the shop1 get the shame category of shop2 if the distnce given by shop2 less then or equall -
pip install vs python -m pip install [duplicate]
I would like to know if there are any diference between these two commands: $ python -m pip install Django Found in Django oficial documentation: https://docs.djangoproject.com/en/3.0/topics/install/#database-installation and this: $ pip install Django Which I found in the https://pypi.org/project/Django/ (Python official repository) Both to be typed in a virtual environment created previously: $ python3 -m venv venv Thank you. -
Create XML file using Python 3 for Django models
Here is my code: from xml.etree.ElementTree import tostring, Element, SubElement, Comment import xml.dom.minidom project=someModel.objects.get(id=1) root=Element(project.name) comment = Comment('Generated for '+project.name) root.append(comment) for p in someOther.objects.filter(pro_id=project.id): Title = SubElement(root, 'Title') Title.text = p.Title res=tostring(root, encoding='utf-8').decode('utf-8') dom = xml.dom.minidom.parseString(res) r = dom.toprettyxml() print(r) OR myfile=open('project.xml') myfile.write(r) myfile.close() So when i run this code i get the following error: "xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 12" Not getting any idea why i am getting this error. Is this because of "value of db" or "string formatting" So how can i fix this problem? pls help. -
How to pass extra context to Django Rest Framework serializers
It is my first project using Django rest framework and i'm struggling to get this right. I know that in mainstream Django framework, if i need to add extra contexts to a class-based view, i will do something like this: class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books by a certain author John context['john_books'] = Book.objects.filter(author=john) return context then, i will be able to access the context 'john_books' in my template. Now i need to do same by passing extra contexts to my PostViewSets. On the detail view, i want to access the list of post authored by that post author in my api endpoint (something like 'Posts from the same author'). I have read about get_serializer_context but still can't figure out how to implement it. This is what i have so far: class PostViewSets(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer def get_serializer_context(self): context = super(PostViewSets, self).get_serializer_context() author = self.get_object.author author_posts = self.get_queryset().filter(author=author) context.update({'author_posts': author_posts}) return context i get this error: AttributeError at /posts/ 'function' object has no attribute 'author' My Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) body = models.TextField() is_featured = models.BooleanField(default=True) viewcount = models.IntegerField(default=0) … -
Django list off item in which category containing some same item
Hi I have a model named ITEMS for some items ITEMS = item1, item2, item3, item4, item5, item6, item7 how can I do this... each item from ITEMS contains 4 categories uncategorized, cat1, cat2, cat3 and each category contain some items from ITEMS model except item in witch this category comes For example... item1 has 4 categories uncategorized, cat1, cat2, cat3 uncategorized = item7 cat1 = item2, item3 cat2 = item4, item5 cat3 = item6, item7 Those all categories cam be contained any of this item except item1 witch contains all 4 categories how can I achieve this type of model structure in Django..? if there is no such model. how can I do by own logic..? Thanks in advance if you need a more detail reply at any time. -
Table of contents
Django 3.0.6 Could you tell me whether there is a ready made application for generating table of contents similar to WordPress's plugins? Example of such a plugin: https://wordpress.org/plugins/table-of-contents-plus/ In the admin site one writes [TOC] and a table of contents is generated automatically. -
how to set source for for a foreign key in serializer django rest frame work
i have model as follows: class UserWorkspace(models.Model): workspace = models.ForeignKey( "Workspace", models.CASCADE, db_column="workspace_uuid" ) user = models.ForeignKey("User", models.CASCADE, db_column="user_uuid") and i need to change the name in serializer i tried: class UserWorkspaceSerializer(serializers.ModelSerializer): workspace_uuid = serializers.PrimaryKeyRelatedField(source="workspace", queryset=Workspace.objects.all()) user_uuid = serializers.PrimaryKeyRelatedField(source="user", queryset=User.objects.all()) class Meta: model = UserWorkspace fields = ("workspace_uuid", "user_uuid") but i get the error return self.fields[key] KeyError: 'workspace' -
How to send message on django channel to all users before disconnect
i am trying to send a message to all users before a client disconnects(when client leaves the page). def disconnect(self, close_code): # Leave room group self.user = self.scope["user"] self.send(text_data=json.dumps({ "message": self.user.username, "typeMessage": "lobby", "created": False, })) print("Try to send the message") async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) This is the function where i try to send the message but it doesn't work. The print function works, "Try to send the message" is displayed on terminal's output. If you could help me with a suggestion that would be great. Thank you! -
Custom Model action/function in django admin
I am trying to send newsletters as emails to the subscribed users. For that, I did: I made a Custom send_mail() function within my model to send emails to subscribed users class Post(models.Model): 'model fields here' def __str__(self): return self.title + ' by ' + self.author def send_mail(self, request): content = self.content title = self.title slug = self.slug series_name = self.series_name confirmed_subscribers = Subscriber.objects.values_list('email').filter(confirmed=True) current_site = get_current_site(request) subject = "New Blog - '" + title + "' @ AM-Blogs!!" message = render_to_string('new_post.html',{ 'title': title, 'content': content, 'slug': slug, 'series_name': series_name, 'domain': current_site.domain, }) for sub in confirmed_subscribers: email = EmailMessage( subject, message, settings.EMAIL_HOST_USER, [sub], ) email.fail_silently = True email.send() return redirect ('Home') Then, in admin.py: class PostAdmin(admin.ModelAdmin): class Media: js = ('tinyInject.js',) actions = ['send_mail'] def send_mail(self, request, queryset): for post in queryset: post.send_mail(request) send_mail.short_description = "Send selected Newsletters to all subscribers" admin.site.register(Post, PostAdmin) And when I got to my admin panel and perform the action: Error: ValueError at /admin/blog/post/ not enough values to unpack (expected 2, got 1) Highlighted Error: D:\My_Projects\My-Blog\blog\admin.py in send_mail post.send_mail(request) … ▶ Local vars D:\My_Projects\My-Blog\blog\models.py in send_mail email.send() … ▶ Local vars How can I solve this issue? Please help!! -
Django calculate difference between rows in ORM
What I'm trying to do is avoid a potentially expensive calculation that I do after retreiving a queryset, but doing it during the query, but I'm not sure if it's possible. For example, if I have a model like: class DailyUsers(model.Model): date = models.DateField() users = models.IntegerField() And I do the following annotation: queryset = models.DailyUsers.values("date", "unique_users") >> [ {"date": "2020-01-01", "users": 10} {"date": "2020-01-02", "users": 10} {"date": "2020-01-03", "users": 20} {"date": "2020-01-04", "users": 20} {"date": "2020-01-05", "users": 21} ] I then need to perform the following calculation: result_dict = {obj["date"]: obj["unique_users"] for obj in queryset} result_dict_diff = {} for k, v in result_dict.items(): k_prev = k - relativedelta.relativedelta(days=1) if k_prev in result_dict: result_dict_diff[k] = result_dict[k] - result_dict[k_prev] else: result_dict_diff[k] = result_dict[k] >> { "2020-01-01": 10, "2020-01-02": 0, "2020-01-03": 10, "2020-01-04": 0, "2020-01-05": 1, } The calculation essentially subtracts the previous days users from the current day for the new value (skipping the first day). Is there a way to do this in the orm? I don't mind if the end result is in the queryset and not a dict structure. -
Filtering a Queryset on multiple values of same attribute
My models.py looks like class Entity(models.Model): name = models.CharField( max_length=256, verbose_name="Entity Name" ) def __str__(self): return self.name class AttributeValue(models.Model): entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="attribute_values" ) value = models.CharField(max_length=9112, verbose_name="Attribute Value") def __str__(self): return self.value and queryset = Entity.objects.all() Now I wan't to filter all the entities which have attribute values abc and def i.e for example one entity { "id": 1, "name": "XYZ", "attribute_values": [ { "id": 1, "value": "abc", "entity": 1 }, { "id": 2, "value": "def", "entity": 1 }, ] } -
ReactJS - How to log the specific field that is causing a 400 error code when submitting form
I am currently working on a web app that uses ReactJS as the frontend, and DRF as the backend, and I am working on the form validation right now. In the backend, for fields that are phone numbers, I am using PhoneNumber field, which is a Django library that interfaces with python-phonenumbers to validate phone numbers keyed in. Hence, I was thinking that it would be best if I do my form validation based on the response from the DRF api post request, since it would be tough for me to come up with a regex that completely complies with the PhoneNumber field's requirement. Hence, I am trying to figure out if it is possible for the axios error response to specifically tell me which field is causing the 400 error code. If so, I can then display the relevant error like 'This is not a phone number' above the relevant fields. Or if not, is there any better way for me to handle this and be able to align completely with the PhoneNumber field's requirements? Basically I do not want to run into an issue where the phone number passes the ReactJS form validation but fails the Django PhoneNumber … -
python insert multiple rows from dataframe to mysql
I am working on a legacy django code where raw queries are used. Here each rows from dataframe is iterated and insert statement is created for each row and committed. In addition to data from dataframe, I also need to add other additional data to insert, so I cannot directly use some .to_sql methods and have to iterate it. from django.db import connections # Insert DataFrame recrds one by one. with connections['frontend'].cursor() as cursor: ad_blog = 'STATIC_BLOG_TEXT' ad_by = 'STATIC_BLOG_INTEGER' for i,row in data.iterrows(): sql = "INSERT INTO book_details (`df_name`, `df_title`, `ad_blog`, `ad_by`) VALUES ('" + row[0] + "', '" + row[1] + "', '" + ad_blog + "', '" + ad_by + "' )" cursor.execute(sql) connection.commit() Since the dataset has grown now into almost million rows, this might slow the task. How can I create a bulk insertion? Is there any multi=Truekind of option that facilitates bulk insertion? -
How to configure MySQL 5.5 in order to store high codepoints?
Thank you in advance for your time reading this. I am currently developing a project in Django 2.X (python 3.7.4) which uses MySQL 5.5 as DB. This project consumes data from an external API and occasionally raises the following error when trying to persist the data consumed (as a specific string taken from a JSON): mymodel.value = mystring # string taken from the JSON mymodel.save() ... django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x8E\\xA8' for column 'value' at row 1") I have isolated one of the JSON strings that causes the trouble and I have checked each one of the characters as follows: for i in mystring: print(i, ord(i)) which returns: ... d 100 ! 33 32 127912 When attempting to save the string without the last character works like a charm, so my guess is that codepoint 127912 might be the cause of the problem. I have also modified the charset of the column in the database table as follows: ALTER TABLE <my_table> CHANGE COLUMN value value LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL; * Field: value * Type: longtext * Collation: utf8mb4_unicode_ci * Null: NO * Privileges: select,insert,update,references With no luck Any suggestions in order to save the string? -
Django/Nginx: statics files are not served
I try to deploy my Django project in a remote server using Nginx but my files are not served. I guess my path is incorrect but don't really know why... python3 manage.py collectstatic get all my files in intensecov_static folder. /home/zebra/ - intensecov_app - intensecov - coverage (project) - manage.py - static - ... - intensecov_static - css - style.css - images - ... settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), os.path.join(BASE_DIR,'randomization_management/static'), os.path.join(BASE_DIR,'randomization_settings/static'), os.path.join(BASE_DIR,'randomization/static'), ) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = '/home/zebra/intensecov_static' /etc/nginx/sites-available/intensecov server { listen 80; server_name 192.168.80.9; root /home/zebra/intensecov_app; location /static { alias /home/zebra/intensecov_static; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; break; } } } -
How do I make custom templates for django_social_share?
I have followed every steps in installing and using django-social-share. When I loaded social_share on my detail page where I want it displayed, it worked fine using the default templates. Nothing was displayed when I tried to override the default templates. I have the template in root_dir/templates/templatetags/post_to_facebook.html. I don't know why nothing displayed when I try to use those custom templates- neither the custom templates nor the default one displayed. Any help will be appreciated. Here's my files settings.py INSTALLED_APPS = [ # Local apps 'users.apps.UsersConfig', 'pages.apps.PagesConfig', 'blog.apps.BlogConfig', # Third party 'django_social_share', 'crispy_forms', . . . TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] . . . post_to_facebook.html <span class="w3-badge w3-hover-blue facebook-this"> <a href="{{ facebook_url }}" class="w3-xlarge" target="_blank" title="Share on Facebook"><i class="fa fa-facebook"></i></a> </span> post_to_twitter.html <span class="w3-badge w3-hover-blue tweet-this"> <a href="{{ tweet_url }}" class="w3-xlarge meta-act-link meta-tweet" target="_blank" title="Share on Twitter"><i class="fa fa-twitter"></i></a> </span> post_detail.html {% extends 'base.html' %} {% load social_share %} {% load static %} {% block title %} {{ post.title }} {% endblock title %} {% block content %} <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <h1>{{ post.title }}</h1> <p class="date">Published {{ post.publish }} … -
Scorm implementation in LMS
I have an LMS developed in Django and now I want to make it SCORM compliant but I don't know how to implement it in LMS. I read articles about SCORM but it didn't help me much regarding the development. So I need help regarding the steps to implement it in existing LMS. -
Correct way to use async class based views in Django
I am trying to use the very new Django 3.1 Async view classes. Based on the limited documentation available, I have tried to create my own async def __call__() method. From the documents: For a class-based view, this means making its __call__() method an async def (not its __init__() or as_view()). Django 3.1 Development Documents However, until now I have had no luck with writing an asynchronous class based view. I constantly get await exceptions, or asyncio.iscoroutinefunction returns False, which I assume should return true if the class is actually Asynchronous. Since the documentation is lacking an example, could someone with more knowledge of async programming help me with an example of a class based asynchronous view? -
Django project structure with multiple apps
I intend to make a django project with multiple apps. The main folder shall have a base.html which shall have links to different apps. The apps will have their own template directory. -myproject -__init__.py -settings.py -views.py -urls.py -admin.py -test.py -app1 -templates -abc.html -views.py -urls.py -app2 -templates -abc2.html -views.py -urls.py What are the configuration I should make in settings.py? -
Django dropdown menu 2 seperate classes concerning 1 item
My second post about Django, but it’s all new for me so need a bit of guidance. I have made an ERD of an app i want to create. It’s having to give the options to make notes about items whom I get offered in a repairshop. The items have to be the kind Smartphone, Personal Computer or Else. I changed the classes names in english, but im dutch so i left the 'attributes' as they were: my code I split these columns in two because I only have to store the Smartphone, Personal Computer and Else once and just Reference to it with a FK from the Class Item. I think the idea is good, but how do implement this into practice. In my knowledge it more easy to add a form into class Item and then offering a dropdownmenu of smartphone, pc or else. But this is not what I want. Any ideas or thoughts where I can find answers best way doing this? With kind regards, Florus -
ValueError: dictionary update sequence element #0 has length 25; 2 is required When Unpacking a tuple with a dictionary
I get the following error when unpacking this dictionary when referenced from the method generate_pdf which now when assigned this method as conext = self.get_context(self) <--- returns a tuple and not the dictionary ? why and how can i get the key and value that are within the dictionary in the fuction/method in generate_pdf and so that i can use them in an EmailMessage object Below function is use it populate context def get_context(self, state=None): utility= ... customer= ... context = snoop.pp("get_context dict", { 'document': self, 'utility': utility, 'utility_email': self.utility.email, 'customer': self.customer, 'customer_first_name': self.customer.customer_first_name, 'customer_last_name': self.customer.customer_last_name, 'customer_email': self.customer.customer_email, 'docs': self._docs, 'state': state }) It returns a dict , now i call it or reference to it as context = self.get_context(state) here i want to unpack so i get the customer_email value and send email but i keep getting def generate_pdf(self, state=None, upload=True): # !!! ensure this is not called concurrently for the same document context = self.get_context(state) snoop.pp(type(context)) for f,d in enumerate(context): f, d snoop.pp(print(f,d)) document, utility, utility_email, customer, customer_first_name,customer_last_name, customer_email, docs, state = context snoop.pp("customer_email ", customer_email) snoop.pp(context) context_dict = dict(context) for key, value in context_dict.items(): snoop.pp('Value', value) snoop.pp("Done") snoop.pp("Get Customer Email From Context ", context.customer_email) object = self.pdf.generate(template=self.get_template(state), … -
Django UpdateView user validation not working
Hello guys I have this update view where I am not able to validate the user(owner). How to tweak this to add that bit too.? Please have a look at the code. class StoreInfoView(UpdateView, LoginRequiredMixin): model = Store template_name = 'store/store_information.html' form_class = StoreInfoForm success_message = 'Updated' success_url = reverse_lazy('store:store_home') def get_object(self, queryset=None): obj = Store.objects.get(id=self.kwargs['id']) if obj.user != self.request.user: raise PermissionDenied('You Don\'t have permission to edit!') return obj def get(self, *args, **kwargs): self.object = Store.objects.get(id=self.kwargs['id']) form_class = self.get_form_class() form = self.get_form(form_class) context = self.get_context_data(object=self.object, form=form) return self.render_to_response(context) Thanks