Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Serializer Error: AttributeError: 'FeedPostSerializer' object has no attribute 'auth_user'
I´m creating a newsfeed in an APP. A user is logged in and sees the posting of other users. Therefore I need two user models (user + auth_users) Now I want to add a boolean field that shows if a post is already liked or not. I already looked at the documentation and other posts here but I can´t find a solution. The auth_user is shown in the response but I can´t included it in the "get_already_liked" function class NewsPostSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(read_only=True) auth_user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) attachments = AttachmentSerializer(read_only=True, many=True) already_liked = serializers.SerializerMethodField() def get_already_liked(self, request): liking_kwargs = { 'post_id': request.id, 'user_id': self.auth_user } if LikePost.objects.filter(**liking_kwargs).exists(): return True else: return False class Meta: model = Post read_only_fields = ( 'id', "user", 'creation_time_stamp', 'auth_user', 'ready_liked', ) fields = ( 'id', 'user', 'creation_time_stamp', 'last_update_time_stamp', 'description', 'attachments', 'already_liked', 'auth_user', ) -
Render JSON in HTML Table with Django/JavaScript
Friends, I need your help! I am new to Python / Django and I am doing this project with the knowledge I get from day to day studying. I have a function in my views.py that communicates with an API and returns a result in Json. The result is basically this: [ { "_id": "5d6f28ec02523e0012a4eae6", "pass": false, "renderSatisfaction": false, "botTimeOut": false, "ignore": false, "exit": false, "errorslog": [], "chaterroslog": [], "Historic": [], "userID": "5b43b8a48b769470363b58909a9049", "user_key": "ABCD", "username": "Igor Miranda", "Created_at": "2019-09-04T03: 01: 00.716Z", "__v": 0 } { "_id": "5d6f291d55d3f500402d338e", "pass": false, "renderSatisfaction": false, "botTimeOut": false, "ignore": false, "exit": false, "errorslog": [], "chaterroslog": [], "Historic": [], "userID": "577a55a043aab2a6aa78586b2520392", "user_key": "ABCD", "username": "Igor Miranda", "Created_at": "2019-09-04T03: 01: 49.484Z", "__v": 0 } ] I need to render this result inside a table in an HTML page with Django, where I have the result of the fields "username", "username_key" and "history". I've read a lot of topics here on StackOverFlow, but I still can't solve my need. Follows my views.py, ConsumimirApi.html files and the result on the page. views.py def ConsumirApi(request): url = 'http://urlapi.test.com.br' body = {"start": "2019-09-04 19:30:00", "end": "2019-09-04 23:59:59"} response = orders.post (url, auth = HTTPBasicAuth ('123456', 'password1234'), headers = {'Content-Type': 'application … -
How can i possibly make a dynamic REST API link of a Model that changes by id of another Model?
What i currently have setted up with django rest is : MODEL NAME : Animes /api/ <- root /api/animes/ <- lists all animes available in my db /api/animes/id/ <- returns the anime instance that has id=id MODEL NAME : Episodes /api/ <- root /api/episodes/ <- lists all episodes of all animes available in my db /api/episodes/id/ <- returns the episode instance that has id=id So basically im trying to achieve is : if i request api/episodes/{anime_name}/ i get that specific anime's Episodes listed . how can i do that ? EpisodesSerializer class EpisodesSerializer(serializers.ModelSerializer): class Meta: model = Episodes fields = '__all__' Router router = routers.DefaultRouter() router.register('animes', AnimesViewSet, 'animes') router.register('episodes', EpisodesViewSet, 'episodes') urlpatterns = router.urls EpisodesViewSet class EpisodesViewSet(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] MainModel = Episodes queryset = Episodes.objects.all() serializer_class = EpisodesSerializer -
How can I add a class automatically in Django?
I would like that every time I create a form with django the tag input includes a specific css class (form-control), to do this I have to write in form.py the following code, adding lines for each field: class InsertItem(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'form-control'}) self.fields['price'].widget.attrs.update({'class': 'form-control'}) Is there a way to force Django to include the css class that I need in every form, without having to write that things for each from and each line? -
Django save method is overwriting field values
I have a model that is overwriting a field value during the save opperation, I don't know if that happens during the communication with the database or its a pure Django problem. My bugged model: class Classificacao(models.Model): item = models.ForeignKey(Item, verbose_name="Item", db_index=True, on_delete=models.CASCADE, db_column='seq_prod') is_valid = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In order to identify the bug I overwrited the save method: def save(self, *args, **kwargs): print(self.is_valid) super(Classificacao, self).save(*args, **kwargs) print(self.is_valid) When I created an instance of the class by the following code the overwrited 'save' prints the above: classificacao_nova = Classificacao.objects.create( item=item, created_at=datetime.datetime.now() ) Output: True False The problem gets worst: in other parts of the code the output is True True. Any ideas of what is going on? PS.: The database default for the is_valid column is 1. -
Nested JSON and HyperlinkedModelSerializer problem
I'm working on a tweet App. I have 2 main models : Tweets and Comments. I'm using HyperlinkedModelSerializer to get absolute url for my comments instances with the "url" added in the field. But when It comes to display the comments inside my tweet JSON format, i have this error : `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. This error is gone when I remove the url from the field. Here is my Comment Model : class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id) return qs class Comment(models.Model): content = models.TextField(max_length=150) author = models.ForeignKey( User, on_delete = models.CASCADE ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(blank=True) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey( "self", on_delete = models.CASCADE, blank=True, null=True ) datestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.content[:30]) def save(self): self.object_id = self.parent.id super(Comment, self).save() def children(self): return Comment.objects.filter(parent=self) @property def is_parent(self): if self.parent is None: return False return True Here is my comment serializer : class CommentSerializer(serializers.HyperlinkedModelSerializer): children = serializers.SerializerMethodField() datestamp = serializers.SerializerMethodField() def get_datestamp(self, obj): return obj.datestamp.date() def get_children(self, obj): qs = obj.children() return ChildrenCommentSerializer(qs, many=True).data class Meta: model = … -
Django Post Request to Detail Page (Id)
I want to make a Django post request to specific url with a pk. So I have a list of projects and inside every project there are tasks. I want to add a task to that specific project. This is the View function to create a normal project: @login_required def create_project(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') parent_assignment = Assignment.objects.get(pk=request.POST.get('Studyplan-PAID')) usernames = request.POST.getlist('Studyplan-Canview') users = User.objects.filter(username__in=usernames) userprofiles = UserProfile.objects.filter(user__in=users) project = Project(name=name, description=description, parent_assignment=parent_assignment) project.save() project.canview.set(userprofiles) project.members.set(userprofiles) return redirect('allProjects') This is the project: When I tap this I get a detail page with a lot of tasks: This is a task: So as you can see every project has multiple tasks: This is my attempt at doing a post request to tasks. My problem is that the task is not connected to the id of the project: @login_required def create_task(request): if request.method == 'POST': name = request.POST.get('Studyplan-Name') description = request.POST.get('Studyplan-Description') usernames = request.POST.getlist('Studyplan-Canview') users = User.objects.filter(username__in=usernames) userprofiles = UserProfile.objects.filter(user__in=users) task = Task(name=name, description=description, state="new") task.save() task.canview.set(userprofiles) task.workers.set(userprofiles) return redirect('allaStudieplaner') So this is aa picture from the admin page. I am inside the project and I want the task to be selected here: -
Setted attribute with setattr is different type than given value in Python (Django)
Since ArrayField does not work with FileField in Django, I'm trying to fix it. However, I came up to a line of code, where I don't understand, how it happens, that setted attribute using setattr becomes different type than given value. To be exact - if I add print lines to code: print(data) setattr(instance, self.name, data or '') # line 317 print(getattr(instance, self.name) Here's what I get when I save a Model with FileField: <class 'django.core.files.uploadedfile.TemporaryUploadedFile'> <class 'django.db.models.fields.files.FieldFile'> What happens here? -
Google Vision API error when I push on Heroku
I have the following problem: I performed all the configuration as per Google Cloud documentation The credentials are validated and I can read the images by their url normally. It works fine, but only when it is on localhost, when it goes into production (heroku) does it simply stop working, returning error 503 - service unavailable. It makes no sense because in localhost it works perfectly. Do I need to set up something in my Google Cloud account or something? I really don't know what to do anymore. -
django create count subquery without groupby
I want to use a query thatn could be used as qubquery. But I noticed that query like this: x = Deal.all_objects.filter(state='created').values('id').annotate(cnt=Count('id')).values('cnt') produces SELECT COUNT("deals_deal"."id") AS "cnt" FROM "deals_deal" WHERE "deals_deal"."state" = created GROUP BY "deals_deal"."id" I dont need the GROUP BY, I jost want to count offers that match filter. I dont want to use .count() because It would not let me to write a query like this: Deal.all_objects.filter( Q(creator=OuterRef('pk')) | Q(taker=OuterRef('pk'), state='completed') ).annotate(cnt=Count('pk')).values('cnt') How to modify above query so that it count without GROUP BY? -
How we can auto generate reciept number using python django and that reciept number into json object
i have JSONField instalment_1 . I have to calculate reciept for each instalment. please help me here -
How change urls dynamically based on chosen language prefix
I have 2 languages in Django project. Base is site/pl/ and 2nd is site/en. There are also 2 buttons in header.html to switch language (add prefix to url). String translation works fine. My problems are: 1. When I switch(click button) between languages I want to load home page because right know it works only when I am at home page - so if I move to any subpage and click to language button it reload same page (not home). 2. When I switch between languages I want to change also subpages urls to right names. I try some weird way to made this: <li><a href="{{baseurl}}">PL</a></li> <li><a href="{{en_url}}">EN</a></li> and then in views: def index(request, *args, **kwargs): baseurl = '/' en_url = baseurl + 'en' return render(request, 'home.html', {'baseurl': baseurl, 'en_url': en_url}) But I assume it's bad. Here my code: views.py def index(request, *args, **kwargs): return render(request, 'home.html') def about(request, *arg, **kwargs): return render(request, 'about.html') def offer(request, *arg, **kwargs): return render(request, 'offer.html') def contact(request, *arg, **kwargs): return render(request, 'contact.html') app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('o-nas', views.about, name='about'), path('oferta', views.offer, name='offer'), path('kontakt', views.contact, name='contact'), ] in header.html <li><a href="{% url 'index' %}">PL</a></li> … -
How to get compact html code in page source? Django, html
I am sorry if the title is not very precise but I don't know how to define it correctly. I use many tags in my template, so my code after previewing the page has a lot of empty spaces. How can I get the code compact like on the example below (examplefor google browser): [...] startsWith",function(a){return a?a:function(e,c){if(null==this)throw new TypeError("The 'this' value for String.prototype.startsWith must not be null or undefined");if(e instanceof RegExp)throw new TypeError("First argument to String.prototype.startsWith must not be a regular expression");var b=this+"";e+="";for(var f=b.length,d=e.length,h=Math.max(0,Math.min(c|0,b.length)),g=0;g<d&&h<f;)if(b[h++]!=e[g++])return!1;return g>=d}});google.arwt=function(a){a.href=document.getElementById(a.id.substring(a.id.startsWith("vcs")?3:1)).href;return!0};(function(){var g=function(a,b){this.g=a===e&&b||"";this.i=f};g.prototype.l=!0;g.prototype.j=function(){return this.g.toString()};var h=/^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i,f={},e={};var l=/^((market|itms|intent|itms-appss):\/\/)/i,m=function(a){var b;a instanceof g||!l.te [...] The code after choosing the view page source option does not contain any spaces. Why does Google and many other websites use this solution and what is its proper name? -
Field name `username` is not valid for model `User` django rest-auth
i am trying to use django rest_auth login with email : serializers.py: from rest_framework import serializers from users.models import User from rest_auth.serializers import LoginSerializer class CustomLoginSerializer(LoginSerializer): username = None email = serializers.EmailField(required = True) password1 = serializers.CharField(write_only = True) class Meta: model = User fields = ('email','password') imported the loginview: from rest_auth.views import LoginView class CustomLoginView(LoginView): queryset = User.objects.all() i have created custom user modal with email so as the error shows username is valid but how can i remove from login. when i run the localhost:8000/rest-auth/login i am getting email and password view but after login it showing this: Field name `username` is not valid for model `User` -
Class 'Item' has no 'Objects' memberpylint(no-member)
I'm trying to import the model into my views but somehow it's giving me an error "Class 'Item' has no 'Objects' memberpylint(no-member)". I don't understand why? views.py from django.shortcuts import render from .models import Item # def products(request): # context = { # 'items': Item.objects.all() # } # return render(request, "products.html", context) def item_list(request): context = { 'items': Item.Objects.all() } return render(request, "home-page.html", context) def checkout(request): return render(request, "checkout.html") here's my model for that from django.conf import settings from django.db import models CATEGORY_CHOICES = ( ('S', 'Shirt'), ('SW', 'Sportswear'), ('OW', 'Outwear') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): title = models.CharField(max_length = 100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) def _str_(self): return self.title class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length = 100) def _str_(self): return self.title class Order(models.Model): title = models.CharField(max_length = 100) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def _str_(self): return self.title Can anyone tell me what's it I'm doing wrong? Same with the product function when I try to call the Item it's giving me the same error. That's why I commented out. -
Overriding Django admin inlines formset will not save more than 1 row
I have a straight forward admin.ModelAdmin class with an inlines, of which I am overriding the form and formsets with a forms.Model and BaseInlineFormset to add a custom field. I have a custom jQuery script that gets loaded in and whenever a machine is picked from the select2 drop-down it runs an AJAX query to the REST API and grabs the items based on a foreign key value and populates the CleaningEntryInline with information. However, upon saving it is only posting a single record to the database. class CleaningEntryInline(admin.TabularInline): model = CleaningEntry form = CleaningEntryForm formset = CleaningEntryFormSet extra = 0 raw_id_fields = ['cleaning_item'] fieldsets = [ (None,{'fields':[('cleaning_item','cleaning_action', 'checked', 'na', 'notes')]}) ] template = 'admin/quality/cleaningentry/edit_inline/tabular_actions.html' class CleaningLogAdmin(admin.ModelAdmin): ####Save model function override to make and save QC Lab user and make uneditable. def save_model(self, request, obj, form, change): obj.lab_user = request.user.username obj.save() list_display = ['machine_used','get_product_info','lot_num','start_time','lab_user'] list_filter = ['machine_used'] readonly_fields = ['lab_user', 'cleaning_users'] search_fields = ['machine_cleaned', 'lot_num', 'recipe_cleaned__recipe_name__item_code', 'lab_user'] autocomplete_fields = ['machine_used','recipe_cleaned'] fieldsets = [ ('Cleaning Info',{'fields':[('machine_used', 'recipe_cleaned', 'lot_num')]}), (None,{'fields':[('start_time')]}), (None,{'fields':[('clean_time', 'lab_user')]}) ] inlines = [CleaningUserInline, CleaningEntryInline] change_list_template = 'admin/quality/cleaninglog/change_list.html' list_per_page = 25 form = CleaningEntryForm class Media: js = ( 'admin/js/vendor/jquery/jquery.min.js', 'admin/js/jquery.init.js', 'admin/js/list_filter_collaspe.js', 'admin/js/equipaction_filter.js', ) css = {'all':( 'admin/css/vendor/select2/select2.css', ) } … -
ImportError: No module named. Worker failed to boot
I am trying to get gunicorn working with my Nginx but it just can't seem to see the WSGI.py file. I tried different combinations of my project name and with different paths. This is how my wsgi.py file looks like: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'voopglobal.settings') application = get_wsgi_application() It should ideally say "Booting worker with PID and a PID number" but it gives me an error instead. ubuntu@ip-172-31-25-61:~/voop-global-it-project/voopglobal$ gunicorn voopglobal.wsgi [2019-09-10 12:01:01 +0000] [27716] [INFO] Starting gunicorn 19.7.1 [2019-09-10 12:01:01 +0000] [27716] [INFO] Listening at: http://127.0.0.1:8000 (27716) [2019-09-10 12:01:01 +0000] [27716] [INFO] Using worker: sync [2019-09-10 12:01:01 +0000] [27720] [INFO] Booting worker with pid: 27720 [2019-09-10 12:01:01 +0000] [27720] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 377, in import_app __import__(module) File "/home/ubuntu/voop-global-it-project/voopglobal/voopglobal/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi [2019-09-10 12:01:01 +0000] [27720] [INFO] Worker exiting (pid: … -
Using foreign keys on the same model, but on two different fields
If this question is stupid I'm sorry, but I couldn't really find anything useful on Google. So I have a model made up of two fields. I want to create a model with some other fields, but two of them should be the ones from the previous one. Is there any way to obtain this? Code: from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE) meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE) dataSolicitare = models.DateField(default=date.today) denumireMeserie = models.CharField(max_length=50) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return self.cor I thought this might work, but I get these errors: from django.db import models from django.contrib.auth.models import User from datetime import date from .validators import validate_file_size # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE) meserie = models.ForeignKey(CORMeserii, … -
Not Found: /media/media/photos/e.jpg in django
I've deployed one project In web server. our project everything fine but i unable print image on profile page .in our local system working fine but in server error getting Not Found: /media/media/photos/e.jpg in django. models.py class Matr(models.Model): photo = models.ImageField(upload_to='media/photos/', null=True, blank=True) settings.py MIDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) profile.html {% if user.matr.photo %} <img src="{{ user.matr.photo.url }}" width="330"> {% endif %} -
Is there a better way to write output of background tasks to the database?
first of all thx for reading. In my project, I have azure-function / azure webjob to do the parsing,analysis of the raw data when it comes to the storage account. The output will be update to database with direct sql command like: sql_update = """UPDATE "PrototypeOne" SET files_amount =%s, used_time = %s where "User_Name" =%s;""" cursor.execute(sql_update,vars) My questions are: 1, is there a smarter way to update the database? can my backend play some role in between? 2, Is there a pub/sub library for such 'script level' application? Background: My backend is django 2.0+, with postgresql as database on azure. -
connect assets uploaded in anonymous mode post login
I am building a web app where user can upload a file in logged out mode but expects the file to be associated with him post login in the same session. The way I have implemented is to attach both a session_key and a User to the model as follows class Asset(Model): id = BigAutoField(primary_key=True) file = FileField(upload_to=get_file_path) submission_time = DateTimeField(auto_now_add=True, blank=False) expiration_time = DateTimeField(default=some_method) session = CharField(max_length=1024) user = ForeignKey( User, on_delete=CASCADE, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", blank=True, null=True) def __str__(self): return self.file.name When the user first uploads the Asset, I capture the same and store it in backend with session_key. Once users confirms his willingness to post this Asset to share with community by doing signup/login, I match the Asset's session key with current session key and updates the user field in the Asset model. Is this the best approach? Does this approach have any security loopholes here? -
Upload an html file to a Google disk using api
There's a view that forms the body of an html document and and gives it to the new page of the site (url like - http://localhost/cv/4/html/) view.py class CvView(AuthorizedMixin, View): def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) return HttpResponse(data, content_type=content_type) urls.py path('cv/<int:employee_id>/<str:format_>/', CvView.as_view(), name='cv'), variable data passed to HttpResponse contains a complete html document <!DOCTYPE html> <html lang="en"> <head> ..... </head> <body> ..... </body> I need to pass this document to the google drive for opening.To do that, I'm using Google API Client. The function for creating a document opening is as follows def file_to_drive(import_file=None): SCOPES = 'https://www.googleapis.com/auth/drive' creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. ..... ..... # GET PERMISSIONS ..... ..... service = build('drive', 'v3', credentials=creds) # Call the Drive v3 API file_metadata = {'name': 'test.html'} media = MediaFileUpload(import_file, mimetype='text/html') file = service.files().create(body=file_metadata, media_body=media, fields='id') response = None while response is None: status, response = file.next_chunk() … -
Is it safe to use auth_user for regular website users?
I want to create a website where people can post things using accounts. It should also be possible to login with google (or other) OAuth, where I would basicly create an auth_user for them using googles tokens. So is it safe to use djangos preexisting user and group system for regular everyday users of my website by just denoting them without staff or superuser priviledges? Also can I just link the google token to an auth_user and start a session for him that way? Or should I implement my own user and group system? -
Django Prepopulate Class Based CreateView Form Attribute with currently logged in username
I Need to Restrict the Options in a Select Field of a Django Form for not staff users. So theses are my models.py: #!/usr/bin/python3 from django.db import models from django.urls import reverse class Extension(models.Model): username = models.CharField(primary_key=True, max_length=200, help_text='') callerid = models.CharField(max_length=200, help_text='') extension = models.CharField(max_length=3, help_text='') firstname = models.CharField(max_length=200, help_text='') lastname = models.CharField(max_length=200, help_text='') password = models.CharField(max_length=200, help_text='') context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True) def get_absolute_url(self): return reverse('extension-detail', args=[str(self.username)]) def my_get_absolute_url(self): return reverse('my-extension-detail', args=[str(self.username)]) def __str__(self): return self.username class Context(models.Model): name = models.CharField(primary_key=True, max_length=200, help_text='') countryprefix = models.CharField(max_length=200, help_text='') cityprefix = models.CharField(max_length=200, help_text='') number = models.CharField(max_length=200, help_text='') extensionsfrom = models.CharField(max_length=200, help_text='') extensionstill = models.CharField(max_length=200, help_text='') portscount = models.CharField(max_length=200, help_text='') def get_absolute_url(self): return reverse('context-detail', args=[str(self.name)]) def my_get_absolute_url(self): return reverse('my-context-detail', args=[str(self.name)]) def __str__(self): return self.name views.py: #!/usr/bin/python3 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.contrib.auth.models import Permission from catalog.models import Extension, Context from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView from django.views.generic.list import ListView class ExtensionCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Extension fields = '__all__' permission_required = 'catalog.add_extension' class ExtensionUpdate(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): model = Extension fields = '__all__' permission_required = 'catalog.change_extension' class ExtensionDelete(LoginRequiredMixin, PermissionRequiredMixin, DeleteView): model = Extension success_url = reverse_lazy('extensions') permission_required = 'catalog.delete_extension' … -
How to increment django DB using cookies
I am trying to increment my DB by 1 if a user has not visited that unique item.pk before. At the moment it will only increment by 1 for all items in my DB, id like to to increment by 1 for each item.pk in the DB. def bug_detail(request, pk): """ Create a view that returns a single bug object based on the bug ID (pk) and render it to the bug_detail.html template or return 404 error if object is not found Also handles commenting on the bug as well as regulating the amount of views attributed to the bug. """ bug = get_object_or_404(Bug, pk=pk) if request.method == "POST": form = BugCommentForm(request.POST) if form.is_valid(): bugComment = form.save(commit=False) bugComment.bug = bug bugComment.author = request.user bug.comment_number += 1 bug.save() bugComment.save() return redirect(reverse('bug_detail', kwargs={'pk': pk})) else: messages.error( request, "Looks like your comment is empty!", extra_tags="alert-danger") form = BugCommentForm(instance=bug) return redirect(reverse('bug_detail', kwargs={'pk': pk})) else: form = BugCommentForm() comments = BugComment.objects.filter(bug__pk=bug.pk) comments_total = len(comments) response = render(request, 'bug_detail.html', {'bug': bug, 'comments': comments, 'comments_total': comments_total, 'form': form}) if 'last_visit' in request.COOKIES and 'bugg' in request.COOKIES: last_visit = request.COOKIES['last_visit'] # the cookie is a string - convert back to a datetime type last_visit_time = datetime.strptime( last_visit[:-7], "%Y-%m-%d …