Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to specify Django UniqueConstraint for GeoDjango PointField to prevent duplicate points within some tolerance
I'd like to ensure that users cannot enter duplicate coordinates in my database (stored as a geodjango PointField). Django's UniqueConstraint feature permits this, but to my knowledge only excludes exact matches. It would be more useful to prevent coordinates being within some tolerance (e.g. 1m) of one another. Is there an easy way of achieving this with UniqueConstraint? Or if not, what is the best approach? E.g. perhaps writing some custom SQL for BaseConstraint? -
Django queryset for near by vendors by their delivery_target using geolocation
Good afternoon. I don't have much experience with querysets and I'm writing a Django app and I'm having trouble resolving an impasse. In this app, I wanted users to determine the distance of the stores to be shown based on a given radius: top_vendors = Vendor.objects.filter(user_profile__location__distance_lte=(pnt, D(km=RADIUS))).annotate(distance=Distance("user_profile__location", pnt)).order_by("distance") I then created a vendor field to give the vendor a RADIUS delivery so they can limit the distance they can deliver. vendor_max_delivery_distance = models.PositiveIntegerField(default=0) I would like some help to add one more condition to the queryset which would be to limit the list of vendors to the distance established by the user matched with the distance that the vendor can deliver. It's inside RADIUS (already done in top_vendors code) In addition to being within the RADIUS defined by the user, the vendor_max_delivery_distance also meets within this RADIUS. Item number two is driving me crazy from trying to find a solution. If anyone has experience and can help me I would be very grateful! Thank you very much. -
Create Django admin action to save a list of selected objects to another table
I am working on a bjj tournament app. It would take competitors' registration: Name, weight, and rank. I was able to set up the form and save the information into the admin panel. How to create an "action" in the admin panel to allow the admin to choose and create separate groups from the existing table? For example: Eric C - 180 - W Donny W - 160 - B Banaa O - 150 - B Claudi B - 145 - P Nikki R - 160 - B Jordan M - 175 - B How to create an action that let me choose 1,2,4 into a Group 1 (another table in the database) and 3,5 into group 2, and 6 into group 3. Thanks, ChatGPT suggested this but it didn't work """def create_group(modeladmin, request, queryset): # Get the name of the current table table_name = queryset.model._meta.db_table # Create other tables based on the current table with connection.cursor() as cursor: cursor.execute(f"CREATE TABLE {table_name}_other (id INT PRIMARY KEY);") cursor.execute(f"CREATE TABLE {table_name}_more (id INT PRIMARY KEY);") # Display a success message modeladmin.message_user(request, f"Created other tables based on {table_name}.") class MyModelAdmin(admin.ModelAdmin): actions = [create_group] admin.site.unregister(Competitors) admin.site.register(Competitors, MyModelAdmin) """ -
Create custom user model using django with customized fields with authentication
I want to create a user model with two fields (username, code) both are cahrfield with no more other fields just these two and I want to Authenticate this model everytime I create one that is all I would be thankful if you help me🙏🏻 -
Django form error "this field is required" after HTMX request
I'm using HTMX lib to send the requests with Django. The issue is that after succeed htmx request with project_form swapped project_detail_form comes with "this field is required". What am I doing wrong? This is my views.py: def index(request): """Index view.""" project_form = ProjectForm(data=request.POST or None) project_detail_form = ProjectDetailForm(data=request.POST or None) if request.method == "POST": try: if project_form.is_valid(): project_form.save() return render( request, "monitor/_project_detail_form.html", context={"project_detail_form": project_detail_form}, ) except Exception as e: return HttpResponse(f"Error: {e}") return render(request, "monitor/index.html", context={"project_form": project_form}) A part of index.html <form class="pt-4" hx-post="/" hx-target="this" hx-swap="innerHTML" enctype="multipart/form-data"> {% csrf_token %} {{ project_form.as_div }} <button class="btn btn-primary" type="submit">Save</button> </form> _project_detail_form.html {% csrf_token %} {{ project_detail_form.as_div }} <button class="btn btn-primary" type="submit">Save</button> forms.py class ProjectForm(forms.ModelForm): """Project form.""" name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"})) check_interval = forms.IntegerField( widget=forms.NumberInput(attrs={"class": "form-control"}) ) is_active = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "form-check"}) ) class Meta: """Meta.""" model = Project fields = "__all__" class ProjectDetailForm(forms.ModelForm): """Project Detail form.""" project = forms.ModelChoiceField( queryset=Project.objects.all(), widget=forms.Select(attrs={"class": "form-select"}), ) url = forms.URLField(widget=forms.URLInput(attrs={"class": "form-control"})) pagination = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={"class": "form-control"}) ) is_active = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "form-check"}) ) class Meta: """Meta.""" model = ProjectDetail fields = ["project", "url", "pagination", "is_active"] -
duplicate key value violates unique constraint error in django in a many-to-one relationship
I'm trying to set-up a database in django, given the following relationships: class Team(BaseModel): class Meta: db_table = '"teams"' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, null=False, blank=False, max_length=100) members = models.ManyToManyField(User, through='TeamMember', related_name='members', related_query_name='members') creator = models.ForeignKey(User, unique=False, null=True, on_delete=models.SET_NULL, related_name='created_teams', related_query_name='created_teams') team_admins = models.ManyToManyField(User, through='TeamAdmin', related_name='admin_teams', related_query_name='admin_teams') class User(AbstractUser): class Meta: db_table = '"users"' username = None email = models.EmailField(blank=False, unique=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] In essence, I want to set-up a many-to-one relationship between the class User and the class Team via "Creator". A Team can only have one Creator user, but a single user can be the Creator for multiple Teams. To do that, I'm using models.ForeignKey. However, whenever I try to create an additional team using the same user, I get the error: "duplicate key value violates unique constraint "teams_creator_id_key"". Is there something wrong with how I set up this many-to-one relationship? I've tried setting the ForeignKey definition with unique=False, removing that flag altogether, and nothing seems to work. As a sidenote, to create a new Team im using a serializer with the following code: def create(self, validated_data): user = User.objects.get(id=self.context['user_id']) team: Team = Team.objects.create( name = validated_data.get('name'), creator … -
How can you create a custom InlineEntityElementHandler in Wagtail CMS?
I'm trying to create a custom rich text feature which mimics the behaviour of richtext's link feature. The only differences are another name, and adding a class to it. Because we need two different types of links in the frontend (Headless setup). And it's essential that we have the Link Chooser interface (Page, external, email etc.). I tried the following, but now both Link handlers (built-in and custom) have the "arrow" class: @hooks.register('register_rich_text_features') def register_arrow_link(features): feature_name = 'arrow' type_ = 'LINK' tag = 'a class="arrow"' control = { 'type': type_, 'label': '->', 'description': 'Arrow Link', } features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature(control) ) db_conversion = { 'from_database_format': {tag: InlineEntityElementHandler(type_)}, 'to_database_format': {'entity_decorators': {type_: tag}} } features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append(feature_name) -
.gitignore file in django
i should do a push of my small project in django/redis and python on github but i noticed that after creating some users and doing the push, they are also saved on github. Reading on the internet I should create a gitignore file but I don't know what to write in it. I should obviously save the migrations but not the data that has been entered in the database. i found a file on gitignore.io but i am not sure if everything in it fits my case. do you have any tips or sites where i can check this? -
How can the carriage return \r\n in a text which is put in an HTML cell with Django be interpret as carriage return and not present the \r\n?
I have as input a text block with several lines separated by \r\n. I'm extracting the information with Django and putting into a model as TextField, e.g. info = models.TextField() b'Hey\r\n\r\nIn regards to your letter sent ...' Inside a Django template I put the text into an HTML cell {{ letter.info }} When the HTML table is presented, the text is shown as one line with the \r\n visible as part of text. Is there a way to make that the text is presented in different lines? i.e. that the \r\n are interpreted as the carriage return and not presented raw? I've tried some suggestions I found for similar questions, as using style="white-space: break-space" pre-line; pre-wrap but that did not work. I've also tried to replace the \r\n with <br/>, but the raw is presented instead and the line is not broken. -
Send StreamingHttpResponse in django channels
Exception inside application: 'StreamingHttpResponse' object has no attribute 'encode' Traceback (most recent call last): File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\utils.py", line 50, in await_many_dispatch await dispatch(result) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\generic\websocket.py", line 194, in websocket_receive await self.receive(text_data=message["text"]) File "C:\Users\Tamerlan\Desktop\chatbot_project\chatbot_app\consumers.py", line 28, in receive await self.send(text_data=response) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\generic\websocket.py", line 209, in send await super().send({"type": "websocket.send", "text": text_data}) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\consumer.py", line 81, in send await self.base_send(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\channels\sessions.py", line 226, in send return await self.real_send(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\server.py", line 240, in handle_reply protocol.handle_reply(message) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\ws_protocol.py", line 202, in handle_reply self.serverSend(message["text"], False) File "C:\Users\Tamerlan\Desktop\chatbot_project\venv\lib\site-packages\daphne\ws_protocol.py", line 256, in serverSend self.sendMessage(content.encode("utf8"), binary) AttributeError: 'StreamingHttpResponse' object has no attribute 'encode' I … -
Creating a Django project on an existing empty git repository
I'm pretty much new at programming using Mac, Django, Python and PyCharm. I wanted to create my first project and ran into the following problem: For this project I want to use Python 3.7, so I installed it into my Mac using pyenv install 3.7 And set a virtual environment with this line: pyenv virtualenv 3.7.16 python-3.7 Then, for the project I got an empty git repository and cloned it into my /opt/ folder. I opened it with Pycharm and it appears to be empty, just as expected. Then, I went to Files >> New Project, selected Django project and set the location of the project to the folder created during the clone, so the path is /opt/my-first-project. Then, I set the interpreter to be the environment previously created. I get this warning on screen that says Project name should only contain letters, numbers and underscores. For the tests I've done, I guessed this refers to the name of the folder, my-first-project in this case. This is the name of the git repository, and since I'm not the owner of the repository I cannot change that name. How should I create a new Django project inside this repository? -
Exception in logging module itself is not sent to sentry
Django app on python 2 (yeah I know). The sentry integration is working well otherwise, but looks like it doesn't record crashes in logging itself, for instance when passing insufficient arguments to logger.info(). In this case the incriminating line was something like: logger.info('some info about %s and %s', my_thing) i.e. missing an argument. This traceback showed up in heroku logs but nothing in sentry: Apr 27 23:35:32 xxx app/web.9 Traceback (most recent call last): Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 868, in emit Apr 27 23:35:32 xxx app/web.9 msg = self.format(record) Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 741, in format Apr 27 23:35:32 xxx app/web.9 return fmt.format(record) Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 465, in format Apr 27 23:35:32 xxx app/web.9 record.message = record.getMessage() Apr 27 23:35:32 xxx app/web.9 File "/usr/local/lib/python2.7/logging/__init__.py", line 329, in getMessage Apr 27 23:35:32 xxx app/web.9 msg = msg % self.args Apr 27 23:35:32 xxx app/web.9 TypeError: not enough arguments for format string Apr 27 23:35:32 xxx app/web.9 Logged from file models.py, line 18407 Do I need to do something for sentry_sdk to include whatever context the logging module is running in as well? -
Using django-tinymce with django-filebrowser to upload images to a blog post
I am implementing django-tinymce together with django-filebrowser to be able to include media files in the text editor of a blog. Everything seems to be working fine, but when I click on the image button in the text editor, the dialog box doesn't include a button to upload a file. I have gone through the threads on this topic in the forum but cannot find a solution to solve it. These are the settings: INSTALLED_APPS = [ # file-browser 'grappelli', 'filebrowser', ... 'tinymce', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' #django-filebrowser: # Path to filebrowser static files FILEBROWSER_DIRECTORY = 'filebrowser/' FILEBROWSER_STATIC_URL = STATIC_URL + 'filebrowser/' FILEBROWSER_MEDIA_ROOT = BASE_DIR / 'media/uploads/' FILEBROWSER_MEDIA_URL = '/filebrowser/media/' FILEBROWSER_SORT_BY = 'date' FILEBROWSER_MAX_UPLOAD_SIZE = 10485760 # 10 MB EXTENSIONS = { 'Image': ['.jpg','.jpeg','.gif','.png','.tif','.tiff'], 'Video': ['.mov','.wmv','.mpeg','.mpg','.avi','.rm'], 'Audio': ['.mp3','.mp4','.wav','.aiff','.midi','.m4p'], 'Document': ['.pdf','.doc','.rtf','.txt','.xls','.csv','.docx','.xlsx'] } SELECT_FORMATS = { 'File': ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'zip', 'rar', 'tar', 'gz', 'bz2', 'csv'], 'Image': ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'], 'Video': ['swf', 'flv', 'mpg', 'mpeg', 'mp4', 'mov', 'avi', 'wmv'], } #django-tinymce TINYMCE_JS_URL = 'https://cdn.tiny.cloud/1/{api-key}/tinymce/5/tinymce.min.js?referrerpolicy=origin' TINYMCE_DEFAULT_CONFIG = { "theme": "silver", "height": 500, "menubar": True, "plugins": "advlist,autolink,lists,link,image,charmap,print,preview,anchor,searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste,code,help,wordcount," "searchreplace,visualblocks,code,fullscreen,insertdatetime,media,table,paste," … -
Django not showing messages after redirect
I'm using Django 4.0.9, and I'm trying to show a message using django-messages after a user has been created and after it has been deleted. Using prints I can see that the messages get created when the create/delete form executes, but when the messages are printed after the redirect to the homepage they don't exist in the Django system anymore. The interesting part is that if I set the setting DEBUG = True to my 'settings.py' everything works as intended, if DEBUG = False I get the error mentioned above. I'm not sure if the DEBUG setting deletes the cache, doesn't take the messages after the redirect or anything of that kind. This is my view when the user is deleted: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.contrib import messages from .models import User from .forms import DeleteUser def delete_user_view(request): if request.user.is_authenticated: if request.method == 'POST': form = DeleteUser(request.POST) if form.is_valid(): if request.POST["delete_checkbox"]: rem = User.objects.get(username=request.user) if rem is not None: rem.delete() logout(request) messages.info(request, "Il tuo account è stato cancellato.") # This is the print that let's me see the messages BEFORE the redirect allMsg = messages.get_messages(request) print('---------------- START MSG DELETE USER … -
Python djnago coverage : The name "coverage" is not recognized as the name of the cmdlet
I'm using python 3.10, django 4, windows 10, when I type into the console, coverage report outputs an error coverage : The name "coverage" is not recognized as the name of a cmdlet, function, script file, or executable program. Check the spelling of the name, as well as the presence and correctness of the path, and then try again. line:1 sign:1 coverage CategoryInfo : ObjectNotFound: (coverage:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException coverage I have installed I tried to install coverage via pip and through the pychrm interface I tried to enter python coverage but nothing helped -
Website can not fetch from the Django API when secured with HTTPS [closed]
My React.js website is hosted by IONOS company, together with a domain name. It fetches data from a Django REST Framework API, hosted on a virtual server at another address (it fetches through an IP address, the virtual server is not associated with a domain name). The API is run with Gunicorn and Supervisor. Everything works perfectly when the website is not secured. But as soon as I configure the web server of the website to use HTTPS, the website can not fetch from the API anymore : it gets “Connection refused” responses. What should I do to enable the HTTPS website to fetch my Django API ? I’ve been searching for a while, found suggestions to enable connections from a front-end to a back-end, but nothing to deal with requests from web browsers using HTTPS. Help required, thanks ! -
How should we do order_by in Django ORM for self-referred sub objects?
Have an issue with a somewhat problematic ordering/sorting in Django ORM. What I have is a Venue with a FK to self, thus the potential for sub-venues: # models.py class Venue(models.Model): company = models.ForeignKey(to="Company", related_name="venues", on_delete=models.CASCADE) parent = models.ForeignKey( to="self", related_name="children", on_delete=models.CASCADE, null=True, blank=True ) ordering = models.PositiveSmallIntegerField(default=0) # ... This is how it looks like in the custom dashboard we've built. We're doing something akin to: Venue.objects.filter(parent__isnull=True) and then, for each venue, we're doing obj.children.all(), thus creating this layout: # find all parent=None, then loop over all obj.children.all() Spain (ordering=0, parent=None) - Barcelona (ordering=0, parent="Spain") - Castelldefels (ordering=1, parent="Spain") - Girona (ordering=2, parent="Spain") Singapore (ordering=1, parent=None) This is what we want to see when requesting our API endpoint: // json response [ {"venue": "Spain", "ordering": 0}, {"venue": "Barcelona", "ordering": 0}, {"venue": "Castelldefels", "ordering": 1}, {"venue": "Girona", "ordering": 2}, {"venue": "Singapore", "ordering": 1} ] Problem is when we're calling the API, is that we're also using django-filters in our ModelViewSet thus we can't filter on parent__isnull=True or we won't see the children in the API response. We still have access to the queryset in the def list-method before returning it to the serializer. Question is: how do we set the … -
encoding password in django
Why isn't the password received from the user during registration coded and encrypted in the database in the Django framework? Why isn't the password received from the user during registration coded and encrypted in the database in the Django framework -
Django nested transacion.atomic() questions. Is it significant what exception is raised to abort a transaction?
I'm writing code which is basically to upload a spreadsheet. Each row requires the creation of multiple DB objects and relationships. If the data in the row is incapable of being stored, I want to tell the user about the problem, abort the transction representing this row, and continue with the next row. But if there's a more disastrous failure or "too many errors", I want to abort the outer transaction to commit nothing at all to the DB. Is there any particular recommended Python or Django exception class to subclass, to generate exceptions for this purpose? And can I safely catch IntegrityError in the row-processing code so as to issue the best possible error to the user, and then exit the inner transaction by railsing a different exception? I'm thinking Class CannotStoreRow( ValueError): pass, because something in that row of data is an invalid value. Is there any reason something other than ValueError should be used? (Why doesn't Django supply something like AbortTransaction, or does it? ) Overall outline code: try: with transaction.atomic(): process_spreadsheet() except CannotContinueLikeThis: # tell user we have given up and reassure that the DB is unaltered # uncaught exception, DB likewise undamaged? def process_spreadsheet(): # … -
Django ORM: move filter after annotate subquery
This Django ORM statement: Model.objects.all() \ .annotate( ord=Window( expression=RowNumber(), partition_by=F('related_id'), order_by=[F("date_created").desc()] ) ) \ .filter(ord=1) \ .filter(date_created__lte=some_datetime) Leads to the following SQL query: SELECT * FROM ( SELECT id, related_id, values, date_created ROW_NUMBER() OVER ( PARTITION BY related_id ORDER BY date_created DESC ) AS ord FROM model_table WHERE date_created <= 2022-02-24 00:00:00+00:00 ) WHERE ord = 1 As you can see, the date_created__lte filter gets applied on the inner query. Is it possible to control statement location preciser and move the filter outside, like ord? -
Django how to export datetime from MySQL to csv as correct format
I can show datetime from mysql by convert datetime of mysql to string like this code. upd_time = str(log.updated) Then, I use javascript to convert to date like this <script> const dateFromMysql = '{{ upd_time }}'; // conver the string into javascript date object const dateObject = new Date(dateFromMysql); // output complete date in javascript document.getElementById("dt").innerHTML = dateObject; </script> It show correct date. I export datetime from mysql to csv with this code. def export_csv(request): key=request.POST['key'] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename= '+ str(key)+".csv" writer = csv.writer(response) writer.writerow(['field1','field2','updated']) users = Data.objects.filter(key=key).values_list('field1','field2','updated') for user in users: writer.writerow(user) return response In column updated show the time like this. It is UTC timezone. I change TIME_ZONE and USE_TZ in setting it show same time format in mysql. How to export datetime from csv to local timezone? -
How to show reversed foregin key in DRF
I have 2 model and i want to Retrieve all info about card and his reversed foreign key but when i try to do that i get only Card field and not DigitalCard fields models.py class Cards(models.Model): user = models.ForeignKey(IndividualUser, on_delete=models.CASCADE) main_business_card = models.ForeignKey('UserDigitalCard', on_delete=models.PROTECT, null=True, blank=True) class UserDigitalCard(models.Model): card = models.ForeignKey(Cards, on_delete=models.CASCADE) digital_card = models.FileField(blank=True, null=True, upload_to=digital_card_upload_to) digital_card_name = models.CharField(max_length=100) generated_code = models.CharField(max_length=30, default=generate_code) serializer.py class GetDigitalCardSerializer(serializers.ModelSerializer): class Meta: model = UserDigitalCard fields = ('digital_card', 'digital_card_name', 'generated_code') class GetCardSerializer(serializers.ModelSerializer): digital_cards = GetDigitalCardSerializer(read_only=True, many=True) class Meta: model = Cards fields = ('user', 'main_business_card', 'digital_cards') views.py class GetUserCards(generics.RetrieveAPIView): queryset = Cards.objects.all() serializer_class = GetCardSerializer permission_classes = (IsAuthenticated, ) thats what i`ve got { "user": 1, "main_business_card": 6 } -
how to add a huge amount of data in database using Django/python
I am trying to add a huge amount of data in my Django app, data is about 800k, and am calculating some kind of distance and adding an empty field in every input. here is how my models.py looks : class MapLayers(models.Model): """ This Model Saves the KML Files to be shown as map layers in the application """ directory_string_var = "upload/files/" # Fields created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_( "Date Created"), help_text=_("Date the layer created at")) last_updated = models.DateTimeField(auto_now=True, editable=False, verbose_name=_( "Last Update"), help_text=_("Date the layer was last updated")) file = models.FileField(upload_to=get_file_path, help_text=_('Uploaded File'), verbose_name=_('File')) name = models.CharField(max_length=100, help_text=_('Map Layer name'), verbose_name=_('Map Layer name')) category = models.ForeignKey( LayersCategory, on_delete=models.CASCADE, null=True, verbose_name=_("Category"), help_text=_("Category of the current being uploaded layer")) element_count = models.IntegerField(default=0, verbose_name=_("Elements Count"), help_text=_("Shows how many elements inside this file")) class Meta: """ Define the name user will see this model in the admin dashboard """ verbose_name = _('Map Layers') verbose_name_plural = _('Map Layers') def __str__(self): """ Define the object viewable name in the admin dashboard """ return str(self.pk) class WaterElement(models.Model): """ Saves the Name of the internal elements inside every layer """ element_name = models.CharField(max_length=100, verbose_name=_("Element name"), help_text=_("The name of the water element")) map_layer = models.ForeignKey(MapLayers, on_delete=models.CASCADE, verbose_name=_("Map Layer … -
Django error path does not exist. Static files sometimes do not load
I have a weird problem with my app in Django. The link for the app is www.mativated.com. The problem is - sometimes the app loads normally, but very often, some static files do not load - that's why it looks like page is bugged. These are the logs. I am using Whitenoise to serve files in development. My settings are: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I checked the file logo.removebg, and whenever it appears it is called correctly - like this src="{% static 'main/img/logo-removebg.png' %}"> I've been fighting with all these static files since one month, I am looking for any help, advice. I can give you access to files, or give more specific informations. Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/views/static.py", line 40, in serve raise Http404(_("\u201c%(path)s\u201d does not exist") % {"path": fullpath}) django.http.response.Http404: \u201c/home/srv52965/main/staticfiles/main/img/logo-removebg.png\u201d does not exist During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 880, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During … -
Is it able to patch Django thread_sensitive for tests?
I use sync_to_async with thread_sensitive=False for async django view like this: @sync_to_async(thread_sensitive=False) def get_some_from_db(): ... But in test cases all handlers marked as thread_sensitive=False returns None. Is there any way to patch thread sensitive on True only for tests?