Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django post_save() signal triggered when an instance is deleted
I'm currently working on a social network site with Django. I am working on the "tag" feature, which sends a Notification to a user whenever they are tagged in a Post. I created a post_save signal like this: def post_tagged(*args, **kwargs): instance = kwargs['instance'] message = f'{instance.user.slug} mentioned you in a post.' #Find in the content of the post if there are any "@username", if yes create a Notification object for user in MyUser.objects.all(): if instance.content.find(f'@{user.slug}') != -1 and instance.user != user: Notification.objects.create(user = user, message = message) models.signals.post_save.connect(post_tagged, sender = Post) This is working fine when I create a new Post, but it also triggered when I delete a Post. This is the code in the view to delete a post: if 'deletePost' in request.POST: postId = request.POST.get('deletePost', None) post = Post.objects.get(pk = postId) if request.user == post.user: post.delete() message = 'Success' else: message = 'Fail' jsonData = {"message": message,} return HttpResponse(json.dumps(jsonData)) Also if it helps you can see I'm using ajax to send the request to the view. And the delete is also working fine. The only problem is that it also create a Notification to the tagged users when I delete a post. Anyone having the same β¦ -
Django CMS : How to load images from Content delivery network (CDN)
Consider how I did without django-CMS HTML {% static 'mypath/mypic.svg' %} Settings.py try: static_url = cdn_connect() // this method returns the cdn url. exception: static_url = /static The above setup was working fine and images are getting rendered from CDN. Current step up with Django-CMS: Instead of using {% static 'mypath/mypic.svg' %} in html am using /static/mypath/mypic.svg in image src ( Using text plugin as image plugin doesnt support this /static/ path ) The images are getting rendered from static path but not from CDN -
SQL query on Many to Many with intersection
I am working with django-categories which uses django-mptt under the hood. (That implicates db structure that I am using.) I have some products: product -------- id | name 1 | Apple 2 | Orange 3 | Tomato Categories: categories ---------- id | name | parent | tree_id | level 1 | Type | null | 1 | 1 2 | Fruit | 1 | 1 | 2 3 | Vegetable | 1 | 1 | 2 4 | Color | null | 2 | 1 5 | Orange | 4 | 2 | 2 6 | Red | 4 | 2 | 2 7 | Green | 4 | 2 | 2 8 | Dark green | 7 | 2 | 3 9 | Orange | 4 | 2 | 2 Which is tree with single root (nodes have also fields order, left, right but I don't think that it is relevant here): root/ βββ Type/ β βββ Fruit β βββ Vegetable βββ Color/ βββ Red βββ Green | βββ Dark green βββ Orange And M2M table: product_categories ------------------ id | product_id | category_id 1 | 1 | 2 2 | 1 | 6 3 | 2 | 2 4 β¦ -
Update FileField file value
I have accidentally stored a lot of files with the wrong path. The value of the file field got MEDIA_ROOT prepended since I was using this as the upload_to value for the FileField: file = models.FileField(upload_to=settings.MEDIA_ROOT + "attachments/%Y/%m/%d/", null=True) Thus the values stored in the database for the file field is: /Users/hammer/Dev/*****/media/attachments/2018/09/12/pdf-test.pdf And what I want is: attachments/2018/09/12/pdf-test.pdf This is the model now: class Attachment(models.Model): file = models.FileField(upload_to="attachments/%Y/%m/%d/", null=True) original_filename = models.CharField(null=False, blank=False, max_length=4096) file_type = models.ForeignKey("FileType") mail = models.ForeignKey("mail", null=False, blank=False) How do I change the actual stored path for the file field? I've tried setting it with: attachment.file._set_file(fixed_path) But the value stored in the database is not changed when I save the attachment object. -
DRF-GIS: Unable to convert to python object: Invalid geometry pointer returned from OGR_G_CreateGeometryFromJson
I'm trying to create a Polygon from GeoJSON data, but djangorestframework-gis is giving Unable to convert python object error. Can't figure it out, what's wrong. Here's my models. class ServiceArea(models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) area = models.PolygonField() class ServiceProvider(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=20) language = models.CharField(max_length=30) currency = models.CharField(max_length=5) areas = models.ManyToManyField(ServiceArea) Here's my serializers. class ServiceAreaSerializer(GeoFeatureModelSerializer): class Meta: model = ServiceArea geo_field = 'area' fields = ['id', 'name', 'price'] class ServiceProviderSerializer(ModelSerializer): areas = ServiceAreaSerializer(read_only=True, many=True) class Meta: model = ServiceProvider depth = 1 fields = ['id', 'name', 'email', 'phone', 'language', 'currency', 'areas'] When I'm trying to create ServiceArea, calling is_valid() raising this error. "area": [ "Unable to convert to python object: Invalid geometry pointer returned from \"OGR_G_CreateGeometryFromJson\"." ] Here's the GeonJSON data I'm passing to. { "type": "Feature", "geometry": { "area": { "type": "Polygon", "coordinates": [ [ [-64.73, 32.31], [-80.19, 25.76], [-66.09, 18.43], [-64.73, 32.31] ] ] } }, "properties": { "name": "Chourongi", "price": 225 } } I'm using spatialite as database. -
request.POST.get() is giving None
class ApiLoginView(TemplateView): template_name = 'index.html' def post(self,request): email = request.POST.get('Email') password = request.POST.get('Password') print(email) print(password) API_KEY = GetAPIkey().api_key_token() API_URL = GetAPIurl().api_url_token() parameter = { 'authToken':API_KEY, 'email':email, 'password':password, } url = '{}{}'.format(API_URL,'/rest/storeLogin') r = requests.post(url = url, params=parameter) print(r.url) print(request.user) return HttpResponse(r) I am trying to get data from request.POST method, but it is sending me NONE value everytime when i print email and password. Where am i wrong? <form class="my-login-form" id="sanjh_login_form" method="post" url="/login"> {% csrf_token %} <div id="login-data"></div> <div class="field-wrap"> <input id='id_login-email' type="email" name="Email" required autocomplete="off" placeholder="Email Id"> </div> <div class="field-wrap"> <input id='id_login-password' type="password" name="Password" required autocomplete="off" placeholder="Password"> </div> <button id="login-btn" type="button" class="button button-block" >Login</button> <div class="forgot"><a class="user-form-toggle" href="#forgot">Forgot Password?</a></div> </form> -
Django; what should I do when code doesn't work suddenly
It's a general question as well. Today a part of my code doesn't work suddenly. How should I do to find the cause? The problem is a js file doesn't work today even though it worked yesterday and I didn't do anything to the code. The error says Uncaught ReferenceError: deleteEntry is not defined at HTMLButtonElement.onclick {% block javascript %} <script src="{% static 'js/upvote.js' %}"></script> <script src="{% static 'js/delete.js' %}"></script> {% endblock javascript %} The weird thing is upvote.js file does work. Also both files are already inside body tag. (I already seen the same questions and answers) How can I fix this kind of weird error? Also why does this kind of error happen? -
searching for career advice in web/mobile development
sorry that my first question is such a broad one but hear me out on this. I've finished javascript and python basics in addition to html/css and started to learn front-end using bootstrap and back-end using django and i've seen all of these (node.js vs django vs rails) questions. the thing is i want to learn react for full-stack development so i can work on mobile cross-platform apps and here is my status: I'm a high school student (senior year) looking to launch my freelance career no dollar currency bank account wanna get out of Egypt and move out to Canada (sounds naive for some people but it's my dream man!) any advice to get started?! -
Django custome admin selector from property in model
In my model I have a getter and setter for a property: class SomeModel(ext_models.TimeStampedModel): ... @property def test_field(self): return {'key1': 'val1', 'key2': 'val2'} @test_field.setter def test_field(self, value): print(value) I'd like to use the test_field in the admin as a selector. I have tried to add it in the fieldsets, but I receive the error Unknown field(s) test_field specified I have also added it to the readonly_fields and then the field is at least displayed, however just a string and not editable of course. Is there a nice way to get a simple selector widget displaying the dict? -
Calling a Django server function from PHP server
I Just hired as a junior python developer at a company. Here they want to pass a heavy tasks (bulk mailing,Excel import,PDF export) from a PHP server to a django server(celery) to reduce work load. In my computer I managed to run them both locally (separately). My question is what is the best way to pass the data or trigger a function at django server from PHP server For example consider the code below : some_shit.php public function actionExportPdf() { $mPDF = Yii::app()->ePdf->mpdf(); $model = new Gulfuniversityapplication('search'); $dbcriteria = Yii::app()->session['criteria']; $model->setDbCriteria($dbcriteria); $row = Yii::app()->db->createCommand("select field_data from modules where table_name='".$model->tableName()."'")->queryRow(); $filteredData = CJSON::decode($row['field_data']); //$filteredData = $data[$model->tableName()]; $stylesheet = file_get_contents(getcwd().'/path/to/core/assets/css/social.css'); $mPDF->WriteHTML($stylesheet, 1); $mPDF->WriteHTML($this->renderPartial('_exportPdf',array( 'model' => $model, 'data' => $filteredData, ), true)); $mPDF->Output(); } This is their PHP I have no idea what's in it. Here is my Django celery code tasks.py @shared_task def export_task(arg1,arg2): my_cursor = my_db.cursor() my_cursor.execute("SELECT arg1 FROM arg2") out =[] for i in my_cursor.fetchall(): out.append(i) my_cursor.execute("DESCRIBE arg2") column = [] for i in my_cursor.fetchall(): column.append(i[0]) df = pd.DataFrame(data=out,columns=column) writer = pd.ExcelWriter('output.xlsx') df.to_excel(writer,'Sheet1') writer.save() This is my first question here thanks in advance. I have been thinking about POST API calls from PHP if that's the only solution explain it β¦ -
Django rest framework - Create or update values from json
I am very much new to Django and Django Rest Framework. I have an API whose json format is as below (Simplified version for sake of simplicity) { "title" : "Lorem ipsum is a dummy title", "content" : "Lorem ipsum is a demo content" "tags" : ["Movies", "Food"] } Here is how my model looks like: class Tag(models.Model): class Meta: verbose_name_plural = "Tags" name = models.CharField(max_length=200) def __str__(self): return self.name class Post(models.Model): class Meta: verbose_name_plural = "Posts" title = models.CharField(max_length=255) content = models.TextField() tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Here is how my serializer (Tags, Posts) looks like: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' name = serializers.CharField(max_length=200) def create(self, validated_data): return Tag.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() return instance class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'content', 'tags') title = serializers.CharField(max_length=250) content = serializers.CharField(max_length=1000) tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all()) def create(self, validated_data): tags = validated_data.pop('tags') # [do i need to look for tags, create if not exists and retrieve the ids] post = Post.objects.create(**validated_data) for tg in tags: post.tags.add(tg) return post def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.content = validated_data.get('content', instance.content) tags = validated_data.pop('tags') # [do β¦ -
no variable value in django url when append data using jquery
I am getting json data and parsing using jquery. $.each(data, function(i, v) { var html = '<p class="is-marginless"><a href="{% url "phone" slug="' + v.slug + '" location="pakistan" %}">' + v.model + '</a></p>' $('#search').append(html); }); but i am getting this url when rendered http://localhost:8000/'%20+%20v.slug%20+%20'-price-in-pakistan/ I have tried so many varients but with no luck. I am not getting value from v.slug. -
Django admin custom view without model
Newbie django here wondering if there is a way to customize the django admin to show a customized view without using any models or serializers. My problem is that I would like to join 3 existing models and show them in the django admin. Let's say we have User, Transaction and Site where a user can have one or more transactions and a transaction belongs to one site. I would like to show for ex. all the information about the user and the number of days that have passed since the user hasn't made a transaction (which needs to be calculated - not part of the model) I cannot use inline since it only allows you to edit models on the same page as a parent model. Any other solutions? Is this feasible? -
How can I render multiple g11n documents via Django?
I am a Python developer familiar with writing long-form (multipage) documents with Sphinx. Not just exposing an API / docstrings, but other documents for non-technical readers. I render these as static HTML to be served by a webserver. I'm now creating a Django site that needs to render multiple documents as follows: user-specific navigation should appear, so dynamic rendering is required, not static HTML multiple documents will be available (for example, an end-user guide and a developer API) each document should be available in multiple languages One option is to simple create a Sphinx document repo for each document-language pair, and render each statically. But I'd prefer to render via Django (to add user navigation) and select the language dynamically with Django's language detection. Is this possible? -
how to connect the student id and name in django models by making the primary keys in student class and foreign keys in fee class
class Student(models.Model): Name=models.CharField(max_length=200) standard=models.PositiveIntegerField() Std_id=models.IntegerField() class Fee(models.Model): Id=models.ForeignKey(Student,related_name='std_id',on_delete=models.CASCADE) Name=models.CharField(max_length=200) -
Extend the Existing User Model with AbstractUser method error object 'User' has no attribute 'REQUIRED_FIELDS'
I'm trying to extend user but getting errors models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser class User(AbstractUser): fb_userid = models.CharField(max_length=256) objects =AbstractUser() views.py def fb_login(request): users = User.objects.filter(fb_userid=fb_user_id) Error: if not isinstance(cls.REQUIRED_FIELDS, (list, tuple)): AttributeError: type object 'User' has no attribute 'REQUIRED_FIELDS' -
Subdomain sometimes removed from sitemapsin django cms
I have a website built under django-cms. I have a sitemap located at www.domainname.com/sitemap.xml, and a site registered in the db with the domain name set to www.domainnamecom, and the verbose name set to www.domainname.com When I try to access the sitemap, most of the time, it lists the urls with the correct root url (i.e. with the subdomain) like so : <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://www.domainname.com/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://www.domainname.com/contact/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://www.domainname.com/methodology/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> </urlset> However half the time it's outputed without the subdomain, like so : <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://domainname.com/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://domainname.com/contact/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> <url> <loc>https://domainname.com/methodology/</loc> <lastmod>2018-09-11</lastmod> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> </urlset> The same thing happened with the current site displayed in the toolbar, sometimes it includes the subdomain, sometimes not. Note that initially, I had mistakenly named the site in the backoffice domainname.com, and edited afterwards. I'm cleary missing something here, and I have trouble knowing where to look since the behavior of the app seems inconsistent. Here's my urlConf : admin.autodiscover() urlpatterns = [ url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), url(r'^admin/', include(admin.site.urls)), # NOQA url(r'^', include('cms.urls')), url('', include('contact_form.urls', namespace="contact_form")) ] # This is only needed β¦ -
Django behind nginx proxy_pass: Set root url to other than localhost
I have a django rest app that runs in localhost in a server. It can be accessed from outside using nginx proxy_pass. It runs fine until I have a return value from a model that has a FileField. It returns the full url of the file: localhost:8000/static/a_file.file. It should be my server public IP address / domain to access the file, something like: my.domain.com/static/a_file.file. Can I set the base / root url returned from the model? Is my approach of running the app from proxy_pass is wrong? I've seen a lot of article recommend the use nginx as a proxy_pass in production server. -
Update the model objects after changing one of them
I have a model: class BroadcastingTable(models.Model): tv_programm = models.CharField(max_length=50, choices=tv_programm_list) brd_date = models.DateField() brd_start = models.CharField(max_length=12) brd_stop = models.CharField(max_length=12) brd_duration = models.CharField(max_length=12) brd_duration_day = models.CharField(max_length=12) brd_duration_mounth = models.CharField(max_length=12) my forms.py: class TableChoiseForm(forms.ModelForm): class Meta: model = BroadcastingTable and views: def index(request): broadcastingtable = BroadcastingTable.objects.all() return render(request, 'BroadcastingJournal/broadcastingPage.html', locals(),) def edit(request, pk): instance = get_object_or_404(BroadcastingTable, id=pk) edit_form = TableChoiseForm(request.POST or None, instance=instance) try: if edit_form.is_valid(): instance = edit_form.save(commit=False) instance.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: edit_form = TableChoiseForm(instance=instance) return render(request, 'BroadcastingTableChoise/choisePage.html', {"form": edit_form,}) except BroadcastingTable.DoesNotExist: return HttpResponseNotFound("<h2>ΠΠ°ΠΏΠΈΡΡ Π½Π΅ Π½Π°ΠΉΠ΄Π΅Π½Π°</h2>") In the form, the user enters the date, the start_time and the end_time every day, based on the start_time and end_time, the duration time for the month is calculated. Duration mounth time is the sum of the duration time of each day in a month. In viwes.py there is an "edit" function for changing data through a form. Sometimes it is necessary to change old entries for the previous days, but after changing one of the objects in the middle, there is no recalculation of the following objects and the broadcasting time for the month remains incorrect.How after changing the object to recalculate the duration month time for all next objects of the model? -
Django Form ImageField checkbox clear edit
I'm in a Django form and I want to modify the automatic checkbox that comes out in an ImageField field. The problem is the following: The box to clean the saved image appears on a higher line, and what I want is to appear next to the word Clean. Does anyone know how to modify this? I hope help, thank you very much for your time. -
Django Rest Framework model serializer: Set all fields to read only except one
The model that I'm using has a lot of fields. I want to be able to set all the fields to be read only except for one i.e. I want to allow only one particular field to be writable. Is there a shortcut to do this? I'm only aware of using "read_only_fields=('x','y') and I really don't want to type out all the fields especially if I'm going to make changes to the models later. "exclude =" also doesn't apply in this case. -
Django-allauth via email authentication not logging in
I'm using django-allauth for my web application authentication. I cannot seem to sign in successfully via email, not matter how many times I've tried with new emails and passwords. I've added the authenticated backend to my settings.py and configured the following: AUTHENICATICATIONS_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) # Authentication ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True If I switch ACCOUNT_AUTHENTICATION_METHOD = 'email' to 'username', then I am able to log in sucessfully which suggests the core authentication method is working, just not for email. Any thoughts? -
How to get behave-django to use couch database?
I'm fairly new to behave and django but trying to test an already developed project on django with Couchdb using the behave-django BDD integration. For background couchdb is being used to manage the views and data while django is managing users and authentication. CouchDB is running and works with django runserver and can see it using curl and through a web browser. How do I get behave-django to communicate with couchdb? Thanks -
Get username in Django Forms
I want to get username in my form. For example: username of current user is admin then in my form, the name part should fill with 'admin' automatically. What should I do? Here is my codes... views.py def attendanceView(request): if request.method=='POST': form = AttendanceForm(request.POST) if form.is_valid(): attendance = AttendanceModel() attendance.name = form.cleaned_data['name'] attendance.date = form.cleaned_data['date'] attendance.save() return redirect('home') else: form = AttendanceForm() return render(request, 'attendance.html', {'form': form}) models.py class AttendanceModel(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField(default=datetime.now) class Meta: unique_together = ('name', 'date',) forms.py class AttendanceForm(ModelForm): class Meta: model = AttendanceModel fields=('name', 'date') -
Amazon S3 - Failed to load resource: the server responded with a status of 403 (Forbidden) with Django
I'm using Amazon S3 with Django in ubuntu 16.04. First I got an error: The error is has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https:/ is therefore not allowed access. The response had HTTP status code 403. And then I did some research and added: <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> in the CORS configuration. But I still have a error: Failed to load resource: the server responded with a status of 403 (Forbidden) Any friend can help? Thanks!