Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login and logout not functioning as required
I have a custom user in Django and when I logout the user can still see the main page by going to the url. I do not know which part is incorrect as I am using decorators already. I ave two apps, main and home. this is my urls.py: urlpatterns = [ #Has to be included for Forgot Password funcitonality on main page path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('',views.main_page,name='main_page'), #path('profile/logout', views.user_logout, name='logout'), path('',include('main.urls'),name='main'), url(r'^home/',include(('home.urls','home'), namespace='home')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is my main/views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(request, username=username, password=password) if user is not None: return redirect('home:home') else: messages.error(request,'Sorry, the username or password you entered is not valid please try again.') return HttpResponseRedirect('/') else: form=AuthenticationForm() return render(request, 'main/user_login.html', {"form":form}) And my logout view in main/views.py @login_required def user_logout(request): logout(request) return HttpResponseRedirect('main/user_login.html') This is my home/views.py @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] My home/urls.py path('',views.PostListView.as_view(), name='home'), I am also facing an issue that I have to click the login button twice otherwise it … -
Inability to Toggle a Sidebar Using JS
I've all my CSS and Javascript inside my HTML file on Django which looks as follows: <!doctype html> <html lang="en"> <head> <title>Dashboard</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script> function toggleSidebar(){ document.getElementsByClassName("sidebar"); } </script> <style type="text/css"> .toggle-btn { position:absolute; left:180px; top:70px } .toggle-btn span { display:block; width:30px; height:5px; background:#000000; margin: 5px 0px; } .sidebar { height:100%; width:160px; position: fixed; z-index:1; top:0; let:0; background-color:#111; overflow-x: hidden; padding-top:70px; } .sidebar.active { left:0px } .sidebar a { padding:6px 8px 6px 16px; text-decoration: none; font-size:18px; color: #818181; display:block; } .sidebar a:hover { color:#ffffff; } </style> </head> <body> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class="toggle-btn"> <span></span> <span></span> <span></span> </div> <div class="sidebar"> <a href="/categories">Categories</a> <a href="#">Test 1</a> <a href="#">Test 2</a> <a href="#">Test 3</a> <a href="#">Test 4</a> </div> </body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="#">Home.com</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item … -
Why does my django view function never return even though all code executes?
Ok this is a long shot but I am hoping someone, somewhere has experienced this. When executing a django query that requires a long list of ids to be used, my backend function never returns. I have to cast these ids as a list because I'm using ids from one database to get at data in another. The ENTIRETY of my function executes, including a print statement right before it's supposed to return but IT NEVER RETURNS. And it grinds my local environment to a halt. I cannot make any other requests or load any other pages while it's spinning. Even if I simplify the code so that I'm only returning a string saying 'returning' the return part of my function never fires. Here is some sample code, and just know that this crashes out on me (i.e. never returns if the list of ids is longer than, say 6,000). @action(detail=False, methods=['post',]) def view_function(request): profiles = Profile.objects.filter(some_filter).values_list('id', flat=True) print('i got the profiles') the_data_i_need = Profile.objects.using('different_db').filter(profile_id__in=list(profiles)) print('i got the data i need') print('returning') return response.Response({ 'success': 'success!' }) For a small queryset (less than 6000), this executes flawlessly. In the case of a large queryset (over ~6000) ALL of my print … -
Django model update based on json url request and unique values
I made a method to request a json from a url, get some values from and after this populate my objectidServer field from my ImagemServer() Django model. The main purpose is to populate new fields every time this json update. So for example: If someone for any reason delete a a value from this the field the method will request and populate the field again, based on the objectidServer value (if the same value exists do nothing, if not, create). Same to get new values and populate new fields every json update. models.py class ImagemServer(models.Model): objectidServer = models.CharField(max_length=255, null=True, blank=True) views.py def GIS(request): response = requests.get('url') geodata = response.json() id_obj = [(data['attributes']['OBJECTID']) for data in geodata['features']] try: for lista in id_obj: ImagemServer.objects.get(objectidServer=lista) return HttpResponse('OK') except ImagemServer.DoesNotExist: for lista2 in id_obj: imagemServer_list = ImagemServer() obj = ImagemServer(objectidServer=lista2) #print(lista2) #print(imagemServer_list.objectidServer) if imagemServer_list.objectidServer != lista2: for lista3 in id_obj: print(lista3) obj = None obj = ImagemServer() obj.objectidServer = lista3 obj.save() return HttpResponse("UPDATED") else: return HttpResponse("OK") The script works well and I can populate all the fields, but I got a problem when I delete any field: when I request the json again the method not check if values exists and populate everything again, … -
Django | Create table raw query execution with query param
Can please somebody tell me whats wrong about my Syntax? I try since 2 days to get a decent answer on this matter, but wether people just give me minus points or refer me to to the Django docs I already read https://docs.djangoproject.com/en/3.0/topics/db/sql/ tablename = '2020-10-table' v_col = ["userID int(11)", "TID varchar(128)", "CID varchar(128)", "SID varchar(255)", "Timestamp bigint(20)", "LX int(10)", "LocY int(10)", "Width int(10)", "Height int(10)", "Tag varchar(512)"] connection.execute("""CREATE TABLE IF NOT EXISTS `%s` %s""", [tablename, '( '+str(', '.join(v_col))+' )']) I keep receiving this: MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''( userID int(11), TI ...... Can anyone please point out my issue? -
How can do django framework to back-end and react js to front-end
based application using django framework for back-end and I like to code react js for front-end is it possible? -
Why is my database table empty after Heroku deployment?
I have a django app that runs perfectly well on my local server. Unfortunately, when I deploy it onto Heroku, the behaviour doesn't work as expected. I can see that it's a database related issue as my dropdowns which are supposed to load a list of values from my database are empty on production. I have checked on Heroku in the 'Ressources' section of my application and there is a database; it also contains all my project tables (django default tables + my main table). All the django default tables are properly populated (I compared them with my local postgres tables and it matched). Unfortunately, my main table is empty on Heroku, whereas it is populated as expected locally. I really don't understand what has gone wrong, especially considering that the table itself has been recognized, yet it is empty. I've applied the command 'heroku run python manage.py migrate' but it didn't fix the issue. Has anyone faced a similar issue? Not sure if the code would help here, but if you need some specific bits, please let me know. Thanks! -
Best practice to pass attribute from ModelForm.clean() to Model.save()
class MyModel(models.Model): def save(self, *args, **kwargs): super().save(*args, **kwargs) if getattr(self, 'my_attr', False): # do things class MyForm(forms.ModelForm): def clean(self) cleaned_data = super().clean() if self.has_changed(): self.instance.my_attr = self.get_the_needed_info() return cleaned_data class Meta: model = MyModel fields ='__all__' @admin.register(MyModel) class MyAdmin(admin.ModelAdmin) form = MyForm During MyModel.save(), I need to check for a condition that is evaluated in ModelForm.clean(). During clean(), I assign the attribute my_attr to self.instance. It is working it seems to be thread-safe (within an atomic transaction). Is there any reason I miss, that urges a refactoring? -
how to trigger push notification for specific endpoint? in fcm_django lib
I used fcm_django and want to push notification on specific endpoint to be trigged I already test it from python shell all works, but how to add it to my endpoint? wanna see best practice! if I use this one it will pushed notifications? Thanks for your time! @action(detail=True, methods=['post']) def add_server(self, request, pk=None): booking = self.get_object() booking.add_server(request.user) device = FCMDevice() device.send_message() return Response("Server added") -
Django 403 Forbidden CSRF
recently I am seeing a weird error in my Django application. When I try to sign in, Chrome is stuck on "Processing request". After I click on the login button again it gives me the 403 Forbidden CSRF verification failed error. However, when I click on the Back button and press login again with the same user credentials it logs in successfully. I do not know why this is happening. I have two Django applications which 'home' and 'main', after correct credentials it should take the user to the view of 'home' applications. My main/user_login.html <form method="POST" action="{%url 'main:user_login' %}" class="form-signin"> {% csrf_token %} <div class="form-label-group"> <input type="text" name="username" id="inputText" class="form-control" placeholder="Username" required autofocus> <br/> </div> <div class="form-label-group"> <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required> </div> <div class="custom-control custom-checkbox mb-3"> <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Remember password</label> </div> <input type="submit" class="form-control" name="" value="Login"> <hr class="my-4"> <p>Don't have account? <a href="{% url 'main:signup' %}" id="signup">Sign up here</a></p> {% if message %}<p style="color: red;">{{ message }}</p>{% endif %} <a href="{% url 'password_reset' %}" id="signup">Forgot Password</a> </form> my main/views.py: def user_login(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if … -
Django Rest Framework - Search Filter, how to use Method Decorator with Login Required?
I have a Django API for search filters, it is not providing search results per user. How can I make work with @method_decorator and login_required ? class LargeResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 10000 class EntitySearchList(generics.ListAPIView): model = Entity serializer_class = EntitySearchFilterSerializer queryset = Entity.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['description', ] pagination_class = LargeResultsSetPagination -
How to call an API from flutter
Every time i call the end point I get an error message. Values Represented are Static for this example but later on these will be replaced by real values, the Goal is to retrieve the values on the database through the Api. the Values, order and entries have be checked for spelling errors. Any insight would be appreciated. class Search { final int id; final String location; final int employer; final String service; final int position; final String userId; Search({this.id, this.location, this.employer, this.service, this.position, this.userId}); factory Search.fromJson(Map<String, dynamic> json) { return Search( id: json['id'], employer: json['employer'], location: json['location'], service: json['service'], position: json['position'], ); } Map<String, String> headers = { 'content-type': 'application/json', 'accept': 'application/json', 'authorization': 'ztNMKpkGM4USORPl45HGEl8EMyh1' }; Map toMap() { var map = new Map<String, dynamic>(); map["employer"] = employer; map["location"] = location; map["service"] = service; map["postion"] = position; return map; } } Future<Search> createSearch( int employer, String location, String service, int position) async { final http.Response response = await http.post( 'http://m-waks/employer/asefsdgcsjdsxxx/search-employees/', headers: { HttpHeaders.authorizationHeader: 'ztNMKpkGM4USORPl45HGEl8EMyh1','Content-Type': 'application/json', 'Accept': 'application/json' }, body: jsonEncode(<String, dynamic>{ 'employer': employer, 'location': location, 'service': service, 'position': position })); if (response.statusCode < 200 || response.statusCode > 400 || json == null) { throw new Exception("Error while fetching data"); } … -
django form autocomplete show data
models.py class Place(CoreModel): name = models.CharField(max_length=255, ) parent = models.ForeignKey('self', null=True, on_delete=models.CASCADE, default=None) place_type = models.CharField(max_length=255, choices=PLACE_TYPES, default=CITY_OR_VILLAGE) objects = PlacesManager() class Meta: unique_together = ('name', 'parent') def __str__(self): return self.name forms.py class PlaceForm(forms.Form): place_from = forms.ModelChoiceField(queryset=Place.objects.cities_villages(), widget=autocomplete.ModelSelect2( url='place-autocomplete', attrs={'data-minimum-input-length': 3, } ), required=False, ) place_to = forms.ModelChoiceField(queryset=Place.objects.cities_villages(), widget=autocomplete.ModelSelect2( url='place-autocomplete', attrs={'data-minimum-input-length': 3, } ), required=False, ) trip_type = forms.CharField(label='Chose trip type', widget=forms.Select(choices=TRIP_TYPES), required=False, ) As you can see in the picture, we have autocomplete with the same name. I would like the form to display the name and parent, how can I do this? -
Django admin site shows Blog object(1) instead of what I typed in
Python version: 3.8.2 Django version: 3.0.4 Here is my model: from django.db import models class Blog(models.Model): """Something the user wants to talk about""" text = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True) def _str_(self): """Return a string representation of the model.""" return self.text But, in the admin site, it shows me this. (I can't embed images yet...) So, I open Command Prompt, and open the manage.py shell. Then, I type in: from blog_bots.models import Blog Blog.objects.all() and it gives me <QuerySet [<Blog: Blog object (1)>, <Blog: Blog object (2)>]>. But when I do Blog.objects.get(id=1).text, it gives me "Django4Life", which is the test that I did and it is what Blog object(1) is. However, I want it to say what I typed in on the admin site (Django4Life), not Blog object(1). -
ValueError at /post/new/ Cannot assign "<SimpleLazyObject:<User: chetan>>": "Post.author" must be a "User" instance
I keep getting this error "ValueError at /post/new/ Cannot assign ">": "Post.author" must be a "User" instance." class User(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) def __str__(self): return self.user.username class Post(models.Model): author = models.ForeignKey('User.User',related_name="posts",on_delete = models.CASCADE) text = models.TextField() created_at = models.DateTimeField(default = timezone.now) updated_at = models.DateTimeField(blank = True,null =True) def update(self): updated_at = timezone.now() self.save() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class CreatePostView(LoginRequiredMixin, CreateView): # form_class = forms.PostForm fields = ['text',] model = Post def form_valid(self, form): self.object = form.save(commit=False) form.instance.author = self.request.user self.object.save() return super().form_valid(form) Please help! -
How to get all fields of tables related through a foreign key as well as a many to many relationship in django ORM?
I have a table User_Device with fields username, num_of_years and device (foreign key), table Device with fields id, name, type and many to many relationship on field property, which is the third table Property that has fields id, name, location. I know how to get all the fields from the first 2 tables: User_Device.objects.select_related('device').all() I also know how to get all the fields of the many to many table: Device.property.through.objects.all() or filter using: Device.property.through.objects.filter(property=12) which gives me all the fields of the many to many table alone, which looks like Device_Property with fields device_id, property_id I have 2 questions: How do I get all fields of the Device table and the property table like the SQL query would give when you inner join it like: select d.*,p.* from device_property dp inner join property p on dp.property_id=p.id inner join device d on dp.device_id=d.id How to inner join all the three tables and get all fields like the result of the query: select ud.*,d.*,p.* from user_device ud inner join device_property dp on ud.device_id = dp.device_id inner join property p on dp.property_id=p.id inner join device d on dp.device_id=d.id In conclusion table A has a foreign key field on table B and table B … -
How to Upload and display the image by using model form in django?
I've been trying to upload and display the image but it doesn't show the image. In models.py class upload(models.Model): Comments = models.CharField(max_length=200) img = models.ImageField(upload_to='images/',blank=True) forms.py class upl(ModelForm): class Meta: model= upload fields= ['Comments','img'] views.py def home(request): form=upl() if request.method=='POST': form = upl(request.POST, request.FILES) if form.is_valid(): Comments = form.cleaned_data['Comments'] img = form.cleaned_data['img'] p=upload(Comments=Comments,img=img) p.save() return render(request,'home.html',{'form':form,'up':upload.objects.all(), }) in template <form method="POST"> {% csrf_token %} {{form.as_p}} <br> <BUTTON TYPE ="SUBMIT">Submit</BUTTON><br> <br> </form> {%for i in up %} {{i.Comments}} <img src ="{{i.img}}", alt=""> {%endfor%} so this is showing comments but not image. I don't know why the image is not showing. PLEASE HELP ME OUT -
Django - How to leave ImageField blank if user doesn't upload image
I'm trying to build a recipe app that allows users to upload images and save recipes in a list. The problem I'm facing is when the user doesn't upload an image, I get error: attribute has no file associated with it. Error I've looked in Django documentation & tried using default tag in my HTML template with no success. The value is named image_ingredients in models.py How could I make it so the user can just leave the ImageField empty? Here is my code: models.py # Recipe Field class Recipe(models.Model): title = models.CharField(max_length=200) # TODO: Add default image if image is left blank image = models.ImageField(upload_to='recipes/images/', blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,) daily_meals = ['Breakfast', 'Brunch', 'Elevenses', 'Lunch', 'Tea', 'Supper', 'Dinner'] meal = models.ForeignKey(Meal, limit_choices_to={'name__in': daily_meals}, on_delete=models.CASCADE,) image_ingredients = models.ImageField(upload_to='recipes/images/', null=True, blank=True) ingredients = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py # Solo recipe with instructions def solo(request, recipe_id): recipe = get_object_or_404(Recipe, pk=recipe_id) return render(request, 'recipes/solo.html', {'recipe':recipe}) solo.html <h4>Ingredients</h4> <img src="{{ recipe.image_ingredients.url }}"> <p>{{ recipe.ingredients }}</p> -
toggle-btn won't show up next to sidebar
First of all I'm using Django, and I've my CSS inside of my HTML file. Here's what my situation looks like as of right now: I've finished setting a sidebar for the dashboard, aka the members area, and I want to offer users the option to show or hide the latter, just like most popular website nowadays do, including Youtube. I've the following code in the body: <div class="toggle-btn"> <span></span> <span></span> <span></span> </div> And the following one in the head <style type="text/css"> .toggle-btn { position:absolute; left:230px; top:20px; } .toggle-btn span { display:block; width:30px; heigh:5px; background:#151719; margin: 5px 0px; } </style> It is indeed supposed to look just like this , but nothing shows up next to the sidebar. If someone could point out what I might have done wrong, or missed doing, I would super appreciate it. -
Django URL regex between various exact string matches
Django (v2.2) I'm trying to achieve a route which consists of three possibilities all, gs and webservice to do a filter in a table on the page. path(r'^(?P<mode>all|gs|webservice)$', get_orders, name='dash.orders_mode'), path('(?P<mode>/^all$|^gs$|^webservice)/$', get_orders, name='dash.orders_mode'), both ways don't seem to work It's because there are ids on the route aswell. -
How to delete from the form the currency choice in MoneyField
Goodmorning Guys, I'm new in django and I want to ask you the following question. I have in models.py two class: class Single_Income(models.Model): income_label = models.CharField(max_length=100, editable=True) income_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) income_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) class Total_Income(models.Model): total_jan = MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) total_feb= MoneyField(decimal_places=2,default=0, default_currency='EUR',max_digits=11) In views I have the following code: def ricavi_dalle_vendite(request): items = Single_Income.objects.all() if request.method == 'POST': form = SingleIncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = SingleIncomeModelForm() context= { "form": form, 'items': items, } return render(request, "app/income.html", context) So completing the form in the web_application (url "app/income.html") it's possible to fill the Single_Income. Now I want to fill automatically the Total_Income model (after the saving of Single_Income model data) in this way: Single_Income: |____Jan____|___Fab_____| |____100___|_____100____| |____100____|____100____| Total_Income: |____200____|____200____| -
Publishing video to youtube from a django app
I have a Django app which shows youtube videos. Now the user can click share and post the video to FB. Once the video is posted, the user should be able to click on the video and play it within FB page. This functionality is very similar when we add a youtube link in gmail and the receiver upon clicking gets a popup window which plays the video. How can I achieve this? Thanks in advance for your answers. -
How to add a default array of values to ArrayField?
Is it possible to add a default value to ArrayField? I tried to do this for email field, but this did not work: from notifications import constants from django.contrib.postgres.fields import ArrayField class NotificationSetting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='notification_setting') telegram = ArrayField(models.CharField( choices= constants.NOTIFICATION_SOURCE, max_length=30 ), default=list) email = ArrayField(models.CharField( choices= constants.NOTIFICATION_SOURCE, max_length=16 ), default=list(dict(constants.NOTIFICATION_SOURCE).keys())) class Meta: db_table = 'notification_settings' def __str__(self): return f'Notification setting for user {self.user}' And override the save method of the model would be bad practice, I think. -
Django celery beat - can't compare offset-naive and offset-aware datetimes
Im using celery and celery beat to create some tasks, ive added a couple to the DB and when I try and run the below celery -A my app beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler I get the error: 2020-03-20 17:49:03,938: INFO/MainProcess] Writing entries... [2020-03-20 17:49:03,941: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("can't compare offset-naive and offset-aware datetimes") Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/apps/beat.py", line 109, in start_scheduler service.start() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 631, in start interval = self.scheduler.tick() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 329, in tick self.populate_heap() File "/usr/local/lib/python3.7/site-packages/celery/beat.py", line 303, in populate_heap is_due, next_call_delay = entry.is_due() File "/usr/local/lib/python3.7/site-packages/django_celery_beat/schedulers.py", line 116, in is_due if now < self.model.start_time: TypeError: can't compare offset-naive and offset-aware datetimes looking online it looks as this may be related to timezone settings in my settings file which ive set to, but it hasn't resolved the issues CELERY_TIMEZONE = 'Europe/London' CELERY_ENABLE_UTC = True TIME_ZONE = 'Europe/London' USE_TZ = True versions: celery==4.4.2 django-celery-beat==2.0.0 any ideas? Thanks -
How to edit tags in post using taggit
Good afternoon. I started learning django and met a problem that I can’t solve. I want to edit tags in a post created using taggit, but I don’t understand how to do it Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) tags = TaggableManager(through=RuTaggedItem, blank=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text', 'tags') Views.py class EditPostView(View): def get(self, request, pk=None): edit_post = Post.objects.filter(id=pk) form = PostForm(edit_post.values()[0]) return render(request, 'blog/post_edit.html', {'form': form}) def post(self, request, pk=None): form = PostForm(request.POST) if form.is_valid(): post = Post.objects.get(id=pk) # for tag in request.POST.get('tags'): # f.tags.add(tag) if form.has_changed(): for i in form.changed_data: if (form.data[i] != '') and (form.data[i] != None): post.i = form.data[i] post.__setattr__(i, form.data[i]) post.save() return redirect('post_detail', pk=pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form})