Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CPanel MEDIA_ROOT configuration
I have setup my Django project on CPanel. On my python setup page on Cpanel, I have mentioned my Application Root as "example" (where i have uploaded all files) and my Application Url as "example.com" settings.py contains MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py under my app contains urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py contains a field documentFile = models.FileField(upload_to='documents/files/completed/%Y/%m/%d') Now I can see two folders on CPANEL example (where i have uploaded all my files) example.com (I have not made any changes to it) I was able to visit example.com, and everything works absolutely fine. I was able to upload to file to 'documents/files/completed/%Y/%m/%d' When i check i can physically see that the file is created under the folder example But i am not able to fetch it back because, when i am trying to fetch the uploaded file, its actually tyring to fetch from example.com I am new to Django, CPanel.. Changes/Suggestion please -
It is impossible to add a non-nullable field 'user_ptr' to student without specifying a default. This is because the database needs
It is impossible to add a non-nullable field 'user_ptr' to student without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. class User(models.Model): type_user = (('S', 'Student'), ('T', 'Teacher')) username = models.CharField(max_length=15, primary_key=True) password = models.CharField(max_length=10) firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=50, null=True) lastname = models.CharField(max_length=50) type = models.CharField(max_length=1, choices=type_user) class Student(User): #username = models.CharField(max_length=15, primary_key=True) course = models.CharField(max_length=15, null=False) year = models.IntegerField(default=1, null=False) department = models.CharField(max_length=50, null=False) -
Order data by latest uploaded in django FBV
I have a list view where i display the uploaded records right now they are sorted by name i need to change them to sort them by created date(which is in model). @login_required def records(request, template='records.html'): FBVPermission(IsUser).check(request) user = request.user.person.is_user data = {'user':user, 'records': user.records.all()} return render(request, template, data) -
In django whats the difference between mergemigrations and squashmigrations?
When shall we use mergemigrations --meerge/mergemigrations and when to use squashmigrations can we execute these commands via pipeline insteed of each developer in team doing it manually ? -
Cannot find webdriver executable in CircleCI
I'm new to CircleCI and have a django project repo that runs some selenium tests successfully locally, but when they try to run on CircleCI, they cannot find the webdriver, even though I've referenced it in the executable_path param as well as including in the repo. In the edge driver init fixture below, I reference the executable path: # conftest.py @pytest.fixture(scope="class") def edge_driver_init(request): options = webdriver.EdgeOptions() options.add_argument("--headless") edge_driver = webdriver.Edge( executable_path='webdrivers/msedgedriver.exe', options=options ) request.cls.driver = edge_driver yield edge_driver.close() The webdriver folder containing the exectuble is in the root directory of the Django project (same level as the conftest.py). Again, when run locally, it works just fine so I cannot figure out why CircleCI can't see it too. It says no such file or directory. Any suggestions would be greatly appreciated. -
How to implement Disable/Enable edit functionality on django admin change_form with simple action button?
I am trying to create a django change_form as by default are not editable, but editable only if user clicks custom action button. I mean by default; def has_change_permission(self, request, obj=None): return False Created custom action button to achieve this (with extending submit_line.html) {% extends "admin/submit_line.html" %} ... <input type="submit" value="Enable/Disable Edit" name="enableDisableEdit" /> Then I thought, i should do something with overriding response_change function. But couldn't def response_change(self, request, obj): if 'enableDisableEdit' in request.POST: ...Some code to enable disable edit Any idea? Thanks! -
No CustomerOrder matches the query
I am trying the generate PDF's for customers who successfully pays for an item but I keep getting this error. No CustomerOrder matches the query Below are my codes. views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(CustomerOrder, id=order_id) html = render_to_string('orders/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order_id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) return response urls.py urlpatterns = [ path('', views.order_payout, name='order_payout'), path('admin/order/<int:order_id>/pdf', views.admin_order_pdf, name='admin_order_pdf'), path('confirm/', views.confirm_order, name='confirm_order'), ] -
Django ORM: Count, Max, and retrieve field associated with max
In my situation there's a table with 3 fields A, B, and C. I want to group by A, and also store how many occurrences there are of each distinct A (Count). I also want to retrieve the max B for each A group and the C that is associated with the max B for each group. Only C has no duplicates. Does anyone know how to do write such a query using Django ORM? -
Django AssertionError: 404 != 200
I have a Class based view: class PromocionListView(ListView): model = Promocion and this url path: urlpatterns = [ path('promocion/list', PromocionListView.as_view(), name='promocion_list')] so i made the following test: class PromocionTests(TestCase): @classmethod def setUpTestData(cls): cls.promocion = Promocion.objects.create(fecha_de_inicio = date(2022,7,6),duracion = 90) def test_url_exists_at_correct_location(self): response = self.client.get('promocion/list') self.assertEqual(response.status_code, 200)` but it is showing the error: AssertionError: 404 != 200. Does anything knows why this is happening? I googled it a lot but I couldn't find an answer -
When I run a docker image it's stopped without giving any error?
There is my Dockerfile: Click here to see the image . This is the shell script: Click here to see the image . There is the output while image is running: Click here to see the image .As you see it's stopped there, after the model had train, but the container is kept starting. . I'm witing for output like this, to be able to use my api: Click here to see the image . Note: I don't know why nltk is dowloadning after the training, because in when i run the project from my host is the first thing, and the model can't train without ntlk. -
Override Settings for Tests of Django Rest Framework Throttling
I'm trying to test a custom user throttling: def get_user_rate(user): # Returns tupple (user plan quota, total seconds in current month) class SubscriptionDailyRateThrottle(UserRateThrottle): # Define a custom scope name to be referenced by DRF in settings.py scope = "subscription" def __init__(self): super().__init__() def custom_throttle_success(self): """ Inserts the current request's timestamp along with the key into the cache. """ self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) return True def allow_request(self, request, view): """ Override rest_framework.throttling.SimpleRateThrottle.allow_request Check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """ if request.user.is_authenticated: limit, duration = get_user_rate(request.user) # Override the default from settings.py self.duration = duration self.num_requests = limit self.key = self.get_cache_key(request, view) if self.key is None: return True self.history = self.cache.get(self.key, []) self.now = self.timer() # Drop any requests from the history which have now passed the throttle duration while self.history and self.history[-1] <= self.now - self.duration: self.history.pop() if len(self.history) >= self.num_requests: return self.throttle_failure() return self.custom_throttle_success() In settings.py I have added a default throttle rate of 10/second just for security (it is passed first on DEFAULT_THROTTLE_CLASSES): REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.UserRateThrottle', 'api.throttling.SubscriptionDailyRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'user': '10/second', … -
Wagtail: Dynamically load StreamField blocks in the admin EditView
I have a use case where we need dynamic blocks for a StreamField. Unfortunately this doesn't seem possible, since block types are specified in the model's StreamField field. I dug through the FieldPanel, StreamBlock and GroupPanel code and cannot clearly find a way to override the available blocks for the StreamField outside the model definition. This is my current admin EditView, where you can see what I'm trying to accomplish (see the NOTE/FIXME comments below: class EditProductView(EditView): def get_edit_handler(self): summary_panels = [ FieldPanel('title'), FieldPanel('description'), FieldPanel('body'), ] attributes_panel = [ # NOTE/FIXME: This is where we need the custom blocks to load, based # on `self.instance.product_type`. FieldPanel('attributes'), # StreamFieldPanel (which is deprecated) does not work because you can # only set the blocks within the model, when defining the StreamFieldPanel. # I would love to be able to do something like: StreamFieldPanel('attributes', block_types=[ ('test', blocks.CharBlock()), # Like this for example ]) ] settings_panels = [ FieldPanel('categories'), StateMachinePanel('state', sm_prop='sm', heading="State"), ] return TabbedInterface([ ObjectList(summary_panels, heading='Summary'), ObjectList(attributes_panel, heading='Attributes'), ObjectList(settings_panels, heading='Settings'), ]).bind_to_model(self.model_admin.model) Is it possible to override available StreamField blocks in this way, or are there potential issues with json_field DB integrity? -
ensure_csrf_token is not setting the csrf cookie in cookies tab
I have this simple generic view: class GetCSRFToken(views.APIView): permission_classes = [AllowAny, ] @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return Response('csrf is set') and then, in react, i have this code: useEffect(()=>{ axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{ console.log(res.data) }) },[]) so when react render the component that has the effect above, csrf token is not set in the application tab in cookie section why is that?? -
How to put an object model that has a link as an attribute in a table cell in django
I am doing a simple web page using django. So i have a table that has a list of articles, each article has name, id, summary and link. The idea is to make the article name as a link when you show it up in the table: <table class="table table-striped table-bordered table-hover table-condensed" style="font-family: Arial, Helvetica, sans-serif"> <thead> <tr> <th>Name</th> <th>Id</th> <th>Summary</th> </tr> </thead> <tbody> {% for article in articles %} <tr> <td>{{<a href=article.link>article.name</a>}}</td> <td>{{ article.Id}}</td> <td>{{ article.summary}}</td> <td><a href="{% url 'editArticle' article.id %}">Edit</a> <a href="{% url 'eraseArticle' article.id %}">Delete</a></td> </tr> {% endfor %} </tbody> </table> But then this error appears: Could not parse the remainder: 'article.name' from 'article.name' -
How to use Django ORM to find dangling records?
How would one use the Django ORM to write something similar to the following SQL: SELECT * FROM entities WHERE NOT EXISTS (SELECT 1 FROM apples WHERE apples.entity_id = entities.id) AND NOT EXISTS (SELECT 1 FROM oranges WHERE oranges.entity_id = entities.id) AND NOT EXISTS (SELECT 1 FROM bananas WHERE bananas.entity_id = entities.id) I have several meta tables that refer to an actual record with details but it's possible for those records to have no references, in which case they're "dangling". The problem is that there's over 100 million records so a simple exclude using an in filter doesn't work: Entity.objects.exclude(userid__in=Apple.objects.all().values_list('entity_id')) The SQL statement using NOT EXISTS, on the other hand, executes at lightning speed. I'm currently on Django 2.2 (with plans to upgrade to 4.x within a year). -
Fetch call of 'PUT' method in Django produces a 500 status error
When I try to make a fetch "PUT" request, but no matter what it returns 500 status (Internal Server Error) error. I've been trying to fix this error now for hours, but honestly have no idea what is the actual problem. Here is my code:Index.js (only a useful chunk of it) document.querySelectorAll(".bi").forEach(function (icon) { icon.addEventListener("click", (event) => like(event)); }); function like(event) { const target = event.target; const parent = target.parentElement.parentElement; const id = parent.className.slice(-1); const count = parent.querySelector("#like-count"); const number = parseInt(count.innerText); console.log(`${number+1}`); fetch(`/like`, { method: "PUT", headers: { "X-CSRFToken": getCookie("csrftoken"), "Content-Type": "application/json", }, body: JSON.stringify({ 'id': id, }), }) .then(response => console.log(response)) .then(data => { console.log(data); /* console.log(data.like); if (data.like) { target.id = "icon-svg"; count.innerText = `${number - 1}`; } else { target.id = "icon-svg-q"; count.innerText = `${number + 1}`; } */ }) .catch(error=>console.log(error)); } views.py (only a useful chunk of it) @login_required def like(request): if request.method == 'PUT': js = json.loads(request.body) id = int(js['id']) post=Post.objects.get(pk=id) _user =request.user liked=False for i in post.likes.all(): if i.user == request.user: liked=True if not liked: try: f = Like.objects.get(user=_user, post=post) return JsonResponse({ "result":False, "like":liked }, status=400) except Like.DoesNotExist: f = Like(user=_user, post=post) f.save() return JsonResponse({ "result":True, "like":liked }, status=200) else: try: f = … -
Dynamically create objects from queryset
I have a project running Django and folium. I have unknown list of categories and I need to add markers on a map according to its category. current_map = folium.Map(location=(0, 0), zoom_start=6) # a layer marker will be placed in layer_1 = folium.FeatureGroup(name="Category name 1").add_to(current_map) c = Category.object.all() markers = Marker.objects.all() for marker in markers: folium.Marker( location=(marker.latitude, marker.longitude), popup=folium.Popup(html=popup_html(marker), max_width=280, max_height=320), icon=folium.Icon( color=marker.category.color, icon=marker.category.icon.name, prefix="fa", ), tooltip=marker.category.name, ).add_to(layer_1) This code is OK for one or two categories, but if I have 100 categories then I need to do something like this: layer_1 = folium.FeatureGroup(name="Category name 1").add_to(current_map) layer_2 = folium.FeatureGroup(name="Category name 2").add_to(current_map) ... layer_99 = folium.FeatureGroup(name="Category name 99").add_to(current_map) for marker in markers: folium.Marker( # code omitted tooltip=marker.category.name, ).add_to( # if layer_n.layer_name == marker.category.name than add this marker to layer_n ) I tried this way, but it did not work as I need: def layer(name, to): return folium.FeatureGroup(name=name).add_to(to) for marker in markers: folium.Marker( # code omitted tooltip=marker.category.name, ).add_to(layer(marker.category.name, current_map)) How to make this correct? -
Django: tinymce: Export database data field with text and image to a word file using python-docx
I was using "tinymce" because it allows me to introduce text and image (because I need to write information and show an image), using python-docx library I can export it but when I see my word I don't see an image just the code of the image and HTML tags. My goal is export to a word file the same image and text that I introduced to the database field. Can you help me please? Views.py ''' from docx import Document from docx.shared import Inches, Pt, Mm from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.text import WD_BREAK mi_empresa = mis_empresas.objects.get(id=empresa_id) project = Proyecto.objects.get(id=proyecto_id) vulnerabilidades = Vulnerabilidad_PoC.objects.all().filter(id=proyecto_id) if mi_empresa.cod_empresa == "cod_mi_empresa": ################################################################################# # Document # ################################################################################# document = Document() section = document.sections[0] section.page_height = Mm(297) section.page_width = Mm(210) section.left_margin = Mm(25.4) section.right_margin = Mm(25.4) section.top_margin = Mm(25.4) section.bottom_margin = Mm(25.4) section.header_distance = Mm(12.7) section.footer_distance = Mm(12.7) # Get the user's fullname # Cabezera document_elements_heading = document.add_heading("Titulo con vinheta para que salga en el indice") document_elements_heading.alignment = WD_ALIGN_PARAGRAPH.CENTER # Add empty paragraph document.add_paragraph( "DataName1" + str(project.var1) + "\n" "DataName2 " + str(project.clientes_encargados) + "\n" ) for vuln in vulnerabilidades: document.add_heading(str(vuln.proyecto_id)) ################################################################################# # End of the document # ################################################################################# document_data = io.BytesIO() document.save(document_data) document_data.seek(0) response … -
How to include related model via queryset Django?
I have two models. Post and PostAction. When a user clicks the like button, PostAction will be created. But I have a problem. How can I include the PostAction model in the Post model? MODELS class Post(models.Model): description = models.CharField(max_length=2056) posted_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.FileField(upload_to=path_and_rename, blank=True) created_date = models.DateTimeField(default= datetime.now) class PostAction(models.Model): action_number = models.IntegerField(default=0) # default (0) is for like action. (1) is for saving post date = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="acted_user") post = models.ForeignKey(Post,on_delete=models.CASCADE, related_name="post_for") QUERY # order by descending posts and take take_count posts for initializing take_count = 10 posts = Post.objects.order_by("-created_date")[:take_count].annotate(total_likes=F('post_for')) #?? HTML <div class="card_center my-3"> <span class="card_description">{{post.description}}</span> <b>{{post.total_likes}}</b> </div> -
Concept of changing a user's email
I have a question about the very concept of changing a user's email. It's just a concept without code. When the user wants to change email, he goes to settings and click button "Send a link to change email". After that I am sending a message to user's email which contains link with a token to change email. Link looks like this: {{domain}}/new-email/{{uid}}/{{token}}. On this page user can put the new email and now here is my question: I need to send another message to the new mail with a link to check if that new mail is real. My user model contains just current email field. I need to remember somewhere the new mail so after user click the activation link inside message, the email field will be replaced by the new mail. Where should I store the new mail? Should I create a new field inside user model (replace email by current_email and add new_email) and after user click the activation link the current_email will be replaced by the new_email value and new_email will be set to null again? Or maybe should I store the new mail inside token (which will be inside the activation link URL) without … -
convert multiple files from base64 to pdf in memory
I am receiving several files in base64 format and I need to upload them to aws s3 in pdf format but so far I have tried everything and I still can't do it, is there any way to convert them to pdf without creating a file? i'm using django rest framwork "balance":"base64String", "stateOfCashflow":"base64String", "financialStatementAudit":"base64String", "managementReport":"base64String", "certificateOfStockOwnership":"base64String", "rentDeclaration":"base64String", -
Is there a Django setting, that can prevent javascript from calling external API
I manage a Django project collaborating with different front end programmers. Sometimes in my html template I have <script src="https://example.com/script.js"></script> Is there a way that I in my settings.py define whitelisting external domains that can be called. In this example, if example.com is not whitelisted, calling to that domain should be prevented. -
psycopg2.Operational€rror: connection to server at "127.0.0.1", port 5432 failed: Connection refused
Hello friends and mentors, am trying to deploy a project and these are the error I am facing when I run python manage.py migrate on digital ocean Note that am using windows, most of the commands as PostgreSQL is concerned don't run, I try to fix that with Cygwin but I still can't run them, I have git bash, obuntu WSL but there are commands I cant still, hey I am still rookie 🙈, I will so much appreciate any help for example when i run service postgresql start this in any of those terminal i get bash: service: command not found apps@cajetanglobal-66bd7dcc9b-2jjtd:~$ python manage.py migrate Traceback (most recent call last): File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/base/base.py”, line 219, in ensure_connection self.connect() File "/workspace/.heroku/python/1ib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/utils/asyncio.py”, line 33, in inner return func(*args, **kwargs) File “/workspace/.heroku/python/1ib/python3.10/site-packages/django/db/backends/postgresql/base.py”, line 18 7, in get_new_connection connection = Database.connect(**conn_params) File "/workspace/.heroku/python/1ib/python3.10/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync psycopg2.Operational€rror: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The above exception was the direct cause of the following exception: I … -
Is there a way in Django to mask link in navbar according to the loaded template?
I would like to do a simple thing in Django but cannot find the "Django" way to do it and I am sure that there is one. Let's imagine I have a simple navbar as follow: <ul> <li> <a href="{% url 'home-index' %}">Home</a> </li> <li> <a href="{% url 'blog-index' %}">Blog</a> </li> </ul> When I am at the 'blog-index' url, I want to hide this specific link in the navbar. Thanks for your help -
How to display an item from a dataframe in html by django?
I'm using Django and I'm using the following structure for the database: class Main(models.Model): date = models.DateTimeField(default=datetime.datetime.now()) timestamp = models.DateTimeField(auto_now_add=True) main_title = models.CharField(max_length=100) title = models.CharField(max_length=100) changeover_time = models.FloatField() cycle_time = models.FloatField() available_time = models.FloatField() FPY = models.FloatField() class Meta: ordering = [Lower('title')] def __str__(self): return self.title -- In my VIEWS I have the following code: def home(request): item = Main.objects.all().values() df = pd.DataFrame(data=item) df_gb = df.groupby(['title']).agg( {'cycle_time': 'mean'}) mydict = { "df": df_gb.to_html() } return render(request, 'teste.html', context=mydict) -- In my Html Template (teste.html) I have the following code: {% extends 'base.html' %} {% load static %} {% block 'body' %} <ul class="list-group"> <li class="list-group-item">C/O: <span class="badge bg-primary rounded-pill">{{df|safe}} </ul> {% endblock %} -- The results are : C/O: cycle_time title Product Conference 2.0 Product Descharging 7.0 Storing 1.0 Typing 3.5 buying 3.0 -- Displays all averages, using all data from my database, filtering by titles. it works ok But I need to display in the html a data relative to a title. For example, I want to display only the average relative to the title "Typing" I've already tried using for and I can't display this value isolated in my HTML . -- {% extends 'base.html' %} {% …