Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Automatically fill a foreign key form field from another model
Currently I am making a web portal to keep track of employee information. I am now adding onto this an absentee system to log them and keep track of attendance points they accrue. The Absentee model is linked to the Employee model as such: class Absentee(models.Model): employee = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name="absentee_employee") date = models.DateField(null=False, blank=False) reason = models.ForeignKey(Absence, null=True, on_delete=models.CASCADE, related_name="absentee_reason") added_by = models.ForeignKey(Supervisor, null=True, on_delete=models.SET_NULL, related_name="absentee_supervisor") comment = models.CharField(max_length=255, blank=True, null=True) class Meta: ordering = ('date', ) def __str__(self): return f"{self.employee.CoreID} [{self.reason.points}] - {self.comment}" I have managed to be able to show the absentees as a table when you go to an individual employee's detail page, referenced by the Employee model. Within this employee detail page, there is a button to add an absentee that goes into a form to create a new Absentee, referencing the Absentee model. However, the problem is that I can't fill the foreign key field 'employee' automatically based on the which employee the user was looking before being directed to the form. Is there a way to complete this field automatically? Here are the urls and views: urls.py: path('employees/<int:pk>/', views.ManpowerDetailView.as_view(), name='manpower_detail'), path('employees/<int:pk>/absentee/new/', views.AbsenteeCreateView.as_view(), name='absentee_new'), views.py: class ManpowerDetailView(GroupRequiredMixin, DetailView): model = models.Employee template_name = … -
local variable 'form1' referenced before assignment
my problem is that when i submit the form it shows me this error and i can't see where the erroro is !! @login_required def update_profile(request): if request.method == 'POST': user_u = UpdateUser(request.POST) profile_u = UpdateProfile(request.POST) if user_u.is_valid() and profile_u.is_valid(): request.user.username = user_u.cleaned_data['username'] request.user.first_name = user_u.cleaned_data['first_name'] request.user.last_name = user_u.cleaned_data['last_name'] request.user.email = user_u.cleaned_data['email'] request.user.save() prf = Profile.objects.get(user=request.user) prf.Zip_code = profile_u.cleaned_data['Zip_code'] prf.Phone = profile_u.cleaned_data['Phone'] prf.save() return redirect(reverse('profile')) else: data1 = {'username': request.user.username, 'email': request.user.email, 'first_name': request.user.first_name, 'last_name': request.user.last_name} profile = Profile.objects.get(user=request.user) data2 = {'Phone': profile.Phone, 'Zip_code': profile.Zip_code} form1 = UpdateUser(initial=data1) form2 = UpdateProfile(initial=data2) return render(request, 'store/updateprofile.html', {'form1': form1, 'form2': form2}) -
Error using inspectdb in DJANGO: generated just 1 table
I have a "problem" in the models generated in django, I have 13 tables in the database, but the command: python3 manage.py inspectdb, only the History table and the default django table is generated while the Author and Category tables not, below the database and the model generated: the database tables from __future__ import unicode_literals from django.db import models class AuthGroup(models.Model): name = models.CharField(unique=True, max_length=80) class Meta: managed = False db_table = 'auth_group' class AuthGroupPermissions(models.Model): group = models.ForeignKey(AuthGroup, models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = False db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): name = models.CharField(max_length=255) content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING) codename = models.CharField(max_length=100) class Meta: managed = False db_table = 'auth_permission' unique_together = (('content_type', 'codename'),) class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class AuthUserGroups(models.Model): user = models.ForeignKey(AuthUser, models.DO_NOTHING) group = models.ForeignKey(AuthGroup, models.DO_NOTHING) class Meta: managed = False db_table = 'auth_user_groups' unique_together = (('user', 'group'),) class AuthUserUserPermissions(models.Model): user = models.ForeignKey(AuthUser, models.DO_NOTHING) permission = models.ForeignKey(AuthPermission, models.DO_NOTHING) class Meta: managed = False db_table = … -
Where to put django files on server?
I have a question. I work with one guy who is developing in Php, I am developing in Django right know. This is my first time doing something for other people and he firstly asked me to put my application to Apache Web server document root(I think he didn't know that much about Django, and he did everything this way), so I did it, because I didn't know that much about Apache and servers. But right know I am scared because I have all the python files in document root and I realized that this Web server document root \www\myproject might be accessible to other people. How should I change it, where should I put it, what is the best practice? I am deploying with mod_wsgi and Apache 2.4. In the documentation it says, that I shouldn't put code in Web server document root too, but if I put it somewhere else can I access it the same way, like I used to when it was on the Web server document root? Will I have to do something other than changing paths in Apache config? -
upload multiple files using django-admin interface?
I have a product model and I have an imagefield for uploading images. But then when i try to upload images from the django-admin interface, i can only upload 1 at a time.I would like to know if there is a way such that i can upload multiple images within the django interface. Is there a way to achieve that ? models.py class Product(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True,help_text = 'Unique value for product page URL, created from name.') brand = models.CharField(max_length=50) sku = models.CharField(max_length=50) price = models.DecimalField(max_digits=9, decimal_places=2) old_price = models.DecimalField(max_digits=9, decimal_places=2,blank = True, default = 0.00) image = models.CharField(max_length=50) thumbnail = models.FileField(upload_to='static/images/products/thumbnails', null=True, blank=True) productimage = models.FileField(upload_to='static/images/products/main', null=True, blank=True) is_active = models.BooleanField(default=True) is_bestseller = models.BooleanField(default=False) is_featured = models.BooleanField(default=False) quantity = models.IntegerField() description = models.TextField() meta_keywords = models.CharField(max_length=255,help_text = 'Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField(max_length=255,help_text = 'Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) categories = models.ManyToManyField(Category) def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog:products', kwargs={'product_slug': self.slug}) def sale_price(self): if self.old_price > self.price: return self.price else: return None class Meta: ordering = ['-created_at'] admin.py class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm # sets values for how the admin site lists … -
send a file in server to another server use rest framework
I have a server that generates a file I want to send that file to another server when the file is ready so the server that receives file should always listen and I use Django rest framework does anybody have a link to help me -
How to make a Chat in Django Rest Framework with Firebase?
in my project, I'm developing a backend with django rest framework, the front-end is iOS. I need create a chat real time with firebase in API-DRF, for the front-end receive and send informations in EndPoints. In my project, I have EndPoints for login, registration, logout, reset_password and etc, and I have Authentication by Token in my project. My question is, How to make a firebase chat with EndPoints for iOS_app get access?? Thanks. -
How do I configure a django app to work with a mysql data cluster?
I would like to make a heavy use out of all the features provided by the django.db.backends.mysql backend but get it to work with a cluster. I believe the easiest way to do that would be to write a controller that would asynchronously write to a few dbs located on separate hosts and from time to time synchronise them. What do you say? -
Split a Response in Python
I am trying to get a credit card's credential from the front-end, I am getting a 'expiry date' response in ajax 20/2020, and i am trying to split it using python split() function. x = 20/2020 I want result as 20 and 2020 but its coming it different ways as mentioned below, so how can i get two integers in split? x.split() = ['20/2020'] x.split("/") = ["20","2020"] Right now i am getting two or one string in output. -
Can't pass arguments to a procedure
I want to execute stored procedure in sql server, where arguments are as follows (picture). Unfortunately, no matter what format of the query I use, I still get the error not all arguments converted during string formatting The code works until i.description line, where the error occurs. I tried also with str(i.description), but in vain. Btw, I know I shouldn't use __str__(), I am aware of that. It simply doesn't matter in this case in models.py description = models.CharField(max_length=40, blank=True) -
How to include an app url within another app?
Suppose I have two app app1 and app2 I want to include the url of app 2 in app 1 without registering in my mail urls.py.. For example: I want to do url(r"^app2/", include("app2.urls", namespace="app2")), in app1 urls.py not in my main urls.py Is this thing possible in a django project?? if it is..Plz help Thank you -
Django does not support REST request Content-type header as "multipart/form-data"
On the server side, Django rest server is configured with following parsers in settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser' ) } When I send a request from a client with the content-type header as "multipart/form-data", it is not resolving the request data sent from the client(file upload). In the debug mode, request.FILES is coming as Empty If I send the same request without the content-type header, the request object contains the File upload data(success case). In the debug mode, request.FILES contains the files uploaded. We have many REST clients and I cannot force the clients not to set the content-type header. Why is Django not able to resolve multipart data when the content-type header = "multipart/form-data". Am I missing any configuration here? -
How can I set field properties when an object is being created in Django?
Lets say I have a model like so: class Article(models.Model): title_max_length = models.IntegerField(default=255) title = models.CharField(max_length=self.title_max_length) Basically, the user will set the title_max_length, and using that, we will set the title field max_length when an object is created. Is there any way to do this? -
Django Unit test for returning absolute url in models
Below is models.py class Unit(models.Model): name = models.CharField(max_length=200) start = models.DateTimeField() end = models.DateTimeField() description = models.TextField() deleted = models.BooleanField(default=False) def clean(self): if self.end and self.start and self.end <= self.start: raise ValidationError({ 'end': _('End date should be after start date') }) def get_absolute_url(self): return reverse('decentmark:unit_view', kwargs={'unit_id': self.pk}) I wrote few tests for date validation etc. Need some help for writing test for get_aubsolute_url -
How do i create a new proxy model based on another model in django?
I have a model named tranasaction. class transactions(models.Model): id = models.AutoField(primary_key=True) date = models.DateTimeField(default=datetime.now, blank=True) saleduser = models.ForeignKey('UserData',on_delete=models.CASCADE, related_name='vclouduser_data', blank=True, null=True) brand = models.CharField(max_length=50,blank=True) type = models.CharField(max_length=50,blank=True) quantity = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2) amount = models.DecimalField(blank=True,null=True,max_digits=20,decimal_places=2) And I need to create a summary report, so I create a new Model. class SaleSummary(transactions): class Meta: proxy = True verbose_name = 'Sale Summary' verbose_name_plural = 'Sales Summary' what i need that i need to get the total amount of each type as a new model. please help me to solve this. Thanks in advance. -
django css file not loading
I'm struggling to load my custom.css file to use in my bootstrap template: error: "GET /static/artdb/css/custom.css HTTP/1.1" 404 1785 path to custom.css: static/artdb/css/custom.css base.html: {% load static %} : <!-- Custom styles for this template --> <link rel="stylesheet" href="{% static "artdb/css/custom.css" %}"> urls.py: urlpatterns = [ path('artdb/', include('artdb.urls')), path('admin/', admin.site.urls), ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') #STATICFILES_DIRS =(os.path.join(BASE_DIR,"static"),) any idea what's wrong? -
How can i pass style attribute in table in lxml
from lxml import html from lxml import etree import requests page = requests.get('http://www.freejobalert.com/upsc-advt-no-17/31908/') tree = html.fromstring(page.content) tables = tree.xpath('//table') file = open("output.html","wb") for t in tables: print(etree.tostring(t)) file.write(etree.tostring(t)) ex : table style="color:red;padding:5px;" How can i pass style attribute in table in lxml -
Cache Django Templates in multi-tenant site
I have a multi-tenant django project, where there is a single django instance serving multiple tenants from separate databases. It is fully operational in production. I have template caching enabled, which was fine, until I implemented a per-tenant template loader, which essentially allows tenantXYZ to define a customised copy of /some_app/templates/some_template.html. So if the url starts with tenantXYZ, the page loads that template instead of the base version of /some_app/templates/some_template.html, allowing very powerful per-tenant customisation. The problem is template caching (which we only enable on production) returns a cached copy of /some_app/templates/some_template.html, therefore not necessarily returning the correct template! My plan is to subclass Django's django.template.loaders.cached.Loader to make it use a separate cache per tenant (which is what multi-tenant tools do with the normal cache anyway, see django-db-multitenant section on cache KEY_FUNCTION) https://github.com/django/django/blob/master/django/template/loaders/cached.py But I am struggling to understand exactly how the cached.Loader works. It seems that its 'cache' is just a dictionary (in which case I can change it to use a dictionary per tenant to keep the caches separate) and infers that there is only one instance of the loader running. Are those assumptions correct, or does it actually use the CACHE settings (e.g. in a base class … -
many to many filter in django rest framework
I had an issue about filtering retrieving data in relation many to many models.py class Team(models.Model): name = models.CharField(blank=True, unique=True, max_length=100) players = models.ManyToManyField(User, blank=True, related_name='players') seializers.py class MyTeamListSerializer(ModelSerializer): class Meta: model = Team fields = ['name'] views.py class MyTeamListAPIView(ListAPIView): queryset = Team.objects.all() serializer_class = MyTeamListSerializer permission_classes = [IsOwnerOrReadOnly] pagination_class = ProfileLimitPagination filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('players') filter_class = TeamFilter filters.py class TeamFilter(django_filters.FilterSet): teams = django_filters.CharFilter( players='players__id', lookup_type='contains', ) class Meta: model = Team fields = ('players', 'teams',) now, what im trying to do is, retrieve list of my teams that im player in. so i want to request my teams get response list of my teams. i dont know what the problem exact but im new in django rest framework. so, please any one have the solution please help me in my case or if you have another solution to do what i want. thanks -
get 500 on running url and the error is Connection aborted gaierror -2 Name or service not known
ConnectionError(('Connection aborted.', gaierror(-2, 'Name or service not known'))) caused by: ProtocolError(('Connection aborted.', gaierror(-2, 'Name or service not known'))) -
Django Model Formset ignore Form Instance on is_valid()
I have a Formset made up by a Form where I exclude a required field that I want to fill programatically instead of asking the user to fill it. My expectation is that I can exclude it from my request.POST dictionary, and add it with the line below, and that the is_valid() method will both use the request.POST data, and the initial data added to the instance passed to the form, to validate and save it. form_kwargs={"instance": MyModel(sale=5)} # My view.py formset = self.get_formset( data=self.request.POST, form_kwargs={"instance": MyModel(sale=5)} ) # Error here, 'sale' is not set. if formset.is_valid(): formset.save() The get_formset() method returns an instance of the formset. # My formset factory method def get_formset(self, **kwargs): MyFormSet = forms.modelformset_factory(MyModel, form=MyForm) ... return MyFormSet(**kwargs) -
Django CMS : How to place a button inside CMS preserving the link
I am using text plugin ( ck-editor ): Below is my source: <button onclick="location.href='http://www.example.com'" type="button"> www.example.com</button> After saving the text plugin, I could notice that the source under text plugin has changed as below: <button type="button">www.example.com</button> Am I using a wrong plugin? How to handle this case by preserving the link of the button. -
How to check user online and offline status
I am trying to check and display user online status with django and django rest framework. I have tried this article: Django - detect if user is online / offline But did not work on APIview only works on views with render and Httpresponse. -
TypeError get_queryset() missing 1 required positional argument: 'pk'
I am working on a accounting application... I have a model called group which I want to make inside a specific company... I mean different company will have different set of groups So,I have tried some thing like this in my list view class group1ListView(LoginRequiredMixin,ListView): model = group1 def get_queryset(self, pk): company_details = get_object_or_404(company, pk=pk) return self.model.objects.all().filter(Q(User=self.request.user) & Q(Company=company_details.id)) The User and Company fields are related through foreign key in my group1 model.. But getting this error, ' TypeError get_queryset() missing 1 required positional argument: 'pk'' Can any one tell me what I am doing wrong in this?? Thank you -
set html class to TextField in django model
I want to change TextField in my model to TinyMCE RichTextEditor. I have downloaded tinymce 4.8.3 development package and customized it. Then I pasted tinymce files to staticfiles directory. As I understand it, in order for everything to work, I must assign an HTML class for the <textarea> </textarea> element on the view page. How it works on the local html file. I've tried almost all the applications that are installed through the pip(django-tinymce, django-tinymce4-lite etc..). And I still wanted to adjust this rich text editor for myself. Rich Text Editor must be appeared on admin page. This is my models.py: class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() created = models.DateTimeField(auto_now_add=True) tags = TaggableManager(blank=True) class Media: js = ('js/init-tinymce.js', 'js/tinymce/tinymce.js',) admin.py: class PostModelAdmin(admin.ModelAdmin): list_display = ["title", "created"] list_display_links = ["title"] list_filter = ["created", "tags"] search_fields = ["title", "content",] class Meta: model = Post admin.site.register(Post, PostModelAdmin) Please explain to me if I understood something differently. I use Django 2.0.8 and python 3.6. On the Internet, I found how to set a class like in this form, but I can not add it to my project. class MyTextForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyTextForm, self).__init__(*args, **kwargs) self.fields['content'].widget.attrs['class'] = 'tinymce' class Meta: model …