Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django query: get objects where only 'time' is greater than HH:mm no matter what the date is?
I have a model called, MinutePrice, which has a DateTimeField as one of fields. What I want to do is making query of objects whose time is greater than 15:30, no matter what the date is. What I've tried: MinuetePrice.objects.filter(Q(date_time__lte="15:30")) Errors occured: ValidationError: ["'15:30' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] Any ideas to solve this? -
IntegrityError Primary Key Invalid in django
Something fixed in Order Class of model. and then, I run migrate. But, it is shown an error as django.db.utils.IntegrityError: The row in table 'core_order' with primary >key '4' has an invalid foreign key: core_order.billing_address_id contains a >value '1' that does not have a corresponding value in core_address.id. Models.py from django.conf import settings from django.db import models from django.db.models import Sum from django.shortcuts import reverse from django_countries.fields import CountryField # Create your models here. CATEGORY_CHOICES = ( ('SB', 'Shirts And Blouses'), ('TS', 'T-Shirts'), ('SK', 'Skirts'), ('HS', 'Hoodies&Sweatshirts') ) LABEL_CHOICES = ( ('S', 'sale'), ('N', 'new'), ('P', 'promotion') ) ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("core:product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" def get_total_item_price(self): return self.quantity * self.item.price def get_total_discount_item_price(self): return self.quantity * self.item.discount_price def get_amount_saved(self): return … -
Django rest serializer validation errors during update
I have a separate serializer for updating a user's account, and for some reason whenever I try to use an invalid input its not sending the validation errors as a response, its only sending back the original values that were set. Eg. old username is abc123, if I try to update it to abc123* i want it to throw an error saying its not a proper format but instead it just sends back abc123 as serializer.data. Anybody know why this is happening? serializer class UpdateAccountSerializer(serializers.ModelSerializer): username = serializers.CharField(max_length=16) full_name = serializers.CharField(max_length=50) class Meta: model = Account fields = ['username', 'full_name'] def validate_username(self, username): if Account.objects.filter(username=username).exists(): raise serializers.ValidationError(_("This username is taken.")) if not re.fullmatch(r'^[a-zA-Z0-9_]+$', username): raise serializers.ValidationError( _("Usernames must be alphanumeric, and can only include _ as special characters.")) return username def validate_full_name(self, full_name): if not re.fullmatch(r'^[a-zA-Z ]+$', full_name): raise serializers.ValidationError( _("Invalid name.")) return full_name def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.full_name = validated_data.get( 'full_name', instance.full_name) instance.save() return instance view class UpdateAccountView(APIView): def patch(self, request, pk, format=None): account = Account.objects.filter(id=pk) if account.exists(): account = account[0] if request.user == account: serializer = UpdateAccountSerializer( account, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer._errors, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_404_NOT_FOUND) If you're wondering … -
Is there such thing as a VideoField in Django?
So I have been making a site recently, and I want a way for people to upload videos and for me to display them, just like I do with an ImageField. However I have found that VideoField is not a thing. I have used FileField so far, and it is uploading to the right folder, however I don't know how to display that video like an ImageField. I want to use something specifically made for video files, but so far I have't found anything online about VideoFiles. Here is my model. class Post(models.Model): # ... other things here video_file = models.FileField(upload_to='post_files',blank=True,null=True) So my question is: is there a VideoFile in Django? -
If statement throws TemplateSyntaxError Invalid block tag on line 119: 'else', expected 'empty' or 'endfor'
I am trying to make a django app, but I am encountering the following error: Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 119: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have reviewed the code, and can not find any typos in my template file, but the template loads normally without the following lines: {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link">{{ i }}</a> </li> {% else %} <li class="page-item"> <a href="?page={{ i }}" class="page-link">{{ i }}</a> </li> {% endif %} {% endfor %} My entire code for the app is in this github repo in the listings folder: https://github.com/twheelertech/btre_project I have checked models.py and views.py in the listings app, but they seem to be formatted correctly. I am using windows 10, python 3.7.3, django 2.2.6 Thanks for the help. :) -
Take the current value of a variable (for the logged-in user) and save it to database
I would like to take the current value of a variable which is in a javascript in my templates.py, and save it to the database for the current logged-in user. Thanks -
Django slugs not unique wuth unique=True
I created two articles with the title "test" and this is what the second one generates as an error: duplicate key value violates unique constraint "xxx_content_slug_xxxx_uniq" DETAIL: Key (slug)=(test) already exists. Knowing that this is my model: class Content() id = models.AutoField(primary_key=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Content, self).save(*args, **kwargs) and knowing that I made the migration in the DB. I don't know how to solve that. Note: The problem is generated from the class post that inherits the content class and I don't think this information can help. -
Fastest way to implement commenting feature
I am implementing Instagram like commenting feature in my mobile application. The format of each comments at the user end looks like this: Hello @user1 and @user2 How are you today? Now there are 2 very interesting situations here: The server uses some regex pattern and extract the "user1" and "user2". When the user hits an API to view all such comments, the client side logic also parses each comment and extracts each "user1" and "user2" from the comment string. I don't think my solution or approach is scalable and would make the user experience quite laggy as there would be so much computations involved even though I use pagination to bring about 30 comments at once. Can someone give their opinions/knowledge as to what business logic should I use to make it fast and scalable? -
What framework to use for my mobile backend
I am creating a mobile application, similar to the snapchat app, and have already coded my frontend. I am not sure which framework to use for my rest api, which will serve as my backend. The choices are between NodeJs, Django and spring boot Which one would be the most efficient for this task. Thank you. -
jQuery parents() selector failing
I have an anchor, and I have attached an onClick callback to it, so once it is clicked, an AJAX request is fired which calls a view that deletes the image from the database. It should also remove <div class="image-preview"> altogether, too, however that is not happening for some reason. When I tested div removal code in JSFiddle, it works. The image is successfully getting removed from the database and delete_view is involved in the process. I have also tried to console.log from inside the success callback and I can see a debug message. console.log($(this).parents('.image-preview')); returns Object { length: 0, prevObject: Object(1) }, thus I think the selector is failing. What could be the reason? HTML: <div id="information"> <div class="image-previews"> <div class="image-preview"> <img src="/media/tmp/None/IMG_20190507_144128.jpg" width="80" height="54"> <p><a id="115" class="delete-temp-image-link">delete</a></p> <label><input type="radio" name="main" value="IMG_20190507_144128.jpg">main</label> </div> </div> <div id="div0"> <div>Name: IMG_20190507_144128.jpg</div> <div>Size: 3.03MB</div> <div>Type: image/jpeg</div> <div class="progressNumber">100%</div> </div> </div> jQuery: var $deleteClicked = function(event) { var url = Urls.deleteTempImage(event.target.id); $.ajax({ url: url, data: { 'id': event.target.id }, success: function (data) { console.log('spam'); $(this).parents('.image-preview').remove(); } }); } $(document).on('click', '.delete-temp-image-link', $deleteClicked); view: def delete_view(request, id): img = get_object_or_404(TemporaryImage, id=id) img.delete() return HttpResponse('successfull') -
Choice field in Django registration forms look inactive, but works
So the thing is that I added custom user model models.py class CustomUserModel(AbstractUser): pass Morasko = "Morasko" Piatkowo = "Piątkowo" district_choices = [ (Morasko, "Morasko"), (Piatkowo, "Piątkowo"), ] district = models.CharField(max_length=15, choices=district_choices, default=district_choices[0]) Field 'district' is supposed to be a choice field with two options. Here is custom registration form I am using. forms.py class NewUserForm(UserCreationForm): district = forms.ChoiceField(widget=forms.RadioSelect, choices=CustomUserModel.district_choices) class Meta(UserCreationForm): model = CustomUserModel fields = ('username', 'email', 'district', 'password1', 'password2') def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.district = self.cleaned_data['district'] if commit: user.save() return user My html registration file: register.html {% extends "map_neigh/home.html" %} {% block content %} <div class='container'> <div id='inner'> <br> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-primary" type="submit">Register</button> </form> <br> <br> If you already have an account <a href="/login"><strong>log in.</strong></a> </div> </div> {% endblock %} Choice field actually works - users are saved in DB with clicked district, but it looks inactive and I have no clue why. Clicking it doesn't change the appearance, if I hove over one of options pointer doesn't change neither. Below screenshot of the registration form. -
django spotify api python http post 500 error
Hello I am trying to make a django website using the spotify api, so I am trying to get some simple example code working using the spotipy python library, but keep getting a http post 500 whenever my spotipy code is called. Right now if you click a button on the website it makes a post request to one of my endpoints, which calls a python function and is supposed to return text. This is the code in the python function: import spotipy def spotifyleastplayed_py(request): print("spotifyleastplayed_py()") if request.method == 'POST': print("0") sp = spotipy.Spotify() print("1") results = sp.search(q='weezer', limit=20) print("2") print(results) data = "temp spotifyleastplayed_py() Return Data" return HttpResponse(data) #HttpResponse(json.dumps("{test:bobo}")) When the function is called, my console outputs the following error message: [06/Oct/2019 21:49:03] "GET /spotifyleastplayed HTTP/1.1" 200 1992 spotifyleastplayed_py() 0 1 [06/Oct/2019 21:49:07] "POST /spotifyleastplayed_py/ HTTP/1.1" 500 6326 Do I need to add the spotipy url to django somewhere so the library can make calls successfully? It seems like its failing to make the http request to spotipy. -
Django: want to loop through _set for pk values only
I'm stuck trying to figure out how to filter my template values with the detail view PK. I have a detail view for my employee. I wish to display my employee's subjects, where I then wish to filter the subjects with the evaluations that have been made for the subject. I've gotten so far that I can show my subject names, and show all the evaluations for each subject. However, I don't want to show ALL of them I only want to show the ones that exist for the current employee (detailView PK). As you can see in my template, I'm using _set to make the relation, but I have no clue on how to filter the PK into that equation. Example, what I want: Subject 1: Evaluationname - employee Johnny Evaluationname - employee Johnny Example, what I currently have: Subject 1: Evaluationname - employee Johnny Evaluationname - employee Chris I don't want Chris's evaluation, I only wish to filter the primary key, so in this case Johnny's evaluations. Template {% for subject in subject_list %} <a href="">{{ subject.subejctname }}</a> {% for evaluation in subject.evaluation_set.all %} <div> <p>{{ evaluering.ma }} | {{ evaluering.ma.firstname }} | {{ evaluering.ma.lastname }}</p> </div> {% … -
Recommended C-panel for hosting django web application
So my goal is to run django app(WSGI) on C-panel, my traffic would be 100-200 persons max per day ,I have found a website https://ifastnet.com but I'm not quite sure, what would you recommend? -
Unable to convert bytes stream into image django views
this is a new question as i didn't received any answer to my old one, i have made some tests after some recommendations I am actually struggling on converting a bytes received from LDAP for the thumbnail picture of the user and saving it into the profile model, This is the code that i have actually xuser = CustomUser.objects.filter(id=request.user.id).first() user = xuser.last_name def save_avatar(user, thumbnail): profile=UserProfile.objects.create(user=user) buffer = io.BytesIO() buffer.write(thumbnail) image_file = InMemoryUploadedFile(buffer, None, 'test.png', 'image/png', buffer.getbuffer().nbytes, None) profile.image.save('image', image_file) try: thumbnail = result[0][1]['thumbnailPhoto'][0] save_avatar(user, thumbnail) print('* %s: %d' % (xuser.username, len(thumbnail))) except Exception as e: print(' %s: error: %s' % (xuser.username, str(e))) With this am able to store the image but i have as name only 'image' without the extension i don't know what i have to do next, and if this code should give me something back, if this will help this the format that i have after retrieving the value of the thumbnail attribute: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\' ",#\x1c\x1c(7),01444\x1f\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x00`\x00`\x03\x01!\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1c\x00\x00\x01\x04\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01\x03\x06\x07\x00\x04\x05\x08\xff\xc4\x00:\x10\x00\x01\x03\x03\x02\x03\x05\x06\x04\x03\t\x00\x00\x00\x00\x00\x01\x00\x02\x03\x04\x05\x11\x06!\x121a\x07\x14AQq\x13"2\x81\xa1\xc1#BR\x91\x15$r5C\x82\xa2\xb1\xb2\xc2\xd1\xe1\xff\xc4\x00\x19\x01\x00\x02\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x05\x04\xff\xc4\x00\x1d\x11\x01\x01\x01\x00\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x11!\x12"1\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xb3\x02 \x10\x04\x02\\&E\xc2\xcc 3\t0\x80B\x85\x00$ !\x00\xe0\x08\xc0H\xca\x02,&LP\xbb\xd6\xbem1\x11Y-\xf2\\\xe4$\x83)\xcb"\x1e\x87\x9b\xbdF\xddTu\xb9\x99\xedO\x18\xbb\xbeCt\x1a\xf2\xae9\xf8/\xd6gQ\xc3\x8c\x9a\x9aw\x99X\xde\xaen2\x07Q\x9c)\xa43ES\x04s\xc1#%\x86F\x871\xec9\x0e\x07\x91\x05,o;\x9e\xc1\xbe=b\xf9DP\xa9\xa0\x12\x84\x84\x19\xc0\x11\x00\x90\x10\x08\xb0\x99!z\xf6\xe9$r[\xec\xac\xda*\xde9*\x1c\x0e\t\x8d\x98\xf7=\x1cy\xf4\x18\xf1Z\xf6\xc0\xc7G\x82\xdc\x11\xcb\x03\x92\xcf\xed_w#C\xa9\x9f1i\xcb\x88\x02"Z\xd3\x9f4\xc6\x85\xac}%\xe2\xba\xccO\xf2\xcfgz\xa6g\x83\x0eq#GL\x90q\xea\x8e\xad\xf3~\x1fk>\xe3\xd4\xf0\xa1!h3\x82P\x90\x80p\x04a \x12\xa6\x15\xce\xb9"MM\x03\xa2s^\xf8h\xdc\xc2?C\x8b\xb3\xbf\xa8!E(\xefwjz\xa6\x96T\xcb;G\xc6\xce\xee\x18\xdf\x91\xe6\xb8y|\xbb\xad\x0e\x19\xa9\x88\xdd\xd4\xb5u\xf3U63%S kZ\xe3\xdd\xcf\tv|\x13\xbab\xa9\xb6\xfb\xc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q\xf7\xa2<M\xfe\x93\xff\x00G\xfdU=\x89\xee\x17p_6\x91\xf1\x90@U\xe5\xfa\xaf\xbd\xdd\xe7~r\xd6\x1e\x00}?\xf7+\x9f\xad?\xabWv/\xf3\xe3\x96P\xb8\xec\xbb\x9c`\xe2\xdf*\xe9\xecr\xf6\xea\x9bMe\x9eW\x12\xeaG\tb\xcf\xe8q\xdc|\x9d\xbf\xf8\x928\xb5f\x98S\xc1$\xee\xf8bay\xf4\x03?e\xe4\xea\xaa\x87\xd5\xd4\xcbS!\xcb\xe6{\xa4q\xea\xe3\x9f\xbad\xd6;\x10\x8c\x14\x02\xe7e\xb9j\xac\xee7(f\xce\x1a\x1d\x87\x7fI\xe6\x96\xe7\xb9\xb0\xf3|\xb2\xa6\xd7*\xf6\xd1\xdb$\xa8\x0e\x04\xb5\x98oW\x1eJ\xba.$\xe4\x9c\x9f5\xcf\xd6\x9eKW\xf6/\xd9\x02J\x07\xbbb\xba\x1c\xe1iS\x8e\xca\xae]\xc7[S\xc2\xe3\x86VF\xf8\x0f\xae8\x9b\xf5o\xd5\x06\xbf\xae\xbb\xd9\xab\xc7\x9d4\xbf\xec+\xca \xfb\xad\xf4\t\x90\x1epr\x94 \x0b)\t@oT\xdd%\xaa\xb5\xc1L\xec\xfe\x13\x8f\x11\xf3\x1e\x0b\x9e\xa3\x9c\xfeg\x89k_\xab\xe8JnC\xb2h\xb1\xab\xa1e\xac4\x17\xcb}Xw\x0f\xb0\xa9\x8eL\xf9\x00\xe1\x9f\xa2\r\xff\xd9' i really need some help with this if anyone have a suggestion or something from what i can start i will be really grateful -
why my "def __str__(self)" function isn't working in django
from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) ***def __str__(self): return self.title***[(InteractiveConsole)[1] when i enter Article.objects.all() this line, after that it should show titles i have in my database. But why it's just showing ? although I have written def __str__(self): properly. -
how to configure redirect in DeleteView
when i try to delete some comment it first take me to the comment_delete_confirm.html, then redirect to the page what linked in success_url = '/blog/'. Problem become when i change success_url to something like 'post-detail' (becose i want after comment_delete_confirm return to the post), it cannot find this page, becose in the brauser url it looks like that: '127.0.0.1:8000/blog/post/18/comment_delete/post-detail' this is my views.py and urls.py files: class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment success_url = 'post-detail' # only the author can delete his post # if not author try to delete post it gives 403 forbidden def test_func(self): comment = self.get_object() if self.request.user == comment.user: return True return False urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('post/<int:pk>/comment/', add_comment, name='comment-create'), path('post/<int:pk>/comment_update/', comment_update, name='comment-update'), path('post/<int:pk>/comment_delete/', CommentDeleteView.as_view(), name='comment-delete') ] -
Nginx + Django serve static files to local location
I have a Django app and I want to set the path of static files, to a local path, for example: c:/static/test The Nginx settings for the location is something like: server { listen 80; server_name sitename or ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/blah/blah_blah; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } is it ok to replace root /home/blah/blah_blah; with c:/static/test? To make it clear, I have a website that I want to upload big files to a local server (local path in the user's PC). Thanks -
What is an equivalent Django's save function in Symfony?
What is an equivalent Python's save function in Symfony models?. Django def save(self, *args, **kwargs) self.slug_field = slugify(instance.username) What would it look in Symfony? -
Transpose data from model objects for django-datatables-view
I have data in the following (simplified) format: MetricData(models.Model) with following fields: id, metric, date, facility, value Now I want to create a table with the following format (execute the script to get the indented output table): <table style="width:100%"> <tr> <th>Date</th> <th>Facility 1</th> <th>Facility 2</th> <th>Facility 3</th> </tr> <tr> <td>03/2019</td> <td>1.0</td> <td>1.5</td> <td>2.5</td> </tr> <tr> <td>04/2019</td> <td>1.5</td> <td>1.5</td> <td>2.0</td> </tr> </table> As you can see, the number of facilities which is dynamic (new ones can be added to the database), are the column headers. For each facility there will be metric data in the database. All examples from django-datatables-view I find are basically using models directly and one model entry is converted to one table row. -
Django - Multiple dependent form
I have extended the Django User model creating a 1-to-1 dependency with the class Profile. There will be many profiles playing in the same Community. And a Profile can be playing in different Communities at the same time. I did this with a Many-to-Many field "members" in the Community Model. This is shown below. (I have reduced the irrelevant code) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Extend Users Here class Community(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=50) members = models.ManyToManyField(Profile, through='Membership') def get_members(self): return "\n".join([str(m) for m in self.members.all()]) class Membership(models.Model): community = models.ForeignKey(Community, on_delete=models.CASCADE) player = models.ForeignKey(Profile, on_delete=models.CASCADE) When a new profile is created I would like it to be inmediately associated with a Community. Therefore, in the user registration form I would like to ask him if he wants to join an existing community or create a new one. I believe I need something as "Multiple Form" but I would appreciate help in what exactly do I need and how I can look for information about it. Thanks! -
Import another javascript module in django admin custom javascript file
I have created a separate JavaScript file to wrap common Ajax code (jQuery) and import it in other JavaScript files. But it gives the error SyntaxError: import declarations may only appear at top level of a module. My code as follows. Two files are in the same directory. ajax_call.js function make_ajax_request(requestUrl, requestData, callback_function) { $.ajax({ type: 'GET', url: requestUrl, data: requestData, success: function(response) { try { var jData = JSON.parse(response); if (jData['status'] == 'success') { callback_function(jData); } else { console.log(jData['error']); } } catch (error) { console.log('Parse error in response.') } } }); } change.js import { make_ajax_request } from './ajax_call.js' var $ = django.jQuery; $(document).ready(function() { //code to call the function } admin.py class Media: js = ('admin/js/jquery.init.js', 'js/admin/ajax_call.js', 'js/admin/change.js',) -
Python django authenticate delete
I'm having some problems with the delete method on my project. When I run on postman link to delete the post, it's deleting it, so it works, but I want to make it only if user is_staff to delete this post. This is the code. from django.db import models from django.utils.text import Truncator from django.contrib.auth.models import User from threads.models import Thread class Post(models.Model): """ Model to represent the post in a thread """ content = models.TextField() thread = models.ForeignKey( Thread, on_delete=models.CASCADE, related_name='posts' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts' ) class Meta: ordering = ['created_at'] def __str__(self): truncated_content = Truncator(self.content) return truncated_content.chars(30) -
python django django.shortcuts render is searching for html in wrong directory
For me django.shortcuts render is searching for html in wrong directory: C:\Users\benra\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\admin\templates\blog\home.html but it should be searching for it where the project is C:\Users\benra\django_project\blog\templates\blog how do I fix this? from django.shortcuts import render def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') -
How can solve this : Django pyinstaller wont start app exe
i have install python v 3.4 and django 1.8 , pyinstaller 3.5, i try convert django app to app.exe for windows. pyinstaller --name=mysite mysite/manage.py All ok. ./dist/mysite/mysite.exe runserver localhost:8000 server start ok, but wont start app.exe window. any solution?