Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disallow to change "status" for simple user and keep it for admin and support(superuser)?
The simple user must either not see the status button or it must be grayed out for selection. Admin(user.is_staff) and Support(user.is_superuser) should see the field and be able to change it. Now user can change the status of ticket in Update view. My serializer: class TicketSerializerUpdate(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) status = Status.objects.all() class Meta: model = Ticket fields = "__all__" My models Ticket and Status: class Status(models.Model): status = models.CharField(max_length=150) desc_status = models.TextField() def __str__(self): return self.status class Ticket(models.Model): title = models.CharField(max_length=150) text = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.title File permissions now haven't anything for solve the problem and I haven't any idea. I think it is simple problem, if you need more info you can request me) -
Django tabularInline 'categories.Category_children_ids' has more than one ForeignKey to 'categories.Category'. You must specify a 'fk_name' attribute
I'm want to create nested categories, model work fine. class Category(models.Model): category_name = models.CharField(max_length=100) children_ids = models.ManyToManyField( "Category", blank=True, related_name="categories" ) ...etc but, when i add inline for admin panel class ChildrensInline(admin.TabularInline): model = Category.children_ids.through compiler shows me error: 'categories.Category_children_ids' has more than one ForeignKey to 'categories.Category'. You must specify a 'fk_name' attribute. I also try fk_name='categories', and columns name inside Category_children_ids table, but it not work -
Use of Routers in ReactJS and Django Sends Empty Page [closed]
Routes in ReactJS and Django Integration keeps sending me empty page. Wwhat could be wrong? -
in python wants to take certain part from a given string [duplicate]
I have a string type URL --https://drive.google.com/file/d/1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82/view?usp=sharing I want only part after "d/" and before "/view" from the above string so how can I use it using regex or any other function example I only want 1vBiwyAL3OZ9VVCWCn5t6BagvLQoMjk82 from the above string using python -
In Django, why i cannot import a model in an python file created by me in inside the same app?
I created in Django, in my app an python file for forms and I want to import a model from .models (from the same app). The problem is when I import the model, it returned an error. The model is(models.py): class Article(models.Model): title = models.CharField(max_length=100) location=models.CharField(max_length=120,null=True,blank=True) category=models.CharField(max_length=100,null=True,blank=False) slug=models.SlugField(null=True, blank=True, unique=True) boddy=models.TextField() timestamp = datetime.now() update = models.TimeField(auto_now=True) The problem is in util.py (the python file that i created) : from .models import Article The error is: ImportError: cannot import name 'Article' from partially initialized module 'hello.models' (most likely due to a circular import) (D:\Python\Django\Projects\myproject\hello\models.py) The python files are in the same app -
Python Postgres JSON
Currently as written I insert the payload as JSON into a single column. I want to break the k/v into columns in the predefined table. The value from MQTT is always byte object. ie... b'{"name":"John","age":30,"city":"New York"}' def insertIntoDatabase(message): """Inserts the mqtt data into the database""" with connection.cursor() as cursor: print("Inserting data...) # MQTT message always a byte object # message.payload contains message sent in this format b'{"name":"John","age":30,"city":"New York"}' # Covert to string ***WORKS*** test_json = message.payload.decode('utf8') # Convert string to dict ***WORKS*** json_dict = json.loads(test_json) print(json_dict) # How do I deconstruct the dict into an sql insert???? # Inserts JSON into single column. Need one column per key cursor.callproc('InsertIntoMQTTTable', [str(message.topic), str(message.payload)[2:][:-1], int(message.qos)]) connection.commit() SQL Routine - Called via callproc create function insertintomqtttable(topic text, message text, qos numeric) returns void language plpgsql as $$ BEGIN INSERT INTO mqtt (createdAt, topic, message, qos) VALUES (CURRENT_TIMESTAMP, topic, message, qos); END; $$; alter function insertintomqtttable(text, text, numeric) owner to don; postgres Table Structure - CREATE TABLE mqtt ( id SERIAL PRIMARY KEY, createdAt TIMESTAMP NOT NULL, topic TEXT NOT NULL, message TEXT, qos NUMERIC(1) NOT NULL ); -
updating an object related to two others by a foreignKey and OneToOneKey respectively does not work in django
Here is the model of object I want to update: class Abonnement(models.Model): client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name="abonnements") compteur = models.OneToOneField(Compteur, on_delete=models.CASCADE,related_name="abonnement") adresse = models.CharField(max_length=200, blank=True, null=True) point_service = models.CharField(max_length=200, null=True, blank=True) lat_machine = models.FloatField(default=0.0) lon_machine = models.FloatField(default=0.0) The Client model is linked to this model by a Foreign key and the Compteur model by a OneToOne key Retrieving the object from the OneToOne field does not pose a problem. But when I try to update, it does not work. This is what I do in the controller: compteur = get_object_or_404(Compteur,pk=request.POST["deveui"]) a = compteur.abonnement a.point_service = form.cleaned_data["pointservice"] a.lat_machine = form.cleaned_data["latitude"] a.lon_machine = form.cleaned_data["latitude"] a.save() I also try to do it another way, but nothing changes, the edit still doesn't work compteur = get_object_or_404(Machine,pk=request.POST["deveui"]) a = Abonnement.objects.get(compteur=compteur) a.point_service = form.cleaned_data["pointservice"] a.lat_machine = form.cleaned_data["latitude"] a.lon_machine = form.cleaned_data["latitude"] a.save() -
How can I solve this error "Reverse for 'resume-detail' with no arguments not found. 1 pattern(s) tried: ['userapp/view/(?P<slug>[^/]+)/\\Z']"?
I'm trying to delete from my database but I'm getting the error "Reverse for 'resume-detail' with no arguments not found. 1 pattern(s) tried: ['userapp/view/(?P[^/]+)/\Z']". How do I resolve this error ? views.py def delete_view_experience(request, experience_id): experience_instance=get_object_or_404(Experience, id=experience_id) if experience_instance: experience_instance.delete() messages.success(request,"Information Deleted Successfully") return redirect('resume-detail') urls.py path('userapp/view/<str:slug>/', user_views.resume_detail, name='resume-detail'), path('delete-experience/<int:experience_id>/', user_views.delete_view_experience, name='delete_experience'), models.py class Experience(models.Model): company = models.CharField(null = True, max_length=200) position = models.CharField(null = True, max_length=200) start_date = models.DateField() end_date = models.DateField() experience = models.TextField() skills = models.TextField() resume = models.ForeignKey(Resume, on_delete = models.CASCADE, null = True) def __str__(self): return '{} at {}'.format(self.position, self.company) error traceback Traceback (most recent call last): File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhumuza-Ivan\Desktop\JobPortal\userapp\views.py", line 219, in delete_view_education return redirect('resume-detail') File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 48, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 145, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'resume-detail' with no arguments not found. 1 pattern(s) tried: ['userapp/view/(?P<slug>[^/]+)/\\Z' -
How to create a django microservices monorepo?
Given this blog project which has posts and comments apps: blog ├── blog │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── comments │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── posts ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py I want to be able to run each of the apps (services) independently. The django-admin runserver runs the whole app which is not what my intention. I want to run and deploy services independently, each with its own db and port, and choose which services to start in advance. I'm aware that each app can have its own db specified in settings.py. Not sure about how to run services independently though. I also want the resulting project structure to be PyCharm-friendly, which means I can choose which services to run within the same project workspace. -
Got errors in Django app coverted to desktop app
I am working on a project. I have got a django web app "converted" into desktop app. So now I try to run that app, it gives me error . So can somone help me to resolve these errors.i have attached the screenshot also to understand the situation. -
Pagination in Django Admin with Custom List Filters
I have a proxy model and admin section where I am implementing a custom multi select filter. The results are coming correctly. How ever, pagination is not working with this filter. http://127.0.0.1:8000/users/?taggroup=1&taggroup=2 When I try to click on page 2 the url turns to : http://127.0.0.1:8000/users/?page=2&taggroup=2 But the expected result is : http://127.0.0.1:8000/users/?page=2&taggroup=1&taggroup=2 I tried overriding the change list using [https://stackoverflow.com/questions/62960518/overriding-django-admin-pagination-along-with-url-parameters][1] But now the pagination is like below when I try navigating from page 1 to page 2 and also the pagination is starting from 0 and not 1: http://127.0.0.1:8000/users/?page=2&page=1 Below is the code that I have tried: @register.inclusion_tag('admin/custom_pagination.html', takes_context=True) def custom_pagination(context, cl): pagination = admin_list.pagination(cl) if 'group_id' in context: pagination['params'] = (('taggroup', context['group_id']),) return pagination change_list_template = 'admin/users_changelist.html' def changelist_view(self, request, extra_context=""): response = super(PartnerUsersAdmin, self).changelist_view( request, extra_context) group_id = request.GET.urlencode() if group_id: extra_context = { 'group_id': str(group_id), } response.context_data.update(extra_context) return TemplateResponse(request, "admin/partner_users_changelist.html", response.context_data) #custom_pagination.html {% load admin_list %} {% load i18n %} {% load content_extras %} <p class="paginator"> {% if pagination_required %} {% for i in page_range %} <a href="?p={{ i }}{% for key, value in params %}{% if key != 'p' %}&{{ value }}{% endif %}{% endfor %}"> {{i}}</a> {% endfor %} {% endif %} {{ cl.result_count … -
How to get user object from Django DRF when logged in with TemplateView?
I am begginer in Djnago and logged in to my app with this code: class LoginHandler(TemplateView): def get(self, request, *args, **kwargs): user = authenticate(request, email='jaxen@gmail.com', password='123456') login(request, user) return render(request, "login.html", context={}) But i need to detect logged in user in other app that use DRF. I don't know how fetch the user. I tried this code but not worked: class OtherAppHandler(APIView): def post(self, request): print(f"user: {request.user}") ... Thank you. -
How can I get the rows from the PostgreSQL with specific value. Django
How can I get the rows from the PostgreSQL with specific value? I have this table with columns: id | accountid | dictdata | date | Inside the dictdata column contains a bunch of dictionary data. in my models.py class charts(models.Model): id = models.AutoField(primary_key=True) accoundid= models.IntegerField(default=None,blank=True) dictdata= models.JSONField(default=None,null=True, blank=True) date = models.DateTimeField(auto_now=True) class Meta: db_table = "charts" in my python file data = list(charts.objects.values('dictdata ')) //all dictionary data print(data) Example of print(data): [{'dictdata': {'select': 'bar', 'title': 'some title'}}, {'dictdata': {'select': 'line', 'title': 'some title'}}, {'dictdata': {'select': 'pie', 'title': 'some title'}}] how can I get the rows that contains a specific 'select' value? for example I want to get all the rows with 'bar' {'dictdata': {'select': 'bar', 'title': 'some title'}} -
Why do I get this error "HttpRequest.accepts() missing 1 required positional argument: 'media_type'"?
The source code originally had Httpsrequest.is_ajax which after some reading I realised was depricated. So I changed it to Httpsrequest.accepts and it now throws an error: HttpRequest.accepts() missing 1 required positional argument: 'media_type' How can I solve or bypass this error ? def home_view(request): published_jobs = Job.objects.filter(is_published=True).order_by('-timestamp') jobs = published_jobs.filter(is_closed=False) total_candidates = User.objects.filter(role='employee').count() total_companies = User.objects.filter(role='employer').count() paginator = Paginator(jobs, 3) page_number = request.GET.get('page', None) page_obj = paginator.get_page(page_number) if request.accepts(): job_lists = [] job_objects_list = page_obj.object_list.values() for job_list in job_objects_list: job_lists.append(job_list) return render(request, 'jobapp/index.html', context) -
I am trying to install pillow module on my python django web.. but is not installing in cpnael linux server
Collecting Pillow==2 Downloading Pillow-2.0.0.zip (1.4 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 8.4 MB/s eta 0:00:00 Preparing metadata (setup.py) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (setup.py) ... error error: subprocess-exited-with-error -
Using Django Tenants with Channels - AppRegistryNotReady
We are trying to use django channels to implement websockets in a multi-tenant django application. I have followed the tutorial page in the django channels documentation and also applied the instructions found in the deploying page. However, I am seeing the django.core.exceptions.AppRegistryNotReady error when running pytest cases or even when running a simple "python manage.py check". django@fa5404e77654:/usr/src/app$ python manage.py check Traceback (most recent call last): File "manage.py", line 36, in <module> main() File "manage.py", line 32, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/lib/python3.8/site-packages/channels/apps.py", line 4, in <module> import daphne.server File "/usr/local/lib/python3.8/site-packages/daphne/server.py", line 7, in <module> twisted_loop = asyncio.new_event_loop() File "/usr/local/lib/python3.8/asyncio/events.py", line 758, in new_event_loop return get_event_loop_policy().new_event_loop() File "/usr/local/lib/python3.8/asyncio/events.py", line 656, in … -
How to make text fit in div?
I'm styling a link to make it look like the photo. The problem is in the second div, text over div. In the scope of the question is an example of the photo of how it is and how it should be. (I left the text color in black to illustrate the problem) How it should be var div_color = document.getElementsByClassName('div-categoria'); console.log div_color[0].style.backgroundColor = '#7d35ed'; div_color[1].style.backgroundColor = '#e93f3f'; div_color[2].style.backgroundColor = '#e4bf2a'; .categoria{ margin: 2.5rem 0; } .div-categoria{ display: inline-flex; height: 120px; width: 120px; border-radius: 10px; transition: transform .2s; margin-right: 20px; position: relative } .div-categoria:hover{ transform: scale(1.10); } .categoria a{ text-decoration: none; color: white; } .div-categoria p { margin: 0; color: black; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%); text-transform: uppercase; font-size: 25px; } <div class="categoria"> <a href="#link"><div class="div-categoria"><p>Comida</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas Alcoolicas</p></div></a> <a href="#link"><div class="div-categoria"><p>Bebidas</p></div></a> </div> -
Django HttpResponseRedirect() function
flag = 0 folder_id = 0 if FolderEntries.objects.filter(entry = entry_id).exists(): print("=======================yes in folder") flag = 1 folder_object = FolderEntries.objects.get(entry = entry_id) folder_entries_object = model_to_dict(folder_object) print("-------------------------", folder_entries_object) folder_id = folder_entries_object['folder'] else: flag = 0 if flag == 1: returnHttpResponseRedirect('folder/'+str(folder_id)+'/') else: if request.session.get('HTTP_REFERER', None): HTTP_REFERER = request.session.get('HTTP_REFERER') del request.session['HTTP_REFERER'] return HttpResponseRedirect(HTTP_REFERER) return HttpResponseRedirect('editentry/'+str(entry_id)) In this case if flag = 1, this is redirecting me to 2 urls these are:- http://127.0.0.1:8000/admin/form-entries/edit-entry/folder/174/ url "folder/174" is url that i need. But i am getting unwanted url "admin/form-entries/edit-entry/" What i am doing wrong please guide me. I am a entry level django developer Thanks and Regards Abhishek -
Assign custom role to user
I am a beginner in django and trying to create a web application for my task. I am trying to assign a roles to every to user. But i have an error. enter image description here My model class Rol(Group): state = models.BooleanField(default=True) description = models.CharField(max_length=200) permission = models.ManyToManyField(Permission) def __str__ (self): return '{}'.format(self.state,self.description, self.permission) In this part i don't have any problem the permission is asigned to rol But here My model: class User(AbstractUser): state = models.BooleanField(default=True) roles = models.ManyToManyField(Rol) def __str__ (self): return '{}'.format(self.username,self.state,self.roles) My form: class UserForm(UserCreationForm): username = forms.CharField(label="User",widget=forms.TextInput(attrs= {"class":"form-control"})) password1 = forms.PasswordInput() password2 = forms.PasswordInput() state = forms.CheckboxInput() roles =forms.ModelMultipleChoiceField(label="Roles",queryset=Group.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = User fields = [ "username", "password1", "password2", "activo", "roles" ] In roles lists the roles created but not assigned to the user at the time of saving, it shows me an error: Field 'id' expected a number but got <Group: standart>. The above exception (int() argument must be a string, a bytes-like object or a real number, not 'Group') was the direct cause of the following exception: And highlight this line form.save_m2m() My view def create_user(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form2=form.save(commit=False) form2.save() form.save_m2m() return redirect('list_user') … -
unwanted duplicate objects in Javascript recursion
I'm trying to create a non-profit social media site using Django. Part of the site is nestable comments. However, when I create a comment it gets duplicated by the factor of its depth. so at a depth of one one comment is rendered, at a depth of two two comments are rendered, and at three three. I'm rendering the comments with javascript: function showComments(comment, parent_id, user_id) { // ... (the code of how to render the comment) ... for (subment of comment.subments) { showComments(subment, comment.comment.id, user_id) } } fetch(`/get_comments/${post}`) .then(response => response.json()) .then(data => { results = data.data console.log(results) for (comment of results[0]) { showComments(comment, 0, results[1]) } }) The fetched data doesn't contain any duplicates. How do I recursively render the data without duplicating it? Thank you -
403 net::ERR_ABORTED 403 (Forbidden) error in static files
Please I have been stocked for days now trying to clear the error in my browser console (403 net::ERR_ABORTED 403 (Forbidden)) and my static files is not been severed. Nginx Ubuntu -
django how to Pass an id from a template to a view
I want to update an item and I have this views.py def update(request,cl_itemid): if request.method == "POST": cursor = connection.cursor() resolve_item = get_object_or_404(Clearanceinsert, pk=cl_itemid) cursor.execute("select resolve_clearance_item('"+resolve_item+"')") return render(request, 'clearance/index.html') else: return render(request, 'clearance/index.html') when I clicked an item, the data goes to my def update then run this postgres function let's say I have this list of items test001 | update test002 | update here's my template <table style="width:100%"> <tr> <th>cl_itemid</th> <th colspan="2">Actions:</th> </tr> {%for data in data%} <tr> <td>{{data.cl_itemid}}</td> <td><a href="{% url 'update' data.cl_itemid %}">Update</a></td> </tr> {%endfor%} </table> if this is not possible then maybe someone can recommend an alternative solution -
Updating database based on previous csv file uploads - delete - create - or update Python/Dajngo
Please need help with the following I am trying to update database in comparison to previous uploaded csv file. I need to update all fields except the vin if it changes (vin is the unique value), delete the item if it is no longer in the csv file and create one if one is new vin. stock_no make model trim miles 12345789098765432 4535 honda civic lx 89000 j4j4jj49098765432 3453 toyota corolla DX 54555 12345345438765432 6254 ford mustang es 101299 When I change any value and the csv is uploaded it makes a duplicate: def upload_file__view(request): form = form(request.POST or None, request.FILES or None) company = Comp_info.objects.last() if form.is_valid(): form.save() obj = c.objects.get(activated=False) with open(obj.file_name.path, 'r+') as f: reader = c.reader(f) for i, row in enumerate(reader): if i==0: pass else: # row = "".join(row) # row = row.replace(",", " ") # row = row.split() print(row) print(type(row)) vin = row[0].upper() condition = row[1].replace("U", "Used").replace("N", "New") stock_no = row[2] year = int(row[5]) make = row[3] model = row[4] trim = row[6] mileage = row[8] mpg_city = row[18] mpg_hwy = row[19] engine = row[9] transmission = row[12] fuel_type = row[11] vehicle_type = row[7] drive_type = row[20].replace("4X2", "2WD").replace("4X4", "4WD") exterior_color = row[15] interior_color = row[16] … -
Export Excel from Django with verbose names
I am using DjangoObjectActions from django_object_actions package that adds an action in Django Admin to export my Querys model to excel. class QueryAdmin(DjangoObjectActions, admin.ModelAdmin): def export_to_xls(self, request, obj): query_record = Query.objects.all().values('profile__full_name') return excel.make_response_from_records( query_record, 'xlsx', file_name="Querys" ) list_display = ('weight', 'height') export_to_xls.label = "Export to Excel" changelist_actions = ('export_to_xls',) I could not find how to export my table with columns' verbose names. I found how to just get the verbose names of columns but is there a way to export them to excel? I need it because verbose names are in different language and that would be really great to show columns titles like that. Also I was using charfields with choices in my models. If there is a way I could export values from choices (not only keys), that'd be very good. Would be grateful for any help! -
How do you immediately redirect to another view once a view is rendered in Django?
I have a view like below. class ConfirmationPageView(generic.TemplateView): template_name = "confirmation.html" What I want is to immediately move onto the below view once the ConfirmationPageView is loaded (which means its templates were loaded too). class SecondPageView(generic.TemplateView): template_name = "second.html" I don't care if the user can't see the ConfirmationPageView in this very short transition. I just need this confirmation page to show up breifly so that a third party analytics application can track whether a user visited this confirmation page. Thank you, and please leave any questions in the comments.