Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load ml model joblib dump file into celery task?
from transformers import pipeline import joblib cls = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h") joblib.dump(cls, "model/wav2vec2-base-960h-model-joblib") I used "facebook/wav2vec2-base-960h" to recognize/transcribe text from audio. en_wav2vec2_model = joblib.load(os.path.dirname(os.path.abspath(file))+"/model/wav2vec2-base-960h-model-joblib") using this way I load that model. Now, This model loads properly when it is in a synchronized process. But when I use this model in the celery task it is hang. there is no error showing that the task is created but can not complete. -
csrf_exempt not working in url Django Project
I keep receiving Forbidden (CSRF cookie not set.): /registration/ I have found many answers but non of them are matching with my project. Here is the Django Rest Framework urls with my attempt to exempt CSRF: path('dj-rest-auth/', csrf_exempt(include('dj_rest_auth.urls'))), path('dj-rest-auth/registration/', csrf_exempt(include('dj_rest_auth.registration.urls'))), I dont have anything in the views since the Registration and Login are already built in 'dj_rest_auth.registration.urls' The registration process is working fine from the web page but when I trying to create using flutter it is not allowing me. My question: How can I fix this problem without creating a login in or registration in the views page? -
Getting count of one column that has a distinct on two columns
Here is a simplified representation of my models: class Post(models.Model): user = models.ForeignKey(User) template_id = models.IntegerField(null=True) ... What I want to do is show the number of times a template has been used by users. So when I list out the templates, I want to be able to say Used by X users. The main draw is that I don't only want to count a user once (so if a user uses a template twice, they still count as "one use case"). All stackoverflow posts talk about doing something like this: counts = Post.objects.all().values("template_id").order_by().annotate(count=Count("template_id")) But that obviously double counts a user that uses the same template twice. I was able to do a distinct on template_id and user pairings like so: # Printing this out, I get 2 distinct entries in the QuerySet Post.objects.all().values("template_id", "user").distinct() However, when I try to get the counts of template_id (the code below), it seems to ignore the distinct and still double counts users. # Printing this out I get `count` = 3, which double counts a user. Post.objects.all().values("template_id", "user").distinct().values("template_id").annotate(count=Count("template_id")) Am I missing something here? -
multiple USERNAME_FIELD in djangorestframework?
How can i allow users to authenticate via multiple username field e.g(email | phone_number as USERNAME_FIELD)?? I have a custom User model---> in which I have a USERNAME_FIELD set to 'email'. settings.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', #THis is a default Backend which points to CustomUser's USERNAME_FIELD. 'account.backends.AuthenticateBackend', ##Custom Backend which tells to use phone number as USERNAME_FIELD. ] Here's the issue! It works fine if I use default obtain_auth_token view e.g.(allows me to login via multiple field)---> but whenever I write my own login logic it skips default model backend settings thus, it greets me with error. ValueError: Field 'phone_number' expected a number but got 'someEmail@gmail.com'. -
how to fix vscode terminal delay in win7
every command something it take so long time 30s to 1min waiting answering... -
Blocking IOError when using django + uwsgi
I am getting an error when there are too many requests coming to my application. Previously we did not notice so much issues, but recently we have seen that we get the error: BlockingIOError: [Errno 11] write could not complete without blocking print(ServDHCPRelay,"ServDHCPRelay") File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 41, in write self.__convertor.write(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 162, in write self.write_and_convert(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 190, in write_and_convert self.write_plain_text(text, cursor, len(text)) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 195, in write_plain_text self.wrapped.write(text[start:end]) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 41, in write self.__convertor.write(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 162, in write self.write_and_convert(text) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 190, in write_and_convert self.write_plain_text(text, cursor, len(text)) File "/apps/netadc3/.venvs3/netadc3.8/lib64/python3.8/site-packages/colorama/ansitowin32.py", line 196, in write_plain_text self.wrapped.flush() BlockingIOError: [Errno 11] write could not complete without blocking The error happens on print statements. We upgraded from python3.6 -> rh-python3.8 recently and we are using django 3.2! uWSGI version 2.0.20 -
Generate report date not included
I am trying to generate report in pdf in Django but the date of the report is not showing up. How can you include the date of report the fromdate and todate in the header of the PDF once the dates is saved in the model? Is there something I missed? Please see below the codes. Thanks View.py def GenerateInvoiceAccident(request): try: if request.method == 'POST': fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') report = GenerateReport(user=request.user, fromdate=fromdate, todate=todate, report="Accident Causation PDF") report.save() print(fromdate, todate) # incident_general_accident = IncidentGeneral.objects.filter(user_report__status = 2).values('accident_factor__category').annotate(Count('severity'), filter=Q(severity='Damage to Property')) incident_general_accident = IncidentGeneral.objects.filter(status = 2, date__range=[fromdate, todate ]) incident_general_accident1 = IncidentGeneral.objects.filter(status = 2,severity='Fatal', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_accident2 = IncidentGeneral.objects.filter(status = 2,severity='Damage to Property', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_accident3 = IncidentGeneral.objects.filter(status = 2,severity='Non-Fatal', date__range=[fromdate, todate ] ).annotate(Count('severity')) incident_general_classification = IncidentGeneral.objects.filter(status = 2, severity="Damage to Property", date__range=[fromdate, todate ]).distinct('accident_factor') incident_general_collision = IncidentGeneral.objects.filter(status = 2, severity="Damage to Property", date__range=[fromdate, todate ]).distinct('accident_factor') #you can filter using order_id as well report1 = GenerateReport.objects.all().order_by('-created_at')[:1] except: return HttpResponse("505 Not Found") data = { 'incident_general_accident': incident_general_accident, 'incident_general_classification': incident_general_classification, 'incident_general_collision': incident_general_collision, 'incident_general_accident1': incident_general_accident1, 'incident_general_accident2': incident_general_accident2, 'incident_general_accident3': incident_general_accident3, 'report1':report1 # 'amount': order_db.total_amount, } pdf = render_to_pdf('pages/generate_report_pdf_accident.html', data) #return HttpResponse(pdf, content_type='application/pdf') # force download if pdf: response = HttpResponse(pdf, … -
Local database works but on Heroku I get: operator does not exist: text % unknown
I've been dealing with this issue for days. I have a Postgres (version 13) database set up locally and on Heroku. Django and Python version are identical. When I make an api call to my local database, everything is fine - but when I make the call to the Heroku database I get the error below. The search input (eg 'party') is a string, "trademark_trademark" model is type models.TextField(null=True) I understand that the error is suggesting that I need ensure that the query input is of the right type. Can string not query a TextField. If so what type does it need to be. I'm an amateur and can't wrap my head around it - any idea what the problem might be? ProgrammingError at /trademarks/api/trademarks/ operator does not exist: text % unknown LINE 1: ...rademark" WHERE "trademark_trademark"."trademark" % 'party' ... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. Request Method: GET Request URL: https://CENSORED.herokuapp.com/trademarks/api/trademarks/?q=party&class_nos=0&no_related=true Django Version: 4.0.5 Exception Type: ProgrammingError Exception Value: operator does not exist: text % unknown LINE 1: ...rademark" WHERE "trademark_trademark"."trademark" % 'party' ... ^ HINT: No operator matches the given name and argument types. You … -
Django: referencing a namespace in a template during a unit test gives "not a registered namespace" error
I am just learning how to unit test so I'm sure I'm not understanding some core principal. I have custom 400 and 500 error handlers that return a template indicating the error to the user. Now, in practice, when I run my site, these work perfectly! Errors get caught and the templates get generated exactly as anticipated. The difficulty comes when I try to write unit tests for the 500 error. What occurs: any references to a namespace (in this case, 'base') throws an error. Traceback (most recent call last): File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/--------/Documents/projects/--------/base/testing/test_views.py", line 50, in test_handler_renders_template_response response = self.client.get('/500/') File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 836, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 424, in get return self.generic( File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 541, in generic return self.request(**r) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 805, in request response = self.handler(environ) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/test/client.py", line 153, in __call__ response = self.get_response(request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/sentry_sdk/integrations/django/__init__.py", line 409, in sentry_patched_get_response rv = old_get_response(self, request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response response = self._middleware_chain(request) File "/home/--------/Documents/projects/--------/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner response = response_for_exception(request, exc) … -
How to multiply to columns in different table and get another coloum as output in django orm
I have three tables First one is product table consist of product details and price Second one is customer table with customer details And a cart table with customer_id and product _id as foreign key and qty field for quantity of product I want join cart table and product table and get an additional field called total price that is the result of price in product *qty in cart How to do this in django orm I tried f function but it didn't work -
Infinite POST request on uploading file with Django
I try to upload some files to a server through a web interface with Django. HTML : <form method="post" enctype="multipart/form-data" name="upload_file"> {% csrf_token %} <input type="file" name="uploaded_file_list" multiple> <button class="rounded-full bg-violet-200 text-violet-700 block p-2" name="upload_file" value="dummy" type="submit">Ajouter des fichiers</button> </form> views.py def media_manager(request): file_manager = MediaManager.server.FileManager(django.conf.settings.USER_FILE_ROOT) # POST utilisé pour associer les tags aux images if request.method == "POST": print(request.POST) if request.POST.get("upload_file"): for uploaded_file in request.FILES.getlist("uploaded_file_list"): file_manager.add_file(uploaded_file) context_dict = {} context_dict["filtered_file_list"] = MediaManager.filters.ImageFilter(request.GET, queryset=MediaManager.models.UserImage.objects.all()) return django.shortcuts.render(request, "MediaManager/media_manager.html", context=context_dict) FileManager.py def add_file(self, uploaded_file): file_system_storage = django.core.files.storage.FileSystemStorage(location=self._user_dir_absolute_path) file_system_storage.save(uploaded_file.name, uploaded_file) FileManager also updates context_dict["filtered_dile_list"] with the files uploaded. When I upload a file on the browser, the file is correctly uploaded and the web display also correctly add it on the page. I can see the upload POST request. But this operation is repeated infinitely. Here is the log (with a request.POST print) : <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:23] "POST /media_manager/ HTTP/1.1" 200 19214 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 185 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:24] "POST /media_manager/ HTTP/1.1" 200 19580 [02/Nov/2022 22:03:24] "GET /static/MediaManager/user/Couleurs-logo-Overwatch.jpg HTTP/1.1" 200 63919 1 static file copied to '/home/gautitho/workspace/MonPetitNuage/MonPetitNuage/static', 186 unmodified. <QueryDict: {'csrfmiddlewaretoken': ['vCHAoeGg3QVIZDuHAls8lmV7Y8MXHqxGeWQj16N2zJcCUfoML4pVcnsmJGk7R5Er'], 'upload_file': ['dummy']}> [02/Nov/2022 22:03:25] "POST /media_manager/ HTTP/1.1" 200 19959 … -
How do I get and pass context from one form to another based on primary/foreign key fields?
I am currently building a website that will allow the sale of mixing and mastering services. As it is a small set of services, I don't need a shopping cart or any elaborate form of ordering. Instead, I would like a customer details page (which informs my 'Customer' model), an order page where the customer selects what exactly they will be purchasing and uploads any relelvent files (which also informs my 'Order' model), and finally sends the customer to a stripe checkout page. Currently, the Custome rdetails form is up and running and saving the data to the appropriate database model. Once they click continue, I am struggling to understand how to store the primary key of the Customer instance the user created upon filling out the form, and saving this data in the next form through the foreign key relationship. Similarly, before being sent to Stripe checkout, I would like to create an 'Order Review' page, reviewing the details of their order. I'm not sure how to pull the primary key of the Order intance that was just created in order to for a Model view on the subsequent page. I believe what I;m missing in order to achieve … -
How do I render a PDF in Django using FileResponse
I have a simple function to Open a PDF file, I want to render it within my Django as part of a POST function. def view_pdf(request, pdfpath): filename = pdfpath.replace('\\', '/') name = filename.split('/')[-1] if os.path.exists(filename): response = FileResponse(open(filename, 'rb'), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename={name}' # user will be prompted display the PDF in the browser # response['Content-Disposition'] = f'filename={name}' # user will be prompted display the PDF in the browser return response else: return HttpResponseNotFound('Cannot find the PDF') My view calls this with return view_pdf(request, pdfpath) How do I actually get this to open as a new Tab ? The HTML has a submit button that calls some ajax functions <button type="submit" onclick="window.submitPAGE()" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> So I cant turn it into a FORM because I cant pass the data form the function <form method="POST" target="_blank"> <button type="submit" class="btn waves-effect waves-light btn-primary"><i class="fa fa-print"></i></button> -
Update data in table which has foreign keys in Django
I have two tables where one is connected to the other with a foreign key. The model store_table already consists of three rows, for three different stores. I am now trying to update the model price_table but I am not quite sure that I understand how to utilize the foreign keys, so that it knows which price_table item to be connect to which store_table id. Any suggestions out there on how to achieve this? My two models class store_table(models.Model): store = models.CharField(max_length=100, null=True) number = models.BigIntegerField(null=True) class Meta: unique_together = ( ( "store", "number", ), ) class price_table(models.Model): price = models.CharField(max_length=100, null=True) dates = models.DateField(null=True, blank=True) store_id = models.ForeignKey( store_table, on_delete=models.CASCADE, default=None ) class Meta: unique_together = ( ( "dates", "price", ), ) My code update_models = price_table( dates=dates, price=price ) update_models.save() -
How i can get JSON list without attributes ("count": 3, "next": null, "previous": null, "results":)
I have JSON like this: {"count":3,"next":null,"previous":null,"results":[{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}]} And I want to get JSON like this [{"name":"Max","slug":"DrMax","directions":["Surgery","Stomach"],"description":"Surgery","work_experience":"2","birt_date":"2018-12-04"},{"name":"Ban","slug":"0","directions":["X-Ray"],"description":"Xray","work_experience":"6","birt_date":"2022-11-02"},{"name":"qwe","slug":"qwe","directions":["Surgery","X-Ray","Stomach"],"description":"Xray","work_experience":"6","birt_date":"2022-11-14"}] -
View is returning an HttpResponse, but says it returns None
I have a button in one of my views that triggers a function "compileUpdate" and then returns a file as a response. This was working previously but now I receive the error: "ValueError: The view didn't return an HttpResponse object. It returned None instead." The block of code below essentially: Gets the correct campaign Formats the path of the files to compile Checks if a specific directory exists, and if not creates it Calls the compileUpdate function Returns the file as a http response Non-working file creation and response if req == "Bulk Update": cmp_id = request.headers.get('cmp') campaign = Campaign.objects.get(id=cmp_id) parent_dir = os.path.normpath(os.getcwd() + os.sep + os.pardir) submittedFolder = os.path.join(parent_dir, "SubmittedReviews", "", str(cmp_id) + "-" + campaign.system.name, "") cmp_files = glob.glob(os.path.join(submittedFolder,'*')) archive = os.path.join(parent_dir, "Archive", "", str(campaign.id) + "-" + campaign.system.name, "") if os.path.exists(archive) == False: os.mkdir(archive) bulk_update = os.path.join(archive, str(campaign.id) + "-" + campaign.system.name + "_bulk_update.csv") print(bulk_update) with open(bulk_update, 'w') as bulk_out: writer = csv.writer(bulk_out) compileUpdate(cmp_files, campaign, writer) bulk_out.close() time.sleep(2) file = str(bulk_update).split("/")[-1] with open(bulk_update, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Type'] = 'application/vnd.ms-excel' response['Content-Disposition'] = 'inline; filename="{}"'.format(os.path.basename(bulk_update)) response['X-Accel-Redirect'] = f'/archive/{file}' return response As mentioned above, this errors out saying that I am returning None rather than an http … -
How to submit an update form and create form at the same time in Django?
I am trying to update a model "Stock", then create a new "StockTransaction" at the same time. I want to accomplish this using two different forms submitted together. I am able to get the stock update transaction to work, but when I try to is_valid() on the transaction form, it always returns false. I can't figure out why it is returning false. here are all of the relevant code sections that are used. Any help is appreciated. Thank you in advance! def buyStock(request, pk): stock = Stock.objects.get(id=pk) form = StockForm(instance=stock) tform = StockTransForm() if request.method == 'POST': form = StockForm(request.POST, instance=stock) form.instance.buyPrice = stock.ticker.price form.instance.dateOfPurchase = date.today() form.instance.forSale = False tform.instance.stockID = stock.stockID tform.instance.buyPrice = stock.buyPrice tform.instance.sellPrice = stock.ticker.price tform.instance.broker = form.instance.broker tform.instance.buyer = form.instance.ownerID tform.instance.seller = stock.ownerID tform.instance.ticker = stock.ticker if form.is_valid() and tform.is_valid(): form.save() tform.save() class StockTransaction(models.Model): transactionID = models.AutoField(primary_key=True) ticker = models.ForeignKey(PublicCompany, on_delete=models.CASCADE, default=None, related_name='stocktrans-ticker+') stockID = models.IntegerField() buyer = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-buyer+') seller = models.ForeignKey(FinancialAccount, on_delete=models.PROTECT, default=None, related_name='stocktrans-seller+') sellPrice = models.DecimalField(max_digits=7, decimal_places=2) buyPrice = models.DecimalField(max_digits=7, decimal_places=2) date = models.DateField(auto_now_add=True) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, related_name='stocktrans-broker+') class Stock(models.Model): ownerID = models.ForeignKey(FinancialAccount, on_delete=models.CASCADE, default=None, related_name='stock-owner+')#on delete maybe change buyPrice = models.DecimalField(max_digits=7, decimal_places=2) broker = models.ForeignKey(Agent, on_delete=models.PROTECT, default=None, … -
Django Model: how to find list of auto-generated fields
Is there any Django built-in function that return a list of all auto-generated fields from a Django model? Something like: MyModel._meta._get_auto_generated_fields() -
Django - How can I make a list of the choices I've selected in manytomany?
I'm trying to make a list of the choices I've selected. In this case, the logged in Gestor will select the Funcionarios, and will be able to view the list of selected employees. **models.py ** class Equipe(models.Model): gestor = models.ForeignKey(Gestor, on_delete=models.PROTECT, default="") funcionario = models.ManyToManyField(User) def __str__(self): return self.nome def get_funcionario(self): return "\n".join([p.funcionario for p in self.funcionario.all()]) views.py def listaFuncionario(request): gest = Gestor.objects.get(user_id = request.user.id) equipe = Equipe.objects.filter(gestor_id = gest) equipes = gest.equipe_set.all() func = equipes.funcionario.all() context = {'func':func} return render(request, 'listaFunc.html', context) I try, but it doesn't seem to access the selected Funcionarios table I try but shows me func = equipes.funcionario.all() AttributeError: 'QuerySet' object has no attribute 'funcionario' [02/Nov/2022 15:15:06] "GET /funcionarios HTTP/1.1" 500 65882 n -
How to take elevate or run function as administrator in Django
I have a django project and I want to do operation on hosts file in windows but I am not able to do that because it is read only file so how can I do that any suggestion. So, I am expecting any solution so that I can able to make changes in the host file. I am thinking to make my django project able to run as administrator. -
Django navbar css doesn't make any changes
It's probably not about static files configuration because images work and CSS other than navbar's work, navbar's CSS doesn't make any changes it's just like it's not there, even though when I tried to make a simple h1 and color it (as a test) it worked, it's just the navbar's CSS for some reason that I really can't figure out. base.html: {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock navbar %} {% block content %} {% endblock content %} </body> </html> homepage.html: {% extends 'base.html' %} {% load static %} {% block content %} {% endblock content %} navbar.html: <head> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}" /> </head> <div class="navContainer"> <div class="navbar"> <img src="{% static 'images/navLogo.png' %}" class="logo" /> <nav> <ul> <li><a href="">Home</a></li> <li><a href="">About</a></li> <li><a href="">Projects</a></li> </ul> </nav> </div> </div> static configuration in settings.py: STATIC_ROOT = path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ path.join(BASE_DIR, 'staticfiles') ] app's urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ … -
suddenly datetime indexing field selection became longer
I have partition table with datetime field indexing In django orm i have 2 variant of requests First variant MyModel.objects.filter(my_datetime_field__gt=date(2022, 1 , 1)) This request is being made 3.5-5 seconds Second variant MyModel.objects.filter(my_datetime_field__date__gt=date(2022, 1 , 1)) This request is being made 0.05 seconds Question Previously, requests were completed in the same time. What could have happened? Some information django: 2.0 postgres: 12.3 index_type: btree I try next VACUUM (VERBOSE, ANALYZE) my_table REINDEX INDEX my_index -
How to find history of commands run on mysql
I sort of have a heart attack of a problem. I had a non-root utility user in mysql that used to be able to see all the databases, tables, etc. on the mysql instance. The user was able to insert records, delete records, create tables, etc. too. This user is used by scripts to edit records, or view the data as someone who's not root via phpmyadmin. I don't know how Django fits into this or if it was even the cause but a contractor needed access to the db to work on their project we asked them to work on. They said they were using Django and needed to create some auth tables in the database (auth_group, auth_user, auth_user_groups, etc.) However, after they added their tables for Django, that user can't see anything except the "information_schema" database. Luckily, I checked using the root user in mysql and can see the databases but somehow, the viewing privileges are removed from the non-root user. I want to see what commands the contractor ran to get us into this situation to tell them not to do this again. I was going to check the .mysql_history file in the unix root user directory … -
I get a 404 error when passing as a parameter to the path an int that is a foreign key
This is the url i am trying: http://localhost:8000/blog/categoria/1/ The foreign key is categoria_id that comes from relationship many to many of Post and Categoria. I am using Sqlite3. This file is the models.py from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): nombre=models.CharField(max_length=50) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='categoria' verbose_name_plural='categorias' def __str__(self): return self.nombre class Post(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='blog', null=True, blank=True) autor=models.ForeignKey(User, on_delete=models.CASCADE) categorias=models.ManyToManyField(Categoria) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='post' verbose_name_plural='posts' def __str__(self): return self.titulo This file is the views.py: from django.shortcuts import render from blog.models import Post, Categoria def blog(request): posts=Post.objects.all() return render(request, "blog/blog.html",{"posts":posts}) def categoria(request, categoria_id): categoria=Categoria.objects.get(id=categoria_id) posts=Post.objects.filter(categorias=categoria) return render(request, "blog/categoria.html",{'categoria': categoria, "posts":posts }) This file is the urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.blog, name='Blog'), path('categoria/<int:categoria_id>/', views.categoria, name="categoria") ] -
model inheritance authentication on several children
I would like to have opinions on how to proceed to set up my models. I have a father entity which has two sons simpleman and superman. Both can authenticate but simpleman does not have access to all pages and other limitations. To highlight simpleman I had thought of adding a method that returns true I would like to know do I have to create a Father model with its attributes and its primary key (regNumber: CharField) then with this children I would put this primary key in foreign key ? In the code i think to do this: class Superman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSuper() # where user.is_admin=True and user.is_superuser=True class Simpleman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSimple() # where user.is_admin=False and user.is_superuser=False def heIsSimple(self): return True How will authentication work? How could I get him to look in the right table? To limit access to certain page for the simpleman I had thought of setting up a decoration like this in my views.py @user_passes_test(lambda user: u.heIsSimple())