Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set filters in Django template
I have a custom template tag which verifies the user's group but when I use it as a template filter in an HTML template it is bugging out all over the place. This is my custom template tag: @register.filter(name='is_in_group') def is_in_group(user, group_name): group = Group.objects.get(name=group_name) return True if group in user.groups.all() else False This is the first filter in the template - which is letting every user through: {% if request.user|is_in_group:"food bev supervisor" or "casino supervisor" or "security supervisor" or "cage supervisor" %} But if I change the ordering to: {% if request.user|is_in_group:"casino supervisor" or "food bev supervisor" or "security supervisor" or "cage supervisor" %} ... the code fails. If I set only one group as such: {% if request.user|is_in_group:"food bev supervisor" %} then the filter works correctly (but I cannot set more than one group). Is this a bug in Django? What is the best way around this? -
Django Getting Data From Foreign Key
Im a newbie working on a news site (or at least trying to, a lot of "problems" in the last few days lol ) trying to learn Django the best I can. This is what I want to do : I have an Article Model, it used to have 6 image fields that I used to send to the template and render the images, each image field had its own name and all was well in the world. Then I got tasked with puting the Article images in a separate Image model. So I did this : class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") def __str__(self): return self.title class ArticleImages(models.Model): article = models.ForeignKey(Article, on_delete="models.CASCADE", related_name="image") image = models.ImageField("image") name = models.CharField(max_length=50, blank=True) But so far I wasnt able to access my images in my template using {{ article.image.url }} or {{ article.image.image.url }} or any other combination. Why is that ? Did I set up my models correctly ? One person suggested that I should change the model … -
AttributeError at /admin/student/student_record/
I updated my django model, for my student app, it now looks like this from django.db import models class Student_Record(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) address = models.CharField(max_length=500) gpa = models.FloatField() def __str__(self): return str(self.student_id) + ", " + self.first_name there used to be an IntegerField, student_id but I removed it. I made the migrations, and everything runs fine, but when I visit the django admin panel, to manually update the database records, I get the following error does anyone know what's going on? I registered the model, in admin.py from django.contrib import admin from .models import Student_Record admin.site.register(Student_Record) -
Creating Django objects with objects in an S3 bucket
I've uploaded a large amount of images to S3, using the awcli utility. I am trying to write a Django management command to iterate over them and create objects in the database for them. So far, I've been able to get the object - but I'm stuck on what I should do to make the appropriate Django object. Obviously this code doesn't work but hopefully sheds some light on what I am trying to do. s3 = boto3.resource('s3', region_name='us-east-2') bucket = s3.Bucket('photo-uploads') object = bucket.Object('00004542/000045420020.jpg') photo = Photo.objects.create(title='Some title', image=object) photo.save() -
How to share 'request.user' with localhost:8000 and subdomain analysis.localhost:8000?
i am building a blog using Django, and i have implemented an analysis tool that allows me to plot details about my visitors (country_origin, device, browser, ...). analysis.localhost:8000 is a subdomain of localhost , defined as a class based view with a custom Mixin SuperuserAccessRequired, that returns a 401 Unauthorized if the user is not staff (i am using django-hosts to handle subdomains & this is my first time working with subdomains.). My issue: if i am logged in on localhost:8000 and naviguate to analysis.localhost:8000 i get the 401 response. You are seeing this as: AnonymousUser # generated by print(You are seeing this as: ', request.user) from SuperuserAccessRequired Unauthorized: / [25/Sep/2019 13:14:03] "GET / HTTP/1.1" 401 89 my humble assumption says that localhost:8000 and x.localhost:8000 are not sharing certain variables. How can i fix this issue, i have read django-hosts documentation like 5 times already and i can't seem to find what i am missing my code : project/root/settings.py ... ALLOWED_HOSTS = ['localhost'] ALLOWED_HOSTS += ['analysis.localhost', 'blog.localhost'] SITE_ID = 1 INSTALLED_APPS += [ # Django Apps 'blog', 'analysis', ] INSTALLED_APPS += [ # Django Dependencies 'sass_processor', 'django_hosts', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'analysis.middleware.TrackVisitorMiddleware', … -
Smiley/emojis and foreign languages in url slug resulting to a server error
I am trying to automatically create slugs derieved from titles inputed by users but I realised that if just a smiley/emoji or foreign language is inserted as the title, i get this error message NoReverseMatch at /images/create/ Reverse for 'detail' with arguments '(277, '')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['images/detail/(?P\d+)/(?P[-\w]+)/$'] Here is my model class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.TextField(max_length=911, blank=False) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() tags = TaggableManager(blank=True) image = models.ImageField(upload_to='') description = models.TextField(blank=True, null=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, class Meta: ordering = ('-created',) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', args=[self.id, self.slug]) Here is my view function @login_required def image_create(request): if request.method == 'POST': form = ImageCreateForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) new_item.user = request.user new_item.save() form.save_m2m() create_action(request.user, '|', new_item) messages.success(request, 'Photo added successfully') return redirect(new_item.get_absolute_url()) else: form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form}) My urls.py urlpatterns = [url(r'^create/$', views.image_create, name='create'), I get NoReverseMatch at /images/create/ Reverse for 'detail' with arguments '(277, '')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['images/detail/(?P\d+)/(?P[-\w]+)/$'] instead of … -
IntegrityError in an atomic block
A Match object can be created/updated through the MatchForm. The save method was overriden in a way that wraps the commitment of the changes in an atomic block. Right after commiting, the state of the object should be checked with the rest of the system. If the check fails, an exception is raised and all changes are undone. That's the whole point of the atomic block. class MatchForm(forms.ModelForm): def save(self, **kwargs): try: with transaction.atomic(): try: slot = copy.copy(self.instance.slot) slot.id = None except AttributeError: slot = None match = self.do_save(**kwargs) if not check(slot=slot): raise Rollback # here is where we raise an exception to roll back all changes return match except Rollback: try: Match.objects.get(pk=self.instance.pk) except Match.DoesNotExist: self.instance.pk = None return False def do_save(self, **kwargs): match = super(AddMatchForm, self).save(commit=False) if not match.venue: match.venue = Venue.unassigned_venue() match.save(**kwargs) self.save_m2m() return match However a few times (and I have no idea how to reproduce it) an IntegrityError happens right at the match.save(**kwargs) when the object is saved to the database. The error message is the following: IntegrityError: insert or update on table "myapp_match" violates foreign key constraint "slot_id_refs_id_610e6c14172cdb45" DETAIL: Key (slot_id)=(43198090) is not present in table "myapp_slot". -
How to upload a csv file through Django form and save it the Django database (Django model)
Bonjour la communauté, Pourriez-vous svp m'aider? Je suis bloqué depuis plusieurs semaines et malgré mes recherches sur le net, je ne trouve une solution qui répond à mon souci. Je souhaiterai à paritr d'un formulaire (Django form) importer un fichier excel ou csv dans ma base de données (Django model). view.py def importation(request): if request.method=='POST': form = TabInfoForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'importation.html', {'form':form}) else: form=TabSourceForm() return render(request, 'importation.html', {'form':form}) model.py class TabSource(models.Model): date=models.DateField() dsp=models.CharField(max_length=30) advertiser=models.CharField(max_length=100) insertion_order=models.CharField(max_length=300) insertion_order_id=models.IntegerField() strategy_name=models.CharField(max_length=300) creative_name=models.CharField(max_length=400) spent_budget=models.DecimalField() impressions=models.IntegerField() clics=models.IntegerField() conversions=models.IntegerField() post_clics_conversions=models.IntegerField() post_view_conversions=models.IntegerField() my_file = models.FileField() def __unicode__(self): return "{} {}".format(self.dsp, self.insertion_order) forms.py class TabSourceForm(forms.ModelForm): class Meta: model=TabSource fields=[ 'my_file', ] importation.html {% load static %} {% block content %} <form class="" action="" method="post" enctype="multipart/form-data">{% csrf_token %} <fieldset><legend>Télécharger le Fichier Datorama</legend> {{ form}} <br><br> <button type="submit" name="button">Upload</button> </fieldset> </form> {% endblock %} -
Wagtail blog post table of contents
Is there a way to create a table of contents for a wagtail site which is being used as a blog. More specifically I want to create a table of contents for each blog post. For example I have created a BlogPost page model containing a StreamField for sections within a blog post. The stream field contains a heading and a rich text field. This allows me to create blog posts with multiple headings / sections. Blog post model: content = StreamField( [("article_section", ArticleSectionBlock())], null=False, blank=False, ) content_panels = Page.content_panels + [ StreamFieldPanel("content"), ] Article Section Block: class ArticleSectionBlock(blocks.StructBlock): sections = blocks.ListBlock( blocks.StructBlock( [ ("header", blocks.CharBlock(required=False)), ("content", blocks.RichTextBlock(required=False)), ] ) ) What I would like to do is be able to create a table of contents at the top of each blog post with links to each section within the post. -
django.conf import settings call in another python package
I install a pyhton package. The package requires django to display html pages. The thing is, I want to use this package in my django project. However, one of the modules imports "from django.conf import settings from django.template import Context, Template". This cause "RuntimeError: Settings already configured". How can I make both settings.py that are imported in my django project and the python package's work seemlessly? if not settings.configured: settings.configure() But this causes problems with my actual django project settings.py templates. I understand that is code is overriding my django project's settings.py. Clearly, this package has its own templates. How can I make sure that my templates are still working while still allowing the template in the package are still working too? Both are needed from my django project. Link to part of the python package that is also importing https://github.com/lambdamusic/Ontospy/blob/master/ontospy/ontodocs/builder.py This is code from the python package that is causing the problem: ONTODOCS_VIZ_TEMPLATES = _dirname + "/media/templates/" ONTODOCS_VIZ_STATIC = _dirname + "/media/static/" if StrictVersion(django.get_version()) > StrictVersion('1.7'): from django.conf import settings from django.template import Context, Template settings.configure() django.setup() settings.TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # insert your TEMPLATE_DIRS here ONTODOCS_VIZ_TEMPLATES + "html-single", ONTODOCS_VIZ_TEMPLATES + "html-multi", ONTODOCS_VIZ_TEMPLATES + "markdown", … -
bulk update not working for filefield upload django
I am trying to update multiple files in fileField in django. I am fetching the objects from the database and i am assigning the new file by iteration over them and then, saving the object in the list. If i use bulk_update it updates all the fields including the FileFields but is not uploading the file and if i iterate over each object and use .save(), then its working fine. But using .save() function hits the database multiple times. So, i need to use bulk_update Code update_list = [] t_obj = FileFieldDetails.objects.filter(ques_key__in=q_key) for t in t_obj.iterator(): t.value = request.FILES[0] update_list.append(t) # Not Working FileFieldDetails.objects.bulk_update(update_list,['value']) # Working for i in update_list: i.save() -
'QuerySet' object has no attribute 'model' with rest_framework_mongoengine
I have been trying to use mongodb with DRF but stuck with this error. I tried this but did not help. Here is my serializer (dmdemo is my app) from rest_framework_mongoengine import serializers from dmdemo.models import Form class FormSerializer(serializers.DocumentSerializer): class Meta: model = Form fields = '__all__' and my viewset from rest_framework_mongoengine.viewsets import ModelViewSet from .serializers import FormSerializer from dmdemo.models import Form class FormViewSet(ModelViewSet): def get_queryset(self): return Form.objects.all() But getting the error 'QuerySet' object has no attribute 'model' I am not finding any leads. Thanks! -
django cannot link a user model and a corresponding from to be used in a template for sign up
I have a custom user model subclassing AbstractBaseUser: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254) username = models.CharField(max_length=254, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = UserManager() def __str__(self): return self.email def get_absolute_url(self): return "/users/%i/" % (self.pk) after migrating, I created a simple form for sign up which I am mapping two fields from the model: email and name like below: class SignUpForm(ModelForm): class Meta: model = CustomUser fields = ['name', 'email'] I then have the view to render a template to show the above fields as input fields: class MyRegisterView(RegisterView): def get(self, request): form = SignUpForm() return render(request, "registration.html", context={"form": form}) and in the template, I am simply doing: <form method="post"> {% csrf_token %} <h3>Sign Up</h3> <div> <label for="name"> <input id = "name" name = "name" class="textfield" type="text" value="" placeholder="Name"> </label> </div> <div> <label for="email"> <input id = "email" name = "email" class="textfield" type="email" value="" placeholder="Email"> </label> (also including passwords and so on) The problem is that when I add the name field and then submit, the name field in the database is not getting populated … -
Getting error in Django: matching query does not exist
So basically, I have a Friend model, and in the model is all the code, and then in the views, I have some code for friends as well, and I am getting this error matching query does not exist. I have tried all the solutions I have found online, however none have worked yet, so I came here to try and find the answer. This is using the latest version of Django. Relevant models.py class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User,related_name='owner',null=True,on_delete=models.CASCADE) @classmethod def make_friend(cls,current_user,new_friend): friend,created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls,current_user,new_friend): friend,created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) This is the relevant views.py Sorry if it's a bit long class PostListView(SelectRelatedMixin,TagMixin,generic.ListView): model = Post template_name = 'mainapp/post_list.html' selected_related = ("user","group") queryset = models.Post.objects.all() def get(self,request): users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() context = { 'users':users,'friends':friends } return render(request, self.template_name, context) def get_context_data(self,**kwargs): context = super(PostListView,self).get_context_data(**kwargs) context['user_groups'] = Group.objects.filter(members__in=[self.request.user.id]) context['all_groups'] = Group.objects.all() return context def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') def change_friends(request,operation,pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user,friend) elif operation == 'remove': Friend.lose_friend(request.user,friend) return redirect('mainapp:post_list') So the actual error is happening in the get() method with the friend = Friend.objects.get(current_user=request.user) line. Here … -
update using django backend and angular fronted with rest framework
im try to edit data stored in django(backend) and angular(fronted), i have the insert and delete but i don't have idea how i can edit that data in django from angular, i using in django rest_framework getUsuarios(): Promise<Usuario[]> { return this.http.get('http://127.0.0.1:8000/users?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Usuario[]) } deleteUsuario(id: number): Promise<void> { const url = `${"http://127.0.0.1:8000/users"}/${id}`; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(() => null) } createUsuario(d: Usuario): Promise<Usuario> { return this.http .post("http://127.0.0.1:8000/users/", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Usuario) } -
Django Template loader doesn't have "get_contents()" function implemented. Is there a substitute?
I am working on upgrading some older Django code however I am running into issues with the loader function "get_contents()" as it has apparently been deprecated. I'm not sure how to proceed. Should I create a new child claqss from that loader and implement the function myself or is there another way? I have basically tried looking this problem up on google and the few answers I've come across have been somewhat vague. I can't show much code, as this is a private project, but I can show one line with the names changed. templateVariable = loader.get_template('appName/filename.txt') This is the error I'm getting when I try and run the function: 'Loader' object has no attribute 'get_contents' -
how to define special Filed in models Django
I am going to write a Django custom Field model to store CardNums. The Field must meet the following requirements: 1. The stored value should never be fully visible - given a CardNum like "GR96 0810 0010 0000 0123 4567 890", the value should be displayed as "---7890" everywhere 2. Superusers should be able to see the full value when needed. -
How to model arbitrarily nested categories and subcategories?
I am looking for an efficient way to model product categories and arbitrarily many nested subcategories in Django for eCommerce purposes. What I currently have now works but it becomes a problem when you want to do a query to get all, say, books because you need to first look up all the subcategories of 'Book' recursively, and then get all books from those subcategories. Let's say you have a primary school math textbook, it would belong to: Books -> Textbooks -> Primary school ...and to get all the books one would have to do a monster query like this: >>> from products.models import Product, Category >>> from django.db.models import Q >>> c = Category(name='Books') >>> c.save() >>> c1 = Category(name='Textbooks', parent=c) >>> c1.save() >>> c2 = Category(name='Primary school', parent=c1) >>> c2.save() >>> p = Product(title='Math textbook', description='Math textbook for 4th grade', price=20, category=c2) >>> p.save() >>> Product.objects.filter(Q(category__name='Books') | Q(category__parent__name='Books') | Q(category__parent__parent__name='Books')) <QuerySet [<Product: Product object (3)>]> ...which is inefficient and you can't know in advance how nested the categories would be. Here is how simplified models look like: class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey('Category', on_delete=models.CASCADE) class Category(models.Model): parent = models.ForeignKey('self', … -
API: Return a list of filtered items within a parent list
The data that is returned is one list with all fields. I want the data to be separated in different lists inside the main list, for example a list of data that applies to the date before today and a list after the date of today. I could write two endpoints and have the data filtered in the queryset, but that would take two separate API calls. The viewset: class StudyPageViewSet(viewsets.ModelViewSet): """ Study create, read, update, delete over API. """ model = Study serializer_class = StudyPageSerializer permission_classes = (IsAuthenticated, IsAuthorPermission,) def get_queryset(self): return Study.on_site.all() The Serializer: class StudyPageSerializer(serializers.ModelSerializer): class Meta: model = Study fields = ('id', 'title', 'date', 'location') read_only_fields = ('id',) Outcome should be like: [ { "list_before_today":[ { "id":"5001", "title":"None" }, { "id":"5002", "title":"Glazed" }, ] }, { "list_after_today":[ { "id":"5003", "title":"None" }, { "id":"5004", "title":"Glazed" }, ] }, ] -
i am learning django websocket everything is working fine except for my JS function in HTML file
I am working on django websocket and creating an Echo app but i don't know why i am getting this error Here is my html code {% load staticfiles %} <html> <head> <title>Notifier</title> <script src="{% static '/channels/js/websocketbridge.js' %}" type="text/javascript"></script> </head> <body> <h1>Notifier</h1> <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect('/ws/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action, stream); }) document.ws = webSocketBridge; /* for debugging */ }) </script> </body> </html> This is my views.py from django.views.generic import TemplateView class HomeView(TemplateView): template_name = "home.html" This is my routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from notifier.consumers import EchoConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/", EchoConsumer), ]) }) Tihs is my counsumers.py from channels.consumer import AsyncConsumer class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): # Echo the same received payload await self.send({ "type": "websocket.send", "text": event["text"] }) Guide me with my mistake where and what i am doing wrong in this whole system i do not find any solution on internet i would expect this code to run properly and do an Echo on my browser console. -
Declare global var en python flask
How can I do to put the variables in the general application? If that tires me error. To avoid declaring name = request.form [name] on each route using Python Flask? -
Django ORM - Group by and annotate with subquery
What I'm trying to do in Django ORM is the following: Group by user Sum the profits Annotate with the latest status of that user My queryset looks like this: Sales.objects.values('user').annotate( profits = Sum('profit'), status = Subquery(Status.objects.filter(username=OuterRef('user')).order_by('-date').values('status')[:1] ).order_by() If I inspect the SQL query of this queryset, I can see that the status field is added to the group by clause. But this query cannot be executed. How can I prevent Django from adding this to the group by clause? Because the rest of the query just works fine. -
Problem editing registry using modelform and filter queryset
I have a problem editing registry using filter select in my model form. To register it works perfectly, but when I try to edit it generates error. Can anybody help me ? I believe the problem is as I expressed this line: form = PostoCapacitacaoForm(request.POST or None, session_om=request.session.get('id_organizacao'), instance=postocapacitacao, ) # views.py def EditarPostoCapacitacaoView(request, pk, template_name='config_geral_posto_capacitacao/update.html'): postocapacitacao = PostoCapacitacao.objects.get(pk=pk) form = PostoCapacitacaoForm(request.POST or None, session_om=request.session.get('id_organizacao'), instance=postocapacitacao, ) if form.is_valid(): temp = form.save(commit=False) temp.author = request.user # add the logged in user, as the temp.save() return redirect('listar_postocapacitacao_url') return render(request, template_name, {'form': form}) # form.py class PostoCapacitacaoForm(ModelForm): def __init__(self, *args, **kwargs): session_om = kwargs.pop('session_om') super(PostoCapacitacaoCadastrarForm, self).__init__(*args, **kwargs) self.fields['cd_posto_diponivel'].queryset = self.fields['cd_posto_diponivel'].queryset = PostoDisponivel.objects.filter( cd_organograma__cd_organizacao=session_om) class Meta: model = PostoCapacitacao fields = ['cd_posto_diponivel', 'cd_capacitacao', 'cd_classificacao'] # exclude = ('cd_organizacao',) widgets = { 'cd_posto_diponivel': Select(attrs={'class': 'form-control', 'required': 'True'}), 'cd_capacitacao': Select(attrs={'class': 'form-control', 'required': 'True'}), 'cd_classificacao': Select(attrs={'class': 'form-control', 'required': 'True'}), } labels = { 'cd_posto_diponivel': ('Setor'), 'cd_capacitacao': ('Código da Capacitação'), 'cd_classificacao': ('Código Classificação'), } -
I keep getting the error of referencing a local variable before assignment! how do I solve this?
thanks for taking the time to help me out. I am writing a web scraping api in django but have been getting a terrible error for the past 5 days! the weird thing is that on macOS there is absolutely NO error and when I deploy to AWS it throws the variable referencing error at me! ubuntu has python 3.6.8 and macOS has python 3.6.6 I have already tried different methods but now I cannot think of any! the scraped data which should be returned returns fine on macOS but on ubuntu I am getting crushed! please help! data_list = [] div_class = scrape_driver_2.find(class_ = 'c1_t2i') daraz_products = scrape_driver.find_all(class_ = 'c2prKC') for data_fragment in daraz_products: # iterate and find all classes data_block = data_fragment.text.strip() # Convert code to text formatted_block = data_block.replace('ADD TO CART', '') second_iterated_block = formatted_block.replace('%', '') third_iterated_block = second_iterated_block.replace(')Pakistan', ')-Pakistan') fourth_iterated_block = third_iterated_block.replace('Pakistan', '-Pakistan') data_list.append(fourth_iterated_block) high_data = [{"Timestamp": time_stamp, "TS Token": ts_token, "Status": sitrep}, data_list] return Response({"data": high_data}) engine_initializer.close() The error I get is : UnboundLocalError at /api/big-budget-filter/ local variable 'high_data' referenced before assignment -
Update django task when model field is changed
I have a django model which contains details of when a particular task (email reminder) should be run for a particular booking. It looks a bit like this:- class Task(models.Model): PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETE = 'complete' STATES = ( (PENDING, 'Pending'), (IN_PROGRESS, 'In Progress'), (COMPLETE, 'Complete') ) run_at = models.DateTimeField() state = models.CharField(max_length=50, choices=STATES, default=PENDING) class Meta: ordering = ['run_at'] When the date of the booking is changed, I want the corresponding task's run_at time to be updated. As far as I can see, there are a few ways I can do this:- In the view code. In the save method of the Task model. Using signals. In general, I think it makes most sense to use the view code - it's more explicit that way. But the code I'm working with is very old and the date of bookings can be changed from all sorts of places in all sorts of ways and I'm not convinced I can be 100% certain that I've caught every single place in which this can happen. If I miss any, the Task won't be updated in that case. Plus, if anyone else adds code that changes booking dates, they'll have …