Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix __init__() takes 1 positional argument but 2 were given
i have a search form that return to the user the stored records. what i want is to be able to return the template name and based on the template name. if the template name == "create_folder_test.html" the query will filter on the class Folder if the template name == "blog/list.html" the query will filter on the class suspect what it happen is once the user submit the search form it display the below error : TypeError at /folder/search/ init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/folder/search/?q=121 Django Version: 2.1.3 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Environment: Request Method: GET Request URL: http://127.0.0.1:8000/folder/search/?q=121 Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'widget_tweaks', 'import_export'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /folder/search/ Exception Value: init() takes 1 … -
Is it possible to parse datetime from CharField within a Django query?
When I was setting up my Django app, I created a CharField instead of DateTimeField for when an account is created. Is it possible to write a Django query that first parses the datetime from my CharField and then uses it in the filter? I know that I could do a migration, but I'm wondering if it's possible to achieve the same result without changing the field to a datetime field. from dateutil.parser import parse from datetime import datetime, timedelta # How I parse datetime from string normally account = Account.objects.get(id=1) datetime_from_string = parse(account.created) # How to filter by datetime with a proper DateTimeField time = datetime.now() - timedelta(hours=5) accounts = Account.objects.filter(created__lt=time) -
Display likers username in html template
I have added a user liking system, where a user can like posts. I have added this successfully, however can't seem to display the usernames of the people who liked the post. This is my current implementation. models.py class Post(models.Model): likes = models.ManyToManyField(User, related_name='likes') @property def total_likes(self): return self.likes.count() views.py def likepost(request, pk): if request.method == 'POST': user = request.user post = get_object_or_404(Post, pk=pk) if post.likes.filter(id=user.id).exists(): post.is_liked = True post.likes.remove(user) post.save() else: post.is_liked = False post.likes.add(user) post.save() return redirect('home') home.html {% for post in posts.all %} <form id="like__post" method="POST" action="{% url 'likepost' post.id %}"> {% csrf_token%} <input type="hidden"> </form> <div style="position: absolute; bottom:80px; left: 85px;"> {% if post.is_liked == True %} <a href="javascript:{document.getElementById('like__post').submit()}"><img src="{% static 'heartred.png' %}" width="35px" height="35px"></a> {% else %} <a href="javascript:{document.getElementById('like__post').submit()}"><img src="{% static 'heart.png' %}" width="33px" height="33px"></a> {% endif %} {% endfor %} So far. In my template i get this: auth.User.None -
django-plotly-dash argument in template
I need to send initial data from my template to my dash script. I found demo of it here looks like this: {</span>% plotly_app name="simpleexample-1" initial_arguments='{"dropdown-color": {"value": "green"}}' %} I need to do the same and do it like this: {% plotly_app name="SimpleExample" initial_arguments='{"id": {"value": "2"}}' %} but how i get in my dash script? (Id should be like variable (i need to use this in all project) ) -
Python sorted() does not work Error: 'list' object has no attribute 'META'
I am getting an error:'list' object has no attribute 'META' when I tried to use sorted() function, and have no idea how to solve it... def sort_by(): data = ['a', 'c', 'b', 'a', 'n', 'j', 'r', 'p', 'x', 'l'] r = sorted(data) print(r) return r -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL
I have a problem when i deploy my django with wsgi, but not in dev mode, I use apache2 My user model is in authentification i've tried to migrate authentification first, but it doesn't work I've also already tried deleting the database, nothing's changed. Here is the stacktrace: AH00094: Command line: '/usr/sbin/apache2' AH00491: caught SIGTERM, shutting down AH00489: Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured -- resuming normal operations AH00094: Command line: '/usr/sbin/apache2' [remote ::1:57132] mod_wsgi (pid=8791): Failed to exec Python script file '/home/roo/myproject/Challenges/Challenges/wsgi.py'. [remote ::1:57132] mod_wsgi (pid=8791): Exception occurred processing WSGI script '/home/roo/myproject/Challenges/Challenges/wsgi.py'. [remote ::1:57132] Traceback (most recent call last): [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 178, in get_model [remote ::1:57132] return self.models[model_name.lower()] [remote ::1:57132] KeyError: 'users' [remote ::1:57132] [remote ::1:57132] During handling of the above exception, another exception occurred: [remote ::1:57132] [remote ::1:57132] Traceback (most recent call last): [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/contrib/auth/__init__.py", line 165, in get_user_model [remote ::1:57132] return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/registry.py", line 210, in get_model [remote ::1:57132] return app_config.get_model(model_name, require_ready=require_ready) [remote ::1:57132] File "/home/roo/myproject/venv/lib/python3.7/site-packages/django/apps/config.py", line 181, in get_model [remote ::1:57132] "App '%s' doesn't have a '%s' model." % (self.label, model_name)) [remote ::1:57132] LookupError: App 'authentification' doesn't have a 'Users' model. [remote ::1:57132] [remote ::1:57132] During handling of … -
__init__() takes 1 positional argument but 2 were given | TypeError at /accounts/login/$
I am using Django 2.2 and python 3. When I log in I am getting TypeError at /accounts/login/$ init() takes 1 positional argument but 2 were given Please Find the code of my login.html {% extends 'blog/base.html' % } {% block content %} <div class="jumbotron"> <h2>Please Login:</h2> <h3>(Must be SuperUser, please check with the site admin)</h3> {% if form.errors %} <p>Your Username and password didn''t match! Please try again. </p> {% endif %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} {{% form.as_p %}} <input type="submit" class="btn btn-btn-primary" value="Login"> <input type="hidden" name="next" value="{{next}}"> </form> </div> {% endblock %} Code of Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('accounts/login/$',views.LoginView,name='login'), path('accounts/logout/$',views.LogoutView,name='logout',kwargs={'next_page':'/'}) ] Kindly help -
Plotly dash in Django with multiple users and same chart
I'm completely stuck and wasted so many hours of my life. I've been learning plotly dash in Django for about a week and I just can't find a way to get it to do what I want. I simply want to have a chart that multiple users can see and for it to update for all users when values change. The app will ask all users a question with a rating from 1 to 9. As each user votes a bar chart will show each user's score which they can all see. Can someone please point me in the right direction of a good example or tell me how it's done? -
How to revert objects using django-simple-history
In this answer, the user provided the following HistoricForm to revert an object to an earlier instance of the object: class HistoricForm(object): def __init__(self, *args, **kwargs): self.history_id = kwargs.pop('history_id', None) instance = kwargs.get('instance') if instance and self.history_id: kwargs['instance'] = self.get_historic_instance(instance) super(HistoricForm, self).__init__(*args, **kwargs) def get_historic_instance(self, instance): model = self._meta.model queryset = getattr(model, 'history').model.objects historic_instance = queryset.get(**{ model._meta.pk.attname: instance.pk, 'history_id': self.history_id, }).instance return historic_instance I have added this code to my models.py file, but I am now stuck about how to actually revert a model. The user stated, You can revert by showing the historic instance and save (this way you will post your historic data). I created a view and a corresponding template that shows all the versions of a given object in its history using django-simple-history. However, I don't understand how to allow the user to revert to one of these versions using the above form. Can someone please provide me some guidance? -
Django ORM. How to exclude old data?
I want to exclude unnessery old records from my queryset. I tried use annotate(Max('pc_users__created')), but this is not what i want. I think i should use 'group by' or something like that, but I can not understand how. Here's my models.py class Room(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) room_number = models.SmallIntegerField() def __str__(self): return f'Room №{self.room_number}' class UserProfiles(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) def __str__(self): return f'{self.name}' class Pc(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) title = models.CharField(max_length=100) ram = models.SmallIntegerField() cpu = models.CharField(max_length=20) gpu = models.CharField(max_length=20) def __str__(self): return f'{self.title}' class PcUsers(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) pc = models.ForeignKey(Pc, on_delete=models.PROTECT, related_name='pc_users') user = models.ForeignKey(UserProfiles, on_delete=models.PROTECT) def __str__(self): return f'{self.pc}: {self.user}' class PcRooms(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) pc = models.ForeignKey(Pc, on_delete=models.PROTECT, related_name='pc_rooms') room = models.ForeignKey(Room, on_delete=models.PROTECT) def __str__(self): return f'{self.pc}: {self.room}' and views.py: from myapp.models import Pc def report(request): data = Pc.objects.values( 'id', 'title', 'pc_users__user__name', 'pc_rooms__room__room_number' ) return render(request, 'report.html', {'data': data}) Also here is my data from admin site I want exclude all repetitive records and keep all newest records. Like this +-------+------------+---------+---------+ | ID Pc | Pc Title | Pc User | Pc Room | +-------+------------+---------+---------+ | 1 | … -
Django: form not validating
I had a form working perfectly right, but now it doesn´t work anymore. Can´t detect what I had changed that is affecting this. The form with it´s inital data is showed correctly in the template, but for some reason it´s not validating in the view. The rest of the forms are working without problems. The model class OperacionK(models.Model): comprobante = models.CharField(max_length=200, help_text="", blank=True, null=True) destinatario = models.ForeignKey(Contactos, related_name='cliente', help_text="", blank=True, null=True, on_delete=models.CASCADE) estatus = models.ForeignKey(EstatusOperacionK, default=1, blank=True, null=True, on_delete=models.CASCADE) fecha = models.DateField(help_text="", default=datetime.date.today, blank=True, null=True) fecha_conf_comercial = models.DateField(help_text="", blank=True, null=True) fecha_conf_admin = models.DateField(help_text="", blank=True, null=True) fecha_conf_armado = models.DateField(help_text="", blank=True, null=True) fecha_conf_despacho = models.DateField(help_text="", blank=True, null=True) fecha_conf_entregado = models.DateField(help_text="", blank=True, null=True) fecha_conf_cobrado = models.DateField(help_text="", blank=True, null=True) fecha_conf_cerrado = models.DateField(help_text="", blank=True, null=True) condicion_de_pago = models.IntegerField(help_text="Tier", blank=True, null=True) forma_de_pago = models.ForeignKey(FormasDePago, related_name='cliente', help_text="", blank=True, null=True, on_delete=models.CASCADE) descuento_general = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=True, null=True) numero_remito = models.CharField(max_length=200, default="TO-BE-DEFINED", help_text="", blank=True, null=True) total_operacion = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=True, null=True) total_unidades = models.IntegerField(help_text="Tier", blank=True, null=True) creador = models.ForeignKey(get_user_model(), help_text="Usuario", blank=True, null=True, on_delete=models.CASCADE) condicion_despacho = models.TextField(max_length=500, help_text="En 48 hs", blank=True, null=True) material_extra = models.TextField(max_length=500, help_text="", blank=True, null=True) fecha_deseada_entrega = models.DateField(help_text="", blank=True, null=True) fecha_estimada_cobro = models.DateField(help_text="", blank=True, null=True) contacto_entrega = models.ForeignKey(Personas, related_name='Persona', help_text="", blank=True, null=True, on_delete=models.CASCADE) tipo_operacion = … -
Return Serialized data without storing one field in the database?
Assuming I have a model as follows: class MyModel(models.Model): value = models.TextField(null=True) And I have a serializer as follows: class MyModelSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False, allow_null=True) class Meta: model = MyModel fields = ('value') Is it possible to pass a value to the serializer that is not saved in the database, just passed back in the exact same position? So if I send the application { 'value': 'true', 'uuid': '123' } It would return { 'id': 1, 'value': 'true', 'uuid': '123' } -
Communication between Python desktop app and remote Django server
Would it be possible to have two-way communication between a Python desktop application and a Django server, and if so what would be the best method? The Django server would host a page that allows a user to send commands to the desktop application and view the status of the desktop application. The desktop app would need to send status updates. I've looked into Channels with Django and the client would just need to create a TCP socket connection to send its data. I don't quite know how Django would send the required data to the client. Thanks for any help or input. -
Fixing Django-Haystack Exact Query
I'm trying to fix my Django-haystack search results to only return outputs of the exact query. The principal usecase is that a user enter is destination and get only the results that matches this given place. But the problem I have now is that when a user try for example, a query for "Mexico", the search results also returns information in "Melbourne" which is far from being user-friendly and accepted. What I've tried so far but still not working: My forms.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) self.q_from_data = data.get('q', '') super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() # Ideally we would tell django-haystack to only apply q to destination # ...but we're not sure how to do that, so we'll just re-apply it ourselves here. q = self.q_from_data sqs = sqs.filter(destination=Exact(q)) print('should be applying q: {}'.format(q)) print(sqs) if self.ptag: print('filtering with tags') print(self.ptag) sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag]) return sqs My search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from .models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/product_text.txt') … -
How to Set Rendered URL Endpoint
I know this is an easy problem, but I cannot seem to get it working properly. I recently changed the urlpatterns from mydomain.com/website/template to mydomain.com/template in my project. However, when I render pages, I am being redirected to the old pattern still. When I remove website from the URL, the page is render correctly. How can I render the page without website in the urlpattern? Would I make this change in urls.py or views.py? For the example below, I want the end result to be: mydomain.com/connectwise/search?search_query= I tried return render(request, '/search.html', context) but then the application does not recognize the URL endpoint and returns resource not found. views.py return render(request, 'website/search.html', context) urls.py (application) urlpatterns = [ path('connectwise/search', views.search_bar, name='search_bar'), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('website.urls')), ] -
Is it ever possible to delete a URL path : Django
I had in my urls.py file, url patterns for certain data processing requirements and later I realized that from among a bunch of them, one was not intended as its requirement had ceased. However, when I am trying to delete the particular line (the second pattern in the excerpt of the urls.py reproduced here), I am getting the following error at page load ('holding_list'): NoReverseMatch at /supp/holding_comp/ Reverse for 'holding_change' not found. 'holding_change' is not a valid view function or pattern name. I have checked all the references (I think) wherever the path might have been referred to (including the related template). urls.py path('supp/holding_comp/', views.HoldingListView.as_view(), name='holding_list'), ... ... path('supp/holding_comp/edit/<int:pk>/', views.HoldingUpdateView.as_view(), name='holding_change'), How do I delete the second url pattern (the one for "edit" view)? I tried to look for a similar query but failed to (may be for want of a suitable search string). Any clue will be appreciated. -
How to make swagger schema for file upload API in django-rest-framework using drf-yasg?
I am not able to find any support for making a schema for the file upload API. The Swagger UI must have a button allowing a tester to upload a file for testing purposes. I am using firebase as a database so serializers and models don't come into the picture. I am using only Django's rest framework. I have looked at drf-yasg's documentation that suggests using Operation for file upload. But It is a very abstract and obscure documentation. -
I'm working on a Django project that involves to create an online compiler for C++ code
I'm working on a Django project that involves to create an online compiler for C++ code. have the same for python code. Can anyone append it for C++ Thanks class New(View): template_name = 'webapp/new.html' form_class = SofaProjectForm def get(self,request): form = self.form_class(None) return render(request,'webapp/new.html',{'form':form}) def post(self,request): if request.method == 'POST': form = self.form_class(request.POST) code = request.POST['code'] run = runcode.RunPyCode(code) rescompil, resrun = run.run_py_code() resrun=resrun rescomp=rescompil if not resrun: resrun = 'No result!' else: code = default_py_code resrun = 'No result!' rescompil = "No compilation for Python" return render (request,'webapp/new.html'{'code':code,'resrun':resrun,'rescomp':rescomp}) -
How to change the presentation of a DataTimeField field to a format '% Y-% m-% d% H:% M:% S' to be serialized
Good afternoon, I have the following model in Django, and the field last_update is a Faithful DateTme field that is represented as follows when I serialize it: "2019-08-06T14: 19: 05-04: 00" And I want to represent it like this: "2019-08-06 19:05:04" class Interface(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipo,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puerto,on_delete=models.DO_NOTHING,related_name='puerto_origen', null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipo,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puerto,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interface' class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) ip_gestion_origen=serializers.CharField(source='id_EquipoOrigen.ip_gestion',read_only=True) vendedor_origen=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) ip_gestion_destino=serializers.CharField(source='id_EquipoDestino.ip_gestion',read_only=True) vendedor_destino=serializers.CharField(source='id_EquipoDestino.vendedor',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) #Los campos que voy a mostrar en mi serializacion con la clase Meta class Meta: model=Interface fields=('id_interface','id_EquipoOrigen','EquipoOrigen','ip_gestion_origen','id_PuertoOrigen', 'PuertoOrigen','LocalidadOrigen','CategoriaOrigen','vendedor_origen','estatus', 'etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description', 'id_EquipoDestino','EquipoDestino','ip_gestion_destino','vendedor_destino','id_PuertoDestino','PuertoDestino','LocalidadDestino', 'CategoriaDestino','ultima_actualizacion',) class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interface.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination filter_class=InterfacesFilter -
Django Simple Query Filter
Trying to filter data by logged in user, but the code results in showing all users data instead of just the ones created by user. What am I missing here ? There is no issue with serializer. I am guess I am missing some fundamental here. views.py class TimelinePostList(generics.ListCreateAPIView): serializer_class = TimelinePostSerializer def get_queryset(self): queryset = Timeline_Post.objects.all() user = self.request.user queryset.filter(author = user) return queryset models.py class Timeline_Post(models.Model): slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) text = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) Actual results: { "count": 2, "next": null, "previous": null, "results": [ { "slug": "secon_post", "author": 8, "updated_on": "2019-08-06T18:47:43.915249Z", "text": "secon_post", "created_on": "2019-08-06T18:47:43.915249Z", "status": 0, "media": [] }, { "slug": "lkkej", "author": 5, "updated_on": "2019-08-06T18:04:11.175809Z", "text": "first Post", "created_on": "2019-08-06T18:04:11.175809Z", "status": 1, "media": [] } ] } Expected Results: { "count": 1, "next": null, "previous": null, "results": [ { "slug": "lkkej", "author": 5, "updated_on": "2019-08-06T18:04:11.175809Z", "text": "first Post", "created_on": "2019-08-06T18:04:11.175809Z", "status": 1, "media": [] } ] } -
How to Make Blog Title Unique to User?
I was wondering how to enforce that the blog post title created by a user does not match the name of any other blog posts created by that user. Here is my models.py, as I think this is where it should go, but I can add any other files as needed. Thanks in advance for any tips. models.py class Item(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) name = models.CharField(max_length=50) category = models.CharField(max_length=99) image = models.ImageField(upload_to='images/') #todo: validate size or resize here # ... edited out some fields for SO post slug = models.SlugField(editable=False) def save(self): if not self.id: #new item object, setting slug: self.slug = slugify(self.name) super(Item, self).save() -
How do I set initial request.user as initial modelform data?
I've tried many options but none have worked. I want to initialize a form with logged in user as initial data. #My form class AdaugaPorumbel(forms.ModelForm): class Meta: model = Porumbei fields = ['data_adaugare', 'crescator', 'serie_inel', 'anul', 'culoare', 'culoare_ochi', 'sex', 'ecloziune', 'rasa', 'linie', 'nume', 'tata', 'mama', 'compartiment', 'status', 'data', 'vaccinat', 'info', 'imagine', 'imagine_ochi'] widgets = { 'ecloziune': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'data': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'vaccinat': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'info': forms.Textarea(attrs={'class': 'form-control mt-15', 'rows': '3', 'placeholder': 'Vor apărea în pedigree'}), } # My view @login_required(login_url='/auth/login/') def porumbelnou(request): if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES, initial={'crescator': crescator}) if form.is_valid(): form.save() return HttpResponseRedirect('/porumbei/vizualizare') else: form = AdaugaPorumbel() context = { 'form': form, } template = loader.get_template("adaugare-porumbel.html") return HttpResponse(template.render(context, request)) # I've already try but still won't working if form.is_valid: form.save(commit=False) form.crescator = request.user form.save() ... On models, crescator field is a foreignkey set to settings.AUTH_USER_MODEL. -
Is there a way to inherit the template of an abstract parent model class in Wagtail?
I've got an abstract Page model that defines common fields for a type of page that I then subclass to restrict the types of subpages allowed. I'd like all of the subclasses of this abstract model to default to using the template defined in the abstract model, but it seems like they don't. class BaseListing(Page): empty_message = RichTextField() intro = RichTextField() template = 'listing.html' class Meta: abstract = True class BlogListing(BaseListing): subpage_types = ['BlogPost'] I'd like wagtail to default to using the template defined in the BaseListing model, but it looks for a blog_listing.html template unless I specifically set template on the BlogListing model like this: class BlogListing(BaseListing): subpage_types = ['BlogPost'] template = 'listing.html' -
Aggregate table data in django
I am working on a Django project, and I have a model with the following columns: course id, username date activity_type activity_action count where activity_type can be : video, problem, question and activity_action can be: viewed, solved, asked I am trying to figure out a Django query that given a course id, will return me the following: username number of videos viewed by user for the entire course number of videos viewed by user in last week number of problems solved by user for the entire course number of problems solved by user in last week .... the latest date of user activity is using a single query make sense, or should I simply pull data and manipulate it in code? -
How can I template filter backwards two different models?
I've got three models, "Property", "Owners" and "ContactsOwner", these last one is where I save the owners contacts. # APP: Owners - models.py class Owner(models.Model): name = models.CharField(db_column='Owner_Name', max_length=200) surname = models.CharField(db_column='Owner_Surname', max_length=30) nif = models.IntegerField(db_column='Nif_Number', blank=False, null=False, default='000000000') doc_number = models.CharField(db_column='Document_Number', max_length=20, blank=True, null=True) doc_type = models.CharField(db_column='Document_Type', max_length=20, blank=True, null=True, choices=DOCUMENT_TYPE_CHOICES) address = models.CharField(db_column='Address', max_length=200, blank=True, null=True) post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) nationality = models.CharField(db_column='Country', max_length=20, blank=True, null=True) notes = models.CharField(db_column='Notes', max_length=250, blank=True, null=True) property = models.ManyToManyField(Property) class Meta: db_table = 'Owner' def __str__(self): return self.name def get_absolute_url(self): return reverse("owners:owner_detail",kwargs={'pk':self.pk}) class ContactsOwner(models.Model): owner = models.ForeignKey(Owner, models.DO_NOTHING, db_column='Owner', related_name='owner_contact') # Field name made lowercase. type = models.CharField(db_column='Type', choices=CONTACT_TYPE_CHOICES, max_length=25, blank=True, null=True) # Field name made lowercase. number = models.IntegerField(db_column='Number', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='Email', max_length=100, blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'Contacts_Owner' verbose_name_plural = "Owners Contacts" # APP: Properties - models.py class Property(models.Model): property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase. address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase. post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase. bedrooms = models.IntegerField(db_column='Bedrooms', …